diff --git a/.gitea/workflows/ci.yml b/.gitea/workflows/ci.yml index 408996f..27c8697 100644 --- a/.gitea/workflows/ci.yml +++ b/.gitea/workflows/ci.yml @@ -27,7 +27,7 @@ jobs: - uses: pnpm/action-setup@v4 - uses: actions/setup-node@v4 with: - node-version: 22 + node-version: 24.22.1 cache: pnpm - run: pnpm install --frozen-lockfile - run: pnpm -r build diff --git a/.gitea/workflows/desktop-release.yml b/.gitea/workflows/desktop-release.yml index b59d3e3..9356f24 100644 --- a/.gitea/workflows/desktop-release.yml +++ b/.gitea/workflows/desktop-release.yml @@ -45,7 +45,7 @@ jobs: - uses: pnpm/action-setup@v4 - uses: actions/setup-node@v4 with: - node-version: 22 + node-version: 24.22.1 - uses: dtolnay/rust-toolchain@stable - name: Both Mac processors (universal app) if: runner.os == 'macOS' diff --git a/.nvmrc b/.nvmrc index 2bd5a0a..ce62013 100644 --- a/.nvmrc +++ b/.nvmrc @@ -1 +1 @@ -22 +24.22.1 diff --git a/Cargo.lock b/Cargo.lock index 33cfc00..45834b9 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2,12 +2,81 @@ # It is not intended for manual editing. version = 4 +[[package]] +name = "ab_glyph" +version = "0.2.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "01c0457472c38ea5bd1c3b5ada5e368271cb550be7a4ca4a0b4634e9913f6cc2" +dependencies = [ + "ab_glyph_rasterizer", + "owned_ttf_parser", +] + +[[package]] +name = "ab_glyph_rasterizer" +version = "0.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "366ffbaa4442f4684d91e2cd7c5ea7c4ed8add41959a31447066e279e432b618" + [[package]] name = "adler2" version = "2.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" +[[package]] +name = "aead" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d122413f284cf2d62fb1b7db97e02edb8cda96d769b16e443a4f6195e35662b0" +dependencies = [ + "crypto-common", + "generic-array", +] + +[[package]] +name = "aes" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b169f7a6d4742236a0a00c541b845991d0ac43e546831af1249753ab4c3aa3a0" +dependencies = [ + "cfg-if", + "cipher", + "cpufeatures", +] + +[[package]] +name = "aes-gcm" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "831010a0f742e1209b3bcea8fab6a8e149051ba6099432c8cb2cc117dec3ead1" +dependencies = [ + "aead", + "aes", + "cipher", + "ctr", + "ghash", + "subtle", +] + +[[package]] +name = "aligned" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee4508988c62edf04abd8d92897fca0c2995d907ce1dfeaf369dac3716a40685" +dependencies = [ + "as-slice", +] + +[[package]] +name = "aligned-vec" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc890384c8602f339876ded803c97ad529f3842aba97f6392b3dba0dd171769b" +dependencies = [ + "equator", +] + [[package]] name = "alloc-no-stdlib" version = "2.0.4" @@ -23,18 +92,159 @@ dependencies = [ "alloc-no-stdlib", ] +[[package]] +name = "allocator-api2" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923" + +[[package]] +name = "android_system_properties" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae221649c9976a6f6c56ae1facf410f3ddb33cc661c4b7b61020a912d4237fbc" +dependencies = [ + "libc", +] + +[[package]] +name = "anyhow" +version = "1.0.104" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" + +[[package]] +name = "arbitrary" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3bc62ac97cc33321f50863d514c3bc38a453947a8f9e781137e47c7401020aed" + +[[package]] +name = "arg_enum_proc_macro" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ae92a5119aa49cdbcf6b9f893fe4e1d98b04ccbf82ee0584ad948a44a734dea" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "arrayvec" +version = "0.7.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3fb67a6e08acf24fdeccbac2cb6ac4305825bd1f117462e0e6f2f193345ad56" + +[[package]] +name = "as-slice" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "516b6b4f0e40d50dcda9365d53964ec74560ad4284da2e7fc97122cd83174516" +dependencies = [ + "stable_deref_trait", +] + +[[package]] +name = "ash" +version = "0.38.0+1.3.281" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bb44936d800fea8f016d7f2311c6a4f97aebd5dc86f09906139ec848cf3a46f" +dependencies = [ + "libloading", +] + [[package]] name = "autocfg" version = "1.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" +[[package]] +name = "av-scenechange" +version = "0.14.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0f321d77c20e19b92c39e7471cf986812cbb46659d2af674adc4331ef3f18394" +dependencies = [ + "aligned", + "anyhow", + "arg_enum_proc_macro", + "arrayvec", + "log", + "num-rational", + "num-traits", + "pastey", + "rayon", + "thiserror", + "v_frame", + "y4m", +] + +[[package]] +name = "av1-grain" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8cfddb07216410377231960af4fcab838eaa12e013417781b78bd95ee22077f8" +dependencies = [ + "anyhow", + "arrayvec", + "log", + "nom", + "num-rational", + "v_frame", +] + +[[package]] +name = "avif-serialize" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7178fe5f7d460b13895ebb9dcb28a3a6216d2df2574a0806cb51b555d297f38" +dependencies = [ + "arrayvec", +] + +[[package]] +name = "base16ct" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4c7f02d4ea65f2c1853089ffd8d2787bdbc63de2f0d29dedbcf8ccdfa0ccd4cf" + +[[package]] +name = "base64ct" +version = "1.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06" + +[[package]] +name = "bit-set" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2f926cc3060f09db9ebc5b52823d85268d24bb917e472c0c4bea35780a7d" +dependencies = [ + "bit-vec", +] + +[[package]] +name = "bit-vec" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b71798fca2c1fe1086445a7258a4bc81e6e49dcd24c8d0dd9a1e57395b603f51" + [[package]] name = "bitflags" version = "2.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" +[[package]] +name = "bitstream-io" +version = "4.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7eff00be299a18769011411c9def0d827e8f2d7bf0c3dbf53633147a8867fd1f" +dependencies = [ + "no_std_io2", +] + [[package]] name = "block-buffer" version = "0.10.4" @@ -44,6 +254,15 @@ dependencies = [ "generic-array", ] +[[package]] +name = "block2" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cdeb9d870516001442e364c5220d3574d2da8dc765554b4a617230d33fa58ef5" +dependencies = [ + "objc2", +] + [[package]] name = "brotli-decompressor" version = "5.0.3" @@ -54,6 +273,12 @@ dependencies = [ "alloc-stdlib", ] +[[package]] +name = "built" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c0e531d93d39c34eef561e929e8a7f86d77a5af08aac4f6d6e39976c51858e9" + [[package]] name = "bumpalo" version = "3.20.3" @@ -86,18 +311,86 @@ version = "0.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8f1fe948ff07f4bd06c30984e69f5b4899c516a3ef74f34df92a2df2ab535495" +[[package]] +name = "cc" +version = "1.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "877bf67ac8e52449eb2f9e98a344ea163beb70dd1f9eebe3cc5357dcfeaee4df" +dependencies = [ + "find-msvc-tools", + "jobserver", + "libc", + "shlex", +] + [[package]] name = "cfg-if" version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" +[[package]] +name = "cfg_aliases" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527" + +[[package]] +name = "chacha20" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3613f74bd2eac03dad61bd53dbe620703d4371614fe0bc3b9f04dd36fe4e818" +dependencies = [ + "cfg-if", + "cipher", + "cpufeatures", +] + +[[package]] +name = "chacha20poly1305" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10cd79432192d1c0f4e1a0fef9527696cc039165d729fb41b3f4f4f354c2dc35" +dependencies = [ + "aead", + "chacha20", + "cipher", + "poly1305", + "zeroize", +] + +[[package]] +name = "cipher" +version = "0.4.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad" +dependencies = [ + "crypto-common", + "inout", + "zeroize", +] + +[[package]] +name = "codespan-reporting" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af491d569909a7e4dee0ad7db7f5341fef5c614d5b8ec8cf765732aba3cff681" +dependencies = [ + "unicode-width", +] + [[package]] name = "color_quant" version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3d7b894f5411737b7867f4827955924d7c254fc9f4d91a6aad6b097804b1018b" +[[package]] +name = "const-oid" +version = "0.9.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2459377285ad874054d797f3ccebf984978aa39129f6eafde5cdc8315b612f8" + [[package]] name = "cpufeatures" version = "0.2.17" @@ -107,6 +400,11 @@ dependencies = [ "libc", ] +[[package]] +name = "craft-docpath" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=82a24b006eefa036b43c09a67fb9a3fbd17ffe63#82a24b006eefa036b43c09a67fb9a3fbd17ffe63" + [[package]] name = "crc32fast" version = "1.5.2" @@ -147,6 +445,18 @@ version = "0.2.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5" +[[package]] +name = "crypto-bigint" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0dc92fb57ca44df6db8059111ab3af99a63d5d0f8375d9972e319a379c6bab76" +dependencies = [ + "generic-array", + "rand_core 0.6.4", + "subtle", + "zeroize", +] + [[package]] name = "crypto-common" version = "0.1.7" @@ -157,6 +467,53 @@ dependencies = [ "typenum", ] +[[package]] +name = "ctr" +version = "0.9.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0369ee1ad671834580515889b80f2ea915f23b8be8d0daa4bbaf2ac5c7590835" +dependencies = [ + "cipher", +] + +[[package]] +name = "curve25519-dalek" +version = "4.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "97fb8b7c4503de7d6ae7b42ab72a5a59857b4c937ec27a3d4539dba95b5ab2be" +dependencies = [ + "cfg-if", + "cpufeatures", + "curve25519-dalek-derive", + "digest", + "fiat-crypto", + "rustc_version", + "subtle", + "zeroize", +] + +[[package]] +name = "curve25519-dalek-derive" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f46882e17999c6cc590af592290432be3bce0428cb0d5f8b6715e4dc7b383eb3" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "der" +version = "0.7.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7c1832837b905bbfb5101e07cc24c8deddf52f93225eee6ead5f4d63d53ddcb" +dependencies = [ + "const-oid", + "pem-rfc7468", + "zeroize", +] + [[package]] name = "digest" version = "0.10.7" @@ -164,7 +521,66 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" dependencies = [ "block-buffer", + "const-oid", "crypto-common", + "subtle", +] + +[[package]] +name = "dispatch2" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e0e367e4e7da84520dedcac1901e4da967309406d1e51017ae1abfb97adbd38" +dependencies = [ + "bitflags", + "objc2", +] + +[[package]] +name = "document-features" +version = "0.2.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d4b8a88685455ed29a21542a33abd9cb6510b6b129abadabdcef0f4c55bc8f61" +dependencies = [ + "litrs", +] + +[[package]] +name = "ecdsa" +version = "0.16.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee27f32b5c5292967d2d4a9d7f1e0b0aed2c15daded5a60300e4abb9d8020bca" +dependencies = [ + "der", + "digest", + "elliptic-curve", + "rfc6979", + "signature", + "spki", +] + +[[package]] +name = "ed25519" +version = "2.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "115531babc129696a58c64a4fef0a8bf9e9698629fb97e9e40767d235cfbcd53" +dependencies = [ + "pkcs8", + "signature", +] + +[[package]] +name = "ed25519-dalek" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "70e796c081cee67dc755e1a36a0a172b897fab85fc3f6bc48307991f64e4eca9" +dependencies = [ + "curve25519-dalek", + "ed25519", + "serde", + "sha2", + "subtle", + "zeroize", ] [[package]] @@ -173,6 +589,53 @@ version = "1.19.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be" +[[package]] +name = "elliptic-curve" +version = "0.13.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b5e6043086bf7973472e0c7dff2142ea0b680d30e18d9cc40f267efbf222bd47" +dependencies = [ + "base16ct", + "crypto-bigint", + "digest", + "ff", + "generic-array", + "group", + "hkdf", + "pem-rfc7468", + "pkcs8", + "rand_core 0.6.4", + "sec1", + "subtle", + "zeroize", +] + +[[package]] +name = "equator" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4711b213838dfee0117e3be6ac926007d7f433d7bbe33595975d4190cb07e6fc" +dependencies = [ + "equator-macro", +] + +[[package]] +name = "equator-macro" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "44f23cf4b44bfce11a86ace86f8a73ffdec849c9fd00a386a53d278bd9e81fb3" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "equivalent" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" + [[package]] name = "fax" version = "0.2.7" @@ -188,6 +651,28 @@ dependencies = [ "simd-adler32", ] +[[package]] +name = "ff" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c0b50bfb653653f9ca9095b427bed08ab8d75a137839d9ad64eb11810d5b6393" +dependencies = [ + "rand_core 0.6.4", + "subtle", +] + +[[package]] +name = "fiat-crypto" +version = "0.2.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "28dea519a9695b9977216879a3ebfddf92f1c08c05d984f8996aecd6ecdc811d" + +[[package]] +name = "find-msvc-tools" +version = "0.1.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48" + [[package]] name = "flate2" version = "1.1.10" @@ -199,6 +684,21 @@ dependencies = [ "zlib-rs", ] +[[package]] +name = "foldhash" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" + +[[package]] +name = "font-types" +version = "0.12.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "835ae9d781464a79026cde387f9cbc650c9a4909d7cf7e658b127e3c35d2f35d" +dependencies = [ + "bytemuck", +] + [[package]] name = "futures-core" version = "0.3.34" @@ -231,6 +731,51 @@ checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" dependencies = [ "typenum", "version_check", + "zeroize", +] + +[[package]] +name = "getrandom" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" +dependencies = [ + "cfg-if", + "libc", + "wasi", +] + +[[package]] +name = "getrandom" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd" +dependencies = [ + "cfg-if", + "libc", + "r-efi 5.3.0", + "wasip2", +] + +[[package]] +name = "getrandom" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" +dependencies = [ + "cfg-if", + "libc", + "r-efi 6.0.0", +] + +[[package]] +name = "ghash" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0d8a4362ccb29cb0b265253fb0a2728f592895ee6854fd9bc13f2ffda266ff1" +dependencies = [ + "opaque-debug", + "polyval", ] [[package]] @@ -243,6 +788,31 @@ dependencies = [ "weezl", ] +[[package]] +name = "gpu-allocator" +version = "0.28.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "51255ea7cfaadb6c5f1528d43e92a82acb2b96c43365989a28b2d44ee38f8795" +dependencies = [ + "ash", + "hashbrown 0.16.1", + "log", + "presser", + "thiserror", + "windows", +] + +[[package]] +name = "group" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0f9ef7462f7c099f518d754361858f86d8a07af53ba9af0fe635bbccb151a63" +dependencies = [ + "ff", + "rand_core 0.6.4", + "subtle", +] + [[package]] name = "half" version = "2.7.1" @@ -251,9 +821,60 @@ checksum = "6ea2d84b969582b4b1864a92dc5d27cd2b77b622a8d79306834f1be5ba20d84b" dependencies = [ "cfg-if", "crunchy", + "num-traits", "zerocopy", ] +[[package]] +name = "harfrust" +version = "0.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c03d949a14aa089bbb282f7dd76a498a7f684428e4257202efc119ec010376f9" +dependencies = [ + "bitflags", + "bytemuck", + "read-fonts", + "smallvec", +] + +[[package]] +name = "hashbrown" +version = "0.16.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100" +dependencies = [ + "allocator-api2", + "equivalent", + "foldhash", +] + +[[package]] +name = "hashbrown" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" +dependencies = [ + "foldhash", +] + +[[package]] +name = "hkdf" +version = "0.12.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b5f8eb2ad728638ea2c7d47a21db23b7b58a72ed6a38256b8a1849f15fbbdf7" +dependencies = [ + "hmac", +] + +[[package]] +name = "hmac" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e" +dependencies = [ + "digest", +] + [[package]] name = "image" version = "0.25.10" @@ -283,12 +904,73 @@ dependencies = [ "quick-error", ] +[[package]] +name = "imgref" +version = "1.12.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e44b0a4eaa4c82f441d50a963f2d5f05a787240aeee097597033e72accfd22f" + +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown 0.17.1", +] + +[[package]] +name = "inout" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "879f10e63c20629ecabbb64a8010319738c66a5cd0c29b02d63d272b03751d01" +dependencies = [ + "generic-array", +] + +[[package]] +name = "interpolate_name" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c34819042dc3d3971c46c2190835914dfbe0c3c13f61449b2997f4e9722dfa60" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "itertools" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b192c782037fadd9cfa75548310488aabdbf3d2da73885b31bd0abd03351285" +dependencies = [ + "either", +] + [[package]] name = "itoa" version = "1.0.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" +[[package]] +name = "jixel" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "278a75e12caacec34be774d62ad05e45fc0b6a52d1f4e9f7fbc0209ecdf794f3" + +[[package]] +name = "jobserver" +version = "0.1.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c00acbd29eabad4a2392fa0e921c874934dbbf4194312ad20f04a0ed67a3cb3" +dependencies = [ + "getrandom 0.4.3", + "libc", +] + [[package]] name = "jpeg-decoder" version = "0.3.2" @@ -491,6 +1173,15 @@ dependencies = [ "tracing", ] +[[package]] +name = "lazy_static" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb" +dependencies = [ + "spin", +] + [[package]] name = "libc" version = "0.2.190" @@ -498,20 +1189,67 @@ 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" +name = "libfuzzer-sys" +version = "0.4.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a9fd2f41a1cba099f79a0b6b6c35656cf7c03351a7bae8ff0f28f25270f929d2" dependencies = [ + "arbitrary", + "cc", +] + +[[package]] +name = "libloading" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d7c4b02199fee7c5d21a5ae7d8cfa79a6ef5bb2fc834d6e9058e89c825efdc55" +dependencies = [ + "cfg-if", + "windows-link", +] + +[[package]] +name = "libm" +version = "0.2.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981" + +[[package]] +name = "lightcraft-catalog" +version = "0.10.0" +source = "git+https://github.com/storytold/lightcraft?rev=5fe74557eca64638b1f9015c9769f7e52a889fa2#5fe74557eca64638b1f9015c9769f7e52a889fa2" +dependencies = [ + "crc32fast", + "lightcraft-develop", + "lightcraft-meta", + "lightcraft-raw", + "log", + "serde", + "serde_json", + "thiserror", + "web-time", +] + +[[package]] +name = "lightcraft-codecs" +version = "0.10.0" +source = "git+https://github.com/storytold/lightcraft?rev=5fe74557eca64638b1f9015c9769f7e52a889fa2#5fe74557eca64638b1f9015c9769f7e52a889fa2" +dependencies = [ + "avif-serialize", "bytemuck", "image", "image-webp", + "jixel", "jpeg-decoder", "jpeg-encoder", + "jxl-oxide", "lightcraft-color", "lightcraft-geom", "lightcraft-raster", "moxcms 0.9.1", "png", + "rav1e", + "ravif", "rayon", "serde", "thiserror", @@ -522,17 +1260,32 @@ dependencies = [ [[package]] name = "lightcraft-color" -version = "0.6.0" -source = "git+https://github.com/storytold/lightcraft?rev=0dd6593d9db55a17ab559261bac4d766f015c345#0dd6593d9db55a17ab559261bac4d766f015c345" +version = "0.10.0" +source = "git+https://github.com/storytold/lightcraft?rev=5fe74557eca64638b1f9015c9769f7e52a889fa2#5fe74557eca64638b1f9015c9769f7e52a889fa2" dependencies = [ "lightcraft-geom", "serde", ] +[[package]] +name = "lightcraft-denoise-core" +version = "0.10.0" +source = "git+https://github.com/storytold/lightcraft?rev=5fe74557eca64638b1f9015c9769f7e52a889fa2#5fe74557eca64638b1f9015c9769f7e52a889fa2" +dependencies = [ + "lightcraft-raster", + "miniz_oxide 0.8.9", + "rayon", + "serde", + "serde_json", + "sha2", + "thiserror", + "web-time", +] + [[package]] name = "lightcraft-develop" -version = "0.6.0" -source = "git+https://github.com/storytold/lightcraft?rev=0dd6593d9db55a17ab559261bac4d766f015c345#0dd6593d9db55a17ab559261bac4d766f015c345" +version = "0.10.0" +source = "git+https://github.com/storytold/lightcraft?rev=5fe74557eca64638b1f9015c9769f7e52a889fa2#5fe74557eca64638b1f9015c9769f7e52a889fa2" dependencies = [ "lightcraft-color", "lightcraft-geom", @@ -541,10 +1294,47 @@ dependencies = [ "serde_json", ] +[[package]] +name = "lightcraft-engine" +version = "0.10.0" +source = "git+https://github.com/storytold/lightcraft?rev=5fe74557eca64638b1f9015c9769f7e52a889fa2#5fe74557eca64638b1f9015c9769f7e52a889fa2" +dependencies = [ + "ab_glyph", + "craft-docpath", + "harfrust", + "lightcraft-catalog", + "lightcraft-codecs", + "lightcraft-color", + "lightcraft-denoise-core", + "lightcraft-develop", + "lightcraft-faces", + "lightcraft-fetch", + "lightcraft-geocode", + "lightcraft-geom", + "lightcraft-gpu", + "lightcraft-lensdb", + "lightcraft-merge", + "lightcraft-meta", + "lightcraft-pipeline", + "lightcraft-preview", + "lightcraft-raster", + "lightcraft-raw", + "lightcraft-scenes", + "lightcraft-slideshow", + "log", + "miniz_oxide 0.8.9", + "rayon", + "serde", + "serde_json", + "thiserror", + "unicode-segmentation", + "web-time", +] + [[package]] name = "lightcraft-faces" -version = "0.6.0" -source = "git+https://github.com/storytold/lightcraft?rev=0dd6593d9db55a17ab559261bac4d766f015c345#0dd6593d9db55a17ab559261bac4d766f015c345" +version = "0.10.0" +source = "git+https://github.com/storytold/lightcraft?rev=5fe74557eca64638b1f9015c9769f7e52a889fa2#5fe74557eca64638b1f9015c9769f7e52a889fa2" dependencies = [ "matrixmultiply", "ndarray", @@ -555,18 +1345,91 @@ dependencies = [ "web-time", ] +[[package]] +name = "lightcraft-fetch" +version = "0.10.0" +source = "git+https://github.com/storytold/lightcraft?rev=5fe74557eca64638b1f9015c9769f7e52a889fa2#5fe74557eca64638b1f9015c9769f7e52a889fa2" +dependencies = [ + "log", + "rustls", + "rustls-rustcrypto", + "sha2", + "webpki-roots", +] + +[[package]] +name = "lightcraft-geocode" +version = "0.10.0" +source = "git+https://github.com/storytold/lightcraft?rev=5fe74557eca64638b1f9015c9769f7e52a889fa2#5fe74557eca64638b1f9015c9769f7e52a889fa2" +dependencies = [ + "miniz_oxide 0.8.9", + "serde", +] + [[package]] name = "lightcraft-geom" -version = "0.6.0" -source = "git+https://github.com/storytold/lightcraft?rev=0dd6593d9db55a17ab559261bac4d766f015c345#0dd6593d9db55a17ab559261bac4d766f015c345" +version = "0.10.0" +source = "git+https://github.com/storytold/lightcraft?rev=5fe74557eca64638b1f9015c9769f7e52a889fa2#5fe74557eca64638b1f9015c9769f7e52a889fa2" dependencies = [ "serde", ] +[[package]] +name = "lightcraft-gpu" +version = "0.10.0" +source = "git+https://github.com/storytold/lightcraft?rev=5fe74557eca64638b1f9015c9769f7e52a889fa2#5fe74557eca64638b1f9015c9769f7e52a889fa2" +dependencies = [ + "bytemuck", + "lightcraft-color", + "lightcraft-develop", + "lightcraft-faces", + "lightcraft-geom", + "lightcraft-pipeline", + "lightcraft-raster", + "log", + "pollster", + "wgpu", +] + +[[package]] +name = "lightcraft-inpaint" +version = "0.10.0" +source = "git+https://github.com/storytold/lightcraft?rev=5fe74557eca64638b1f9015c9769f7e52a889fa2#5fe74557eca64638b1f9015c9769f7e52a889fa2" +dependencies = [ + "rayon", +] + +[[package]] +name = "lightcraft-lensdb" +version = "0.10.0" +source = "git+https://github.com/storytold/lightcraft?rev=5fe74557eca64638b1f9015c9769f7e52a889fa2#5fe74557eca64638b1f9015c9769f7e52a889fa2" +dependencies = [ + "lightcraft-develop", + "lightcraft-geom", + "quick-xml", +] + +[[package]] +name = "lightcraft-merge" +version = "0.10.0" +source = "git+https://github.com/storytold/lightcraft?rev=5fe74557eca64638b1f9015c9769f7e52a889fa2#5fe74557eca64638b1f9015c9769f7e52a889fa2" +dependencies = [ + "lightcraft-codecs", + "lightcraft-color", + "lightcraft-geom", + "lightcraft-meta", + "lightcraft-raster", + "lightcraft-raw", + "lightcraft-scenes", + "rayon", + "serde", + "thiserror", +] + [[package]] name = "lightcraft-meta" -version = "0.6.0" -source = "git+https://github.com/storytold/lightcraft?rev=0dd6593d9db55a17ab559261bac4d766f015c345#0dd6593d9db55a17ab559261bac4d766f015c345" +version = "0.10.0" +source = "git+https://github.com/storytold/lightcraft?rev=5fe74557eca64638b1f9015c9769f7e52a889fa2#5fe74557eca64638b1f9015c9769f7e52a889fa2" dependencies = [ "lightcraft-geom", "lightcraft-tiff", @@ -576,22 +1439,36 @@ dependencies = [ [[package]] name = "lightcraft-pipeline" -version = "0.6.0" -source = "git+https://github.com/storytold/lightcraft?rev=0dd6593d9db55a17ab559261bac4d766f015c345#0dd6593d9db55a17ab559261bac4d766f015c345" +version = "0.10.0" +source = "git+https://github.com/storytold/lightcraft?rev=5fe74557eca64638b1f9015c9769f7e52a889fa2#5fe74557eca64638b1f9015c9769f7e52a889fa2" dependencies = [ "lightcraft-color", "lightcraft-develop", "lightcraft-geom", + "lightcraft-inpaint", "lightcraft-raster", "lightcraft-raw", "rayon", "serde", ] +[[package]] +name = "lightcraft-preview" +version = "0.10.0" +source = "git+https://github.com/storytold/lightcraft?rev=5fe74557eca64638b1f9015c9769f7e52a889fa2#5fe74557eca64638b1f9015c9769f7e52a889fa2" +dependencies = [ + "jpeg-encoder", + "lightcraft-raster", + "log", + "siphasher", + "zune-core", + "zune-jpeg", +] + [[package]] name = "lightcraft-raster" -version = "0.6.0" -source = "git+https://github.com/storytold/lightcraft?rev=0dd6593d9db55a17ab559261bac4d766f015c345#0dd6593d9db55a17ab559261bac4d766f015c345" +version = "0.10.0" +source = "git+https://github.com/storytold/lightcraft?rev=5fe74557eca64638b1f9015c9769f7e52a889fa2#5fe74557eca64638b1f9015c9769f7e52a889fa2" dependencies = [ "lightcraft-color", "lightcraft-geom", @@ -601,9 +1478,10 @@ dependencies = [ [[package]] name = "lightcraft-raw" -version = "0.6.0" -source = "git+https://github.com/storytold/lightcraft?rev=0dd6593d9db55a17ab559261bac4d766f015c345#0dd6593d9db55a17ab559261bac4d766f015c345" +version = "0.10.0" +source = "git+https://github.com/storytold/lightcraft?rev=5fe74557eca64638b1f9015c9769f7e52a889fa2#5fe74557eca64638b1f9015c9769f7e52a889fa2" dependencies = [ + "jpeg-encoder", "jxl-oxide", "lightcraft-color", "lightcraft-geom", @@ -618,15 +1496,66 @@ dependencies = [ "zune-jpeg", ] +[[package]] +name = "lightcraft-scenes" +version = "0.10.0" +source = "git+https://github.com/storytold/lightcraft?rev=5fe74557eca64638b1f9015c9769f7e52a889fa2#5fe74557eca64638b1f9015c9769f7e52a889fa2" +dependencies = [ + "lightcraft-color", + "lightcraft-raster", + "rayon", + "serde", +] + +[[package]] +name = "lightcraft-slideshow" +version = "0.10.0" +source = "git+https://github.com/storytold/lightcraft?rev=5fe74557eca64638b1f9015c9769f7e52a889fa2#5fe74557eca64638b1f9015c9769f7e52a889fa2" +dependencies = [ + "lightcraft-raster", + "serde", + "serde_json", +] + [[package]] name = "lightcraft-tiff" -version = "0.6.0" -source = "git+https://github.com/storytold/lightcraft?rev=0dd6593d9db55a17ab559261bac4d766f015c345#0dd6593d9db55a17ab559261bac4d766f015c345" +version = "0.10.0" +source = "git+https://github.com/storytold/lightcraft?rev=5fe74557eca64638b1f9015c9769f7e52a889fa2#5fe74557eca64638b1f9015c9769f7e52a889fa2" dependencies = [ "serde", "thiserror", ] +[[package]] +name = "litrs" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4744e383959f0db86ede514b809b1c53251889093803c05267acc7d4e7030d70" + +[[package]] +name = "lock_api" +version = "0.4.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965" +dependencies = [ + "scopeguard", +] + +[[package]] +name = "log" +version = "0.4.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6" + +[[package]] +name = "loop9" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0fae87c125b03c1d2c0150c90365d7d6bcc53fb73a9acaef207d2d065860f062" +dependencies = [ + "imgref", +] + [[package]] name = "matrixmultiply" version = "0.3.11" @@ -637,6 +1566,16 @@ dependencies = [ "rawpointer", ] +[[package]] +name = "maybe-rayon" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ea1f30cedd69f0a2954655f7188c6a834246d2bcf1e315e2ac40c4b24dc9519" +dependencies = [ + "cfg-if", + "rayon", +] + [[package]] name = "memchr" version = "2.8.3" @@ -683,6 +1622,44 @@ dependencies = [ "pxfm", ] +[[package]] +name = "naga" +version = "30.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a616d2fb8c89516ac2723a581f69d6c18576046bed761bd6b305e5618e6ae130" +dependencies = [ + "arrayvec", + "bit-set", + "bitflags", + "cfg-if", + "cfg_aliases", + "codespan-reporting", + "half", + "hashbrown 0.17.1", + "indexmap", + "libm", + "log", + "naga-types", + "num-traits", + "once_cell", + "rustc-hash", + "spirv", + "thiserror", + "unicode-ident", +] + +[[package]] +name = "naga-types" +version = "30.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "590afbf58a6f4f62873cd5cff4468061844bafa1cdf399cc954537c22d768d49" +dependencies = [ + "hashbrown 0.17.1", + "indexmap", + "rustc-hash", + "thiserror", +] + [[package]] name = "ndarray" version = "0.17.2" @@ -698,6 +1675,62 @@ dependencies = [ "rawpointer", ] +[[package]] +name = "new_debug_unreachable" +version = "1.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "650eef8c711430f1a879fdd01d4745a7deea475becfb90269c06775983bbf086" + +[[package]] +name = "no_std_io2" +version = "0.9.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "418abd1b6d34fbf6cae440dc874771b0525a604428704c76e48b29a5e67b8003" +dependencies = [ + "memchr", +] + +[[package]] +name = "nom" +version = "8.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df9761775871bdef83bee530e60050f7e54b1105350d6884eb0fb4f46c2f9405" +dependencies = [ + "memchr", +] + +[[package]] +name = "noop_proc_macro" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0676bb32a98c1a483ce53e500a81ad9c3d5b3f7c920c28c24e9cb0980d0b5bc8" + +[[package]] +name = "num-bigint" +version = "0.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c89e69e7e0f03bea5ef08013795c25018e101932225a656383bd384495ecc367" +dependencies = [ + "num-integer", + "num-traits", +] + +[[package]] +name = "num-bigint-dig" +version = "0.8.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e661dda6640fad38e827a6d4a310ff4763082116fe217f279885c97f511bb0b7" +dependencies = [ + "lazy_static", + "libm", + "num-integer", + "num-iter", + "num-traits", + "rand 0.8.8", + "smallvec", + "zeroize", +] + [[package]] name = "num-complex" version = "0.4.6" @@ -707,6 +1740,17 @@ dependencies = [ "num-traits", ] +[[package]] +name = "num-derive" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed3955f1a9c7c0c15e092f9c887db08b1fc683305fdf6eb6684f22555355e202" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "num-integer" version = "0.1.47" @@ -716,6 +1760,27 @@ dependencies = [ "num-traits", ] +[[package]] +name = "num-iter" +version = "0.1.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c92800bd69a1eac91786bcfe9da64a897eb72911b8dc3095decbd07429e8048b" +dependencies = [ + "num-integer", + "num-traits", +] + +[[package]] +name = "num-rational" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f83d14da390562dca69fc84082e73e548e1ad308d24accdedd2720017cb37824" +dependencies = [ + "num-bigint", + "num-integer", + "num-traits", +] + [[package]] name = "num-traits" version = "0.2.19" @@ -723,6 +1788,93 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" dependencies = [ "autocfg", + "libm", +] + +[[package]] +name = "objc2" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08849bbd4767dfae9457696856ae1c84fe4e0281bbe4a7abff2d0e06fb7981f8" +dependencies = [ + "objc2-encode", +] + +[[package]] +name = "objc2-core-foundation" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2a180dd8642fa45cdb7dd721cd4c11b1cadd4929ce112ebd8b9f5803cc79d536" +dependencies = [ + "bitflags", + "dispatch2", + "objc2", +] + +[[package]] +name = "objc2-core-graphics" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e022c9d066895efa1345f8e33e584b9f958da2fd4cd116792e15e07e4720a807" +dependencies = [ + "dispatch2", + "objc2", + "objc2-core-foundation", + "objc2-io-surface", +] + +[[package]] +name = "objc2-encode" +version = "4.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ef25abbcd74fb2609453eb695bd2f860d389e457f67dc17cafc8b8cbc89d0c33" + +[[package]] +name = "objc2-foundation" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3e0adef53c21f888deb4fa59fc59f7eb17404926ee8a6f59f5df0fd7f9f3272" +dependencies = [ + "bitflags", + "objc2", + "objc2-core-foundation", +] + +[[package]] +name = "objc2-io-surface" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "180788110936d59bab6bd83b6060ffdfffb3b922ba1396b312ae795e1de9d81d" +dependencies = [ + "bitflags", + "objc2", + "objc2-core-foundation", +] + +[[package]] +name = "objc2-metal" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a0125f776a10d00af4152d74616409f0d4a2053a6f57fa5b7d6aa2854ac04794" +dependencies = [ + "bitflags", + "block2", + "objc2", + "objc2-foundation", +] + +[[package]] +name = "objc2-quartz-core" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "96c1358452b371bf9f104e21ec536d37a650eb10f7ee379fff67d2e08d537f1f" +dependencies = [ + "bitflags", + "objc2", + "objc2-core-foundation", + "objc2-core-graphics", + "objc2-foundation", + "objc2-metal", ] [[package]] @@ -731,15 +1883,113 @@ version = "1.21.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" +[[package]] +name = "opaque-debug" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c08d65885ee38876c4f86fa503fb49d7b507c2b62552df7c70b2fce627e06381" + +[[package]] +name = "ordered-float" +version = "5.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8c7c9e0d9b23589f26070720bac724174bfec1083e82f7854cdd0267518343c0" +dependencies = [ + "num-traits", +] + +[[package]] +name = "owned_ttf_parser" +version = "0.25.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "36820e9051aca1014ddc75770aab4d68bc1e9e632f0f5627c4086bc216fb583b" +dependencies = [ + "ttf-parser", +] + +[[package]] +name = "p256" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c9863ad85fa8f4460f9c48cb909d38a0d689dba1f6f6988a5e3e0d31071bcd4b" +dependencies = [ + "ecdsa", + "elliptic-curve", + "primeorder", + "sha2", +] + +[[package]] +name = "p384" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe42f1670a52a47d448f14b6a5c61dd78fce51856e68edaa38f7ae3a46b8d6b6" +dependencies = [ + "ecdsa", + "elliptic-curve", + "primeorder", + "sha2", +] + +[[package]] +name = "parking_lot" +version = "0.12.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a" +dependencies = [ + "lock_api", + "parking_lot_core", +] + +[[package]] +name = "parking_lot_core" +version = "0.9.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1" +dependencies = [ + "cfg-if", + "libc", + "redox_syscall", + "smallvec", + "windows-link", +] + +[[package]] +name = "paste" +version = "1.0.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a" + +[[package]] +name = "pastey" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "35fb2e5f958ec131621fdd531e9fc186ed768cbe395337403ae56c17a74c68ec" + +[[package]] +name = "pem-rfc7468" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "88b39c9bfcfc231068454382784bb460aae594343fb030d46e9f50a645418412" +dependencies = [ + "base64ct", +] + [[package]] name = "photoreport-engine" version = "0.1.0" dependencies = [ + "lightcraft-catalog", "lightcraft-codecs", + "lightcraft-color", "lightcraft-develop", + "lightcraft-engine", "lightcraft-geom", + "lightcraft-merge", + "lightcraft-meta", "lightcraft-pipeline", "lightcraft-raster", + "lightcraft-raw", "serde", "serde_json", "thiserror", @@ -780,6 +2030,38 @@ version = "0.2.17" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" +[[package]] +name = "pkcs1" +version = "0.7.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c8ffb9f10fa047879315e6625af03c164b16962a5368d724ed16323b68ace47f" +dependencies = [ + "der", + "pkcs8", + "spki", +] + +[[package]] +name = "pkcs5" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e847e2c91a18bfa887dd028ec33f2fe6f25db77db3619024764914affe8b69a6" +dependencies = [ + "der", + "spki", +] + +[[package]] +name = "pkcs8" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f950b2377845cebe5cf8b5165cb3cc1a5e0fa5cfa3e1f7f55707d8fd82e0a7b7" +dependencies = [ + "der", + "pkcs5", + "spki", +] + [[package]] name = "png" version = "0.18.1" @@ -793,6 +2075,35 @@ dependencies = [ "miniz_oxide 0.8.9", ] +[[package]] +name = "pollster" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bc6355899e1c9462875b6757c79f3caa011a1fdae12bbb1a2e72dd1f234f8336" + +[[package]] +name = "poly1305" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8159bd90725d2df49889a078b54f4f79e87f1f8a8444194cdca81d38f5393abf" +dependencies = [ + "cpufeatures", + "opaque-debug", + "universal-hash", +] + +[[package]] +name = "polyval" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9d1fe60d06143b2430aa532c94cfe9e29783047f06c0d7fd359a9a51b729fa25" +dependencies = [ + "cfg-if", + "cpufeatures", + "opaque-debug", + "universal-hash", +] + [[package]] name = "portable-atomic" version = "1.15.0" @@ -808,6 +2119,30 @@ dependencies = [ "portable-atomic", ] +[[package]] +name = "ppv-lite86" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9" +dependencies = [ + "zerocopy", +] + +[[package]] +name = "presser" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e8cf8e6a8aa66ce33f63993ffc4ea4271eb5b0530a9002db8455ea6050c77bfa" + +[[package]] +name = "primeorder" +version = "0.13.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "353e1ca18966c16d9deb1c69278edbc5f194139612772bd9537af60ac231e1e6" +dependencies = [ + "elliptic-curve", +] + [[package]] name = "proc-macro2" version = "1.0.107" @@ -817,6 +2152,25 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "profiling" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d595e54a326bc53c1c197b32d295e14b169e3cfeaa8dc82b529f947fba6bcf5" +dependencies = [ + "profiling-procmacros", +] + +[[package]] +name = "profiling-procmacros" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4488a4a36b9a4ba6b9334a32a39971f77c1436ec82c38707bce707699cc3bbcb" +dependencies = [ + "quote", + "syn 2.0.119", +] + [[package]] name = "pxfm" version = "0.1.30" @@ -847,6 +2201,150 @@ dependencies = [ "proc-macro2", ] +[[package]] +name = "r-efi" +version = "5.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f" + +[[package]] +name = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + +[[package]] +name = "rand" +version = "0.8.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e058c7de0b26af77780c769414d6257830bb240f3c38477dbc2c16e5f54d6d4c" +dependencies = [ + "rand_chacha 0.3.1", + "rand_core 0.6.4", +] + +[[package]] +name = "rand" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9ef1d0d795eb7d84685bca4f72f3649f064e6641543d3a8c415898726a57b41" +dependencies = [ + "rand_chacha 0.9.0", + "rand_core 0.9.5", +] + +[[package]] +name = "rand_chacha" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88" +dependencies = [ + "ppv-lite86", + "rand_core 0.6.4", +] + +[[package]] +name = "rand_chacha" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb" +dependencies = [ + "ppv-lite86", + "rand_core 0.9.5", +] + +[[package]] +name = "rand_core" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" +dependencies = [ + "getrandom 0.2.17", +] + +[[package]] +name = "rand_core" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c" +dependencies = [ + "getrandom 0.3.4", +] + +[[package]] +name = "range-alloc" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca45419789ae5a7899559e9512e58ca889e41f04f1f2445e9f4b290ceccd1d08" + +[[package]] +name = "rav1e" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "43b6dd56e85d9483277cde964fd1bdb0428de4fec5ebba7540995639a21cb32b" +dependencies = [ + "aligned-vec", + "arbitrary", + "arg_enum_proc_macro", + "arrayvec", + "av-scenechange", + "av1-grain", + "bitstream-io", + "built", + "cfg-if", + "interpolate_name", + "itertools", + "libc", + "libfuzzer-sys", + "log", + "maybe-rayon", + "new_debug_unreachable", + "noop_proc_macro", + "num-derive", + "num-traits", + "paste", + "profiling", + "rand 0.9.5", + "rand_chacha 0.9.0", + "simd_helpers", + "thiserror", + "v_frame", + "wasm-bindgen", +] + +[[package]] +name = "ravif" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e52310197d971b0f5be7fe6b57530dcd27beb35c1b013f29d66c1ad73fbbcc45" +dependencies = [ + "avif-serialize", + "imgref", + "loop9", + "quick-error", + "rav1e", + "rayon", + "rgb", +] + +[[package]] +name = "raw-window-handle" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20675572f6f24e9e76ef639bc5552774ed45f1c30e2951e1e99c59888861c539" + +[[package]] +name = "raw-window-metal" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "40d213455a5f1dc59214213c7330e074ddf8114c9a42411eb890c767357ce135" +dependencies = [ + "objc2", + "objc2-core-foundation", + "objc2-foundation", + "objc2-quartz-core", +] + [[package]] name = "rawpointer" version = "0.2.1" @@ -873,12 +2371,204 @@ dependencies = [ "crossbeam-utils", ] +[[package]] +name = "read-fonts" +version = "0.41.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "046a7d674daf459825b32f5062056d6882db0d2f5a479fbd76ccfc870ac18709" +dependencies = [ + "bytemuck", + "font-types", + "once_cell", +] + +[[package]] +name = "redox_syscall" +version = "0.5.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" +dependencies = [ + "bitflags", +] + +[[package]] +name = "renderdoc-sys" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "19b30a45b0cd0bcca8037f3d0dc3421eaf95327a17cad11964fb8179b4fc4832" + +[[package]] +name = "rfc6979" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dd2a808d456c4a54e300a23e9f5a67e122c3024119acbfd73e3bf664491cb2" +dependencies = [ + "hmac", + "subtle", +] + +[[package]] +name = "rgb" +version = "0.8.53" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47b34b781b31e5d73e9fbc8689c70551fd1ade9a19e3e28cfec8580a79290cc4" + +[[package]] +name = "ring" +version = "0.17.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" +dependencies = [ + "cc", + "cfg-if", + "getrandom 0.2.17", + "libc", + "untrusted", + "windows-sys", +] + +[[package]] +name = "rsa" +version = "0.9.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8573f03f5883dcaebdfcf4725caa1ecb9c15b2ef50c43a07b816e06799bb12d" +dependencies = [ + "const-oid", + "digest", + "num-bigint-dig", + "num-integer", + "num-traits", + "pkcs1", + "pkcs8", + "rand_core 0.6.4", + "sha2", + "signature", + "spki", + "subtle", + "zeroize", +] + +[[package]] +name = "rustc-hash" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08d43f7aa6b08d49f382cde6a7982047c3426db949b1424bc4b7ec9ae12c6ce2" + +[[package]] +name = "rustc_version" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92" +dependencies = [ + "semver", +] + +[[package]] +name = "rustls" +version = "0.23.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf" +dependencies = [ + "once_cell", + "rustls-pki-types", + "rustls-webpki 0.103.16", + "subtle", + "zeroize", +] + +[[package]] +name = "rustls-pki-types" +version = "1.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f4925028c7eb5d1fcdaf196971378ed9d2c1c4efc7dc5d011256f76c99c0a96" +dependencies = [ + "zeroize", +] + +[[package]] +name = "rustls-rustcrypto" +version = "0.0.2-alpha" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f12052947763ab8515f753315357599e9b0b4dab3b8ba15f30f725fe6d025557" +dependencies = [ + "aead", + "aes-gcm", + "chacha20poly1305", + "crypto-common", + "der", + "digest", + "ecdsa", + "ed25519-dalek", + "hmac", + "p256", + "p384", + "paste", + "pkcs8", + "rand_core 0.6.4", + "rsa", + "rustls", + "rustls-pki-types", + "rustls-webpki 0.102.8", + "sec1", + "sha2", + "signature", + "x25519-dalek", +] + +[[package]] +name = "rustls-webpki" +version = "0.102.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "64ca1bc8749bd4cf37b5ce386cc146580777b4e8572c7b97baf22c83f444bee9" +dependencies = [ + "ring", + "rustls-pki-types", + "untrusted", +] + +[[package]] +name = "rustls-webpki" +version = "0.103.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4443b1b6d39d7c663139942cc4558262562d2c84123bb6282ef177009ca8b281" +dependencies = [ + "ring", + "rustls-pki-types", + "untrusted", +] + [[package]] name = "rustversion" version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" +[[package]] +name = "scopeguard" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" + +[[package]] +name = "sec1" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3e97a565f76233a6003f9f5c54be1d9c5bdfa3eccfb189469f11ec4901c47dc" +dependencies = [ + "base16ct", + "der", + "generic-array", + "pkcs8", + "subtle", + "zeroize", +] + +[[package]] +name = "semver" +version = "1.0.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" + [[package]] name = "serde" version = "1.0.229" @@ -933,18 +2623,98 @@ dependencies = [ "digest", ] +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + +[[package]] +name = "signature" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77549399552de45a898a580c1b41d445bf730df867cc44e6c0233bbc4b8329de" +dependencies = [ + "digest", + "rand_core 0.6.4", +] + [[package]] name = "simd-adler32" version = "0.3.10" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea" +[[package]] +name = "simd_helpers" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "95890f873bec569a0362c235787f3aca6e1e887302ba4840839bcc6459c42da6" +dependencies = [ + "quote", +] + +[[package]] +name = "siphasher" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33f4fe9184a62d842c9ef383018f3306d8ba224fd9d836f56d7288308847c256" + [[package]] name = "slab" version = "0.4.12" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" +[[package]] +name = "smallvec" +version = "1.16.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d0d5d4b1981b8bbbb7aed204cae5726d683d5d6ac7e74ec54122ea28f315e7c8" + +[[package]] +name = "spin" +version = "0.9.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3763264f6b73151db08c50ff20d7d8a0b8796e021cdea7ceedad07b80155fa0e" + +[[package]] +name = "spirv" +version = "0.4.0+sdk-1.4.341.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d9571ea910ebd84c86af4b3ed27f9dbdc6ad06f17c5f96146b2b671e2976744f" +dependencies = [ + "bitflags", +] + +[[package]] +name = "spki" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d91ed6c858b01f942cd56b37a94b3e0a1798290327d1236e4d9cf4eaca44d29d" +dependencies = [ + "base64ct", + "der", +] + +[[package]] +name = "stable_deref_trait" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" + +[[package]] +name = "static_assertions" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f" + +[[package]] +name = "subtle" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" + [[package]] name = "syn" version = "2.0.119" @@ -1001,6 +2771,15 @@ dependencies = [ "zune-jpeg", ] +[[package]] +name = "tokio" +version = "1.54.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b52fd3255258d26fac7264ab5a76b53c13367136dc011d3d6ad4f8ed070396a3" +dependencies = [ + "pin-project-lite", +] + [[package]] name = "tracing" version = "0.1.44" @@ -1020,6 +2799,12 @@ dependencies = [ "once_cell", ] +[[package]] +name = "ttf-parser" +version = "0.25.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2df906b07856748fa3f6e0ad0cbaa047052d4a7dd609e231c4f72cee8c36f31" + [[package]] name = "typenum" version = "1.20.1" @@ -1032,12 +2817,66 @@ version = "1.0.26" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d245f478577f809a851594d02313b640fb437e0bb33866753cff937863096954" +[[package]] +name = "unicode-segmentation" +version = "1.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6f5d3c3b1bf09027a88a6bc961fc00497d651009560b5463668dc81b0fa87a8" + +[[package]] +name = "unicode-width" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b4ac048d71ede7ee76d585517add45da530660ef4390e49b098733c6e897f254" + +[[package]] +name = "universal-hash" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc1de2c688dc15305988b563c3854064043356019f97a4b46276fe734c4f07ea" +dependencies = [ + "crypto-common", + "subtle", +] + +[[package]] +name = "untrusted" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" + +[[package]] +name = "v_frame" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "666b7727c8875d6ab5db9533418d7c764233ac9c0cff1d469aec8fa127597be2" +dependencies = [ + "aligned-vec", + "num-traits", + "wasm-bindgen", +] + [[package]] name = "version_check" version = "0.9.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + +[[package]] +name = "wasip2" +version = "1.0.4+wasi-0.2.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b67efb37e106e55ce722a510d6b5f9c17f083e5fc79afc2badeb12cc313d9487" +dependencies = [ + "wit-bindgen", +] + [[package]] name = "wasm-bindgen" version = "0.2.129" @@ -1051,6 +2890,17 @@ dependencies = [ "wasm-bindgen-shared", ] +[[package]] +name = "wasm-bindgen-futures" +version = "0.4.79" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3cbab34de2d982e9b48e18d216d04c4a6f641066ff19ffb699980f591ee3610e" +dependencies = [ + "js-sys", + "tokio", + "wasm-bindgen", +] + [[package]] name = "wasm-bindgen-macro" version = "0.2.129" @@ -1083,6 +2933,16 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "web-sys" +version = "0.3.106" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "88261b9deccee56594c11a3460c462c41f58d148598fe70ad77070126a68aba4" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + [[package]] name = "web-time" version = "1.1.0" @@ -1093,12 +2953,380 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "webpki-roots" +version = "1.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f5f280bbb2b287bc8e7de7e3852945a0ff50d1bbcb5ed42b6c7a568c546df171" +dependencies = [ + "rustls-pki-types", +] + [[package]] name = "weezl" version = "0.1.12" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a28ac98ddc8b9274cb41bb4d9d4d5c425b6020c50c46f25559911905610b4a88" +[[package]] +name = "wgpu" +version = "30.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "527ccdf43dd5b2e8676eed9984ce00e2bbb0a1b85b70c1969dcb6cd2eb55ab9e" +dependencies = [ + "arrayvec", + "bitflags", + "bytemuck", + "cfg-if", + "cfg_aliases", + "document-features", + "hashbrown 0.17.1", + "js-sys", + "log", + "parking_lot", + "portable-atomic", + "profiling", + "raw-window-handle", + "smallvec", + "static_assertions", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", + "wgpu-core", + "wgpu-hal", + "wgpu-types", +] + +[[package]] +name = "wgpu-core" +version = "30.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "14c018fce9b6270aa203c2fdd56f3cce996713534bd757e4ea58c8560b121f14" +dependencies = [ + "arrayvec", + "bit-set", + "bit-vec", + "bitflags", + "bytemuck", + "cfg_aliases", + "document-features", + "hashbrown 0.17.1", + "indexmap", + "log", + "naga", + "naga-types", + "once_cell", + "parking_lot", + "portable-atomic", + "profiling", + "raw-window-handle", + "rustc-hash", + "smallvec", + "thiserror", + "wgpu-core-deps-apple", + "wgpu-core-deps-windows-linux-android", + "wgpu-hal", + "wgpu-naga-bridge", + "wgpu-types", +] + +[[package]] +name = "wgpu-core-deps-apple" +version = "30.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "061f3d319a40d39d00b1ecc2c33b89fe21d4e6fe01859df3500a3a8ecccd6b68" +dependencies = [ + "wgpu-hal", +] + +[[package]] +name = "wgpu-core-deps-windows-linux-android" +version = "30.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7586165fd5f6d881cb9ce4bb71f40d6caab2c0f1837e3fc1d9788a197fb6004f" +dependencies = [ + "wgpu-hal", +] + +[[package]] +name = "wgpu-hal" +version = "30.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6b7fb58561a792bc237628ba0792e332de418fefe145f13b5ed8201e6d52f58" +dependencies = [ + "android_system_properties", + "arrayvec", + "ash", + "bit-set", + "bitflags", + "block2", + "bytemuck", + "cfg-if", + "cfg_aliases", + "gpu-allocator", + "hashbrown 0.17.1", + "libc", + "libloading", + "log", + "naga", + "naga-types", + "objc2", + "objc2-core-foundation", + "objc2-core-graphics", + "objc2-foundation", + "objc2-metal", + "objc2-quartz-core", + "once_cell", + "ordered-float", + "parking_lot", + "portable-atomic", + "portable-atomic-util", + "profiling", + "range-alloc", + "raw-window-handle", + "raw-window-metal", + "renderdoc-sys", + "smallvec", + "static_assertions", + "thiserror", + "wgpu-naga-bridge", + "wgpu-types", + "windows", + "windows-core", +] + +[[package]] +name = "wgpu-naga-bridge" +version = "30.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2f62e73117bb7a62bfd9c5a5841438a823f6566c6442a808ee269d2d055c081" +dependencies = [ + "naga", + "wgpu-types", +] + +[[package]] +name = "wgpu-types" +version = "30.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "99dad6f1fbdbbdb4c278a6508b059d44688f5cebddf78d005a46a31340269286" +dependencies = [ + "bitflags", + "bytemuck", + "js-sys", + "log", + "naga-types", + "raw-window-handle", + "static_assertions", + "web-sys", +] + +[[package]] +name = "windows" +version = "0.62.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "527fadee13e0c05939a6a05d5bd6eec6cd2e3dbd648b9f8e447c6518133d8580" +dependencies = [ + "windows-collections", + "windows-core", + "windows-future", + "windows-numerics", +] + +[[package]] +name = "windows-collections" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23b2d95af1a8a14a3c7367e1ed4fc9c20e0a26e79551b1454d72583c97cc6610" +dependencies = [ + "windows-core", +] + +[[package]] +name = "windows-core" +version = "0.62.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb" +dependencies = [ + "windows-implement", + "windows-interface", + "windows-link", + "windows-result", + "windows-strings", +] + +[[package]] +name = "windows-future" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e1d6f90251fe18a279739e78025bd6ddc52a7e22f921070ccdc67dde84c605cb" +dependencies = [ + "windows-core", + "windows-link", + "windows-threading", +] + +[[package]] +name = "windows-implement" +version = "0.60.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "windows-interface" +version = "0.59.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-numerics" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e2e40844ac143cdb44aead537bbf727de9b044e107a0f1220392177d15b0f26" +dependencies = [ + "windows-core", + "windows-link", +] + +[[package]] +name = "windows-result" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-strings" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-sys" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" +dependencies = [ + "windows-targets", +] + +[[package]] +name = "windows-targets" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" +dependencies = [ + "windows_aarch64_gnullvm", + "windows_aarch64_msvc", + "windows_i686_gnu", + "windows_i686_gnullvm", + "windows_i686_msvc", + "windows_x86_64_gnu", + "windows_x86_64_gnullvm", + "windows_x86_64_msvc", +] + +[[package]] +name = "windows-threading" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3949bd5b99cafdf1c7ca86b43ca564028dfe27d66958f2470940f73d86d75b37" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" + +[[package]] +name = "windows_i686_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" + +[[package]] +name = "windows_i686_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" + +[[package]] +name = "wit-bindgen" +version = "0.57.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e" + +[[package]] +name = "x25519-dalek" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c7e468321c81fb07fa7f4c636c3972b9100f0346e5b6a9f2bd0603a52f7ed277" +dependencies = [ + "curve25519-dalek", + "rand_core 0.6.4", + "zeroize", +] + +[[package]] +name = "y4m" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7a5a4b21e1a62b67a2970e6831bc091d7b87e119e7f9791aef9702e3bef04448" + [[package]] name = "zerocopy" version = "0.8.62" @@ -1119,6 +3347,26 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "zeroize" +version = "1.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e13084392c5e4bc371903e2935a5eaeed24905a7511356b883835e18a78f6879" +dependencies = [ + "zeroize_derive", +] + +[[package]] +name = "zeroize_derive" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c50655cbb0fe3fc43170059e702f1ce5e19b84cec58dc87b037a09935c2f328" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "zlib-rs" version = "0.6.8" diff --git a/Cargo.toml b/Cargo.toml index ad0676e..fb5f23b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -10,12 +10,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" } +lightcraft-develop = { git = "https://github.com/storytold/lightcraft", rev = "5fe74557eca64638b1f9015c9769f7e52a889fa2" } +lightcraft-codecs = { git = "https://github.com/storytold/lightcraft", rev = "5fe74557eca64638b1f9015c9769f7e52a889fa2", default-features = false } +lightcraft-pipeline = { git = "https://github.com/storytold/lightcraft", rev = "5fe74557eca64638b1f9015c9769f7e52a889fa2" } +lightcraft-raster = { git = "https://github.com/storytold/lightcraft", rev = "5fe74557eca64638b1f9015c9769f7e52a889fa2" } +lightcraft-geom = { git = "https://github.com/storytold/lightcraft", rev = "5fe74557eca64638b1f9015c9769f7e52a889fa2" } +lightcraft-faces = { git = "https://github.com/storytold/lightcraft", rev = "5fe74557eca64638b1f9015c9769f7e52a889fa2" } +lightcraft-merge = { git = "https://github.com/storytold/lightcraft", rev = "5fe74557eca64638b1f9015c9769f7e52a889fa2" } +lightcraft-raw = { git = "https://github.com/storytold/lightcraft", rev = "5fe74557eca64638b1f9015c9769f7e52a889fa2" } +lightcraft-color = { git = "https://github.com/storytold/lightcraft", rev = "5fe74557eca64638b1f9015c9769f7e52a889fa2" } +lightcraft-meta = { git = "https://github.com/storytold/lightcraft", rev = "5fe74557eca64638b1f9015c9769f7e52a889fa2" } +# Photo Merge only. The develop crates do not export the colour-tag step a raw without matrices +# needs before write_linear_dng. Desktop turns this on; the browser engine does not. +lightcraft-engine = { git = "https://github.com/storytold/lightcraft", rev = "5fe74557eca64638b1f9015c9769f7e52a889fa2" } +lightcraft-catalog = { git = "https://github.com/storytold/lightcraft", rev = "5fe74557eca64638b1f9015c9769f7e52a889fa2" } serde = { version = "1", features = ["derive"] } serde_json = "1" thiserror = "2" diff --git a/apps/api/prisma/migrations/20261020120000_archive_team_directory/migration.sql b/apps/api/prisma/migrations/20261020120000_archive_team_directory/migration.sql new file mode 100644 index 0000000..0ecd726 --- /dev/null +++ b/apps/api/prisma/migrations/20261020120000_archive_team_directory/migration.sql @@ -0,0 +1,17 @@ +-- The teams directory, written by the worker and only read by the site. +ALTER TABLE "cloud_sources" ADD COLUMN "directory_built_at" TIMESTAMP(3), +ADD COLUMN "directory_dirty_at" TIMESTAMP(3); + +CREATE TABLE "archive_team_sides" ( + "source_id" UUID NOT NULL, + "event_id" UUID NOT NULL, + "raw" TEXT NOT NULL, + "name" TEXT NOT NULL, + + CONSTRAINT "archive_team_sides_pkey" PRIMARY KEY ("source_id", "event_id", "raw") +); + +CREATE INDEX "archive_team_sides_source_id_name_idx" ON "archive_team_sides"("source_id", "name"); + +ALTER TABLE "archive_team_sides" ADD CONSTRAINT "archive_team_sides_source_id_fkey" FOREIGN KEY ("source_id") REFERENCES "cloud_sources"("id") ON DELETE CASCADE ON UPDATE CASCADE; +ALTER TABLE "archive_team_sides" ADD CONSTRAINT "archive_team_sides_event_id_fkey" FOREIGN KEY ("event_id") REFERENCES "events"("id") ON DELETE CASCADE ON UPDATE CASCADE; diff --git a/apps/api/prisma/migrations/20261020150000_archive_videos/migration.sql b/apps/api/prisma/migrations/20261020150000_archive_videos/migration.sql new file mode 100644 index 0000000..871e95d --- /dev/null +++ b/apps/api/prisma/migrations/20261020150000_archive_videos/migration.sql @@ -0,0 +1,35 @@ +-- Videos in the archive: a web copy and a poster are kept, the original stays on the cloud. +ALTER TABLE "cloud_folders" ADD COLUMN "video_count" INTEGER NOT NULL DEFAULT 0; + +CREATE TABLE "cloud_videos" ( + "id" UUID NOT NULL, + "source_id" UUID NOT NULL, + "folder_id" UUID NOT NULL, + "file_id" TEXT NOT NULL, + "path" TEXT NOT NULL, + "etag" TEXT, + "size" BIGINT, + "status" TEXT NOT NULL DEFAULT 'PENDING', + "attempts" INTEGER NOT NULL DEFAULT 0, + "error" TEXT, + "duration_ms" INTEGER, + "width" INTEGER, + "height" INTEGER, + "captured_at" TIMESTAMP(3), + "storage_key" TEXT, + "web_bytes" BIGINT, + "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "updated_at" TIMESTAMP(3) NOT NULL, + CONSTRAINT "cloud_videos_pkey" PRIMARY KEY ("id") +); +CREATE UNIQUE INDEX "cloud_videos_source_id_file_id_key" ON "cloud_videos"("source_id", "file_id"); +CREATE INDEX "cloud_videos_status_source_id_idx" ON "cloud_videos"("status", "source_id"); +CREATE INDEX "cloud_videos_folder_id_status_path_idx" ON "cloud_videos"("folder_id", "status", "path"); +ALTER TABLE "cloud_videos" ADD CONSTRAINT "cloud_videos_source_id_fkey" FOREIGN KEY ("source_id") REFERENCES "cloud_sources"("id") ON DELETE CASCADE ON UPDATE CASCADE; +ALTER TABLE "cloud_videos" ADD CONSTRAINT "cloud_videos_folder_id_fkey" FOREIGN KEY ("folder_id") REFERENCES "cloud_folders"("id") ON DELETE CASCADE ON UPDATE CASCADE; + +-- Videos were skipped by every walk until now, and a walk does not read a folder whose etag has not changed: every +-- folder is read once more (images already indexed keep their etag and are not indexed again), and every cloud is +-- walked at once. +UPDATE "cloud_folders" SET "etag" = NULL; +UPDATE "cloud_sources" SET "next_scan_at" = CURRENT_TIMESTAMP WHERE "status" IN ('READY', 'ERROR'); diff --git a/apps/api/prisma/migrations/20261020190000_archive_video_faces/migration.sql b/apps/api/prisma/migrations/20261020190000_archive_video_faces/migration.sql new file mode 100644 index 0000000..8e9ed87 --- /dev/null +++ b/apps/api/prisma/migrations/20261020190000_archive_video_faces/migration.sql @@ -0,0 +1,33 @@ +-- Faces in archive videos: appearances (a face followed through frames) in the events' face groups. +ALTER TABLE "cloud_videos" ADD COLUMN "faces_status" "FacesStatus" NOT NULL DEFAULT 'NONE'; +CREATE INDEX "cloud_videos_faces_status_idx" ON "cloud_videos"("faces_status"); + +CREATE TABLE "video_faces" ( + "id" UUID NOT NULL, + "video_id" UUID NOT NULL, + "group_id" UUID, + "start_ms" INTEGER NOT NULL, + "end_ms" INTEGER NOT NULL, + "at_ms" INTEGER NOT NULL, + "x0" DOUBLE PRECISION NOT NULL, + "y0" DOUBLE PRECISION NOT NULL, + "x1" DOUBLE PRECISION NOT NULL, + "y1" DOUBLE PRECISION NOT NULL, + "score" DOUBLE PRECISION NOT NULL, + "sharpness" DOUBLE PRECISION, + "embedding" DOUBLE PRECISION[] DEFAULT ARRAY[]::DOUBLE PRECISION[], + "model" TEXT NOT NULL, + "frames" INTEGER NOT NULL, + "frame_key" TEXT NOT NULL, + "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT "video_faces_pkey" PRIMARY KEY ("id") +); +CREATE INDEX "video_faces_video_id_idx" ON "video_faces"("video_id"); +CREATE INDEX "video_faces_group_id_idx" ON "video_faces"("group_id"); +ALTER TABLE "video_faces" ADD CONSTRAINT "video_faces_video_id_fkey" FOREIGN KEY ("video_id") REFERENCES "cloud_videos"("id") ON DELETE CASCADE ON UPDATE CASCADE; +ALTER TABLE "video_faces" ADD CONSTRAINT "video_faces_group_id_fkey" FOREIGN KEY ("group_id") REFERENCES "face_groups"("id") ON DELETE SET NULL ON UPDATE CASCADE; + +-- Videos already made, in organizations with face recognition on (as their photos): their faces are found next. +UPDATE "cloud_videos" v SET "faces_status" = 'PENDING' +FROM "cloud_sources" s JOIN "organizations" o ON o."id" = s."organization_id" +WHERE v."source_id" = s."id" AND o."biometrics_enabled" AND v."status" = 'DONE'; diff --git a/apps/api/prisma/migrations/20261021020000_real_estate/migration.sql b/apps/api/prisma/migrations/20261021020000_real_estate/migration.sql new file mode 100644 index 0000000..46c5a45 --- /dev/null +++ b/apps/api/prisma/migrations/20261021020000_real_estate/migration.sql @@ -0,0 +1,2 @@ +-- AlterTable +ALTER TABLE "organizations" ADD COLUMN "real_estate_enabled" BOOLEAN NOT NULL DEFAULT false; diff --git a/apps/api/prisma/migrations/20261021220000_faces_squad_pass/migration.sql b/apps/api/prisma/migrations/20261021220000_faces_squad_pass/migration.sql new file mode 100644 index 0000000..8137e4f --- /dev/null +++ b/apps/api/prisma/migrations/20261021220000_faces_squad_pass/migration.sql @@ -0,0 +1,2 @@ +-- Photos read before the season squads can be sent through face analysis again, newest first, once. +ALTER TABLE "photos" ADD COLUMN "faces_pass" INTEGER NOT NULL DEFAULT 0; diff --git a/apps/api/prisma/migrations/20261021230000_ehf_provider/migration.sql b/apps/api/prisma/migrations/20261021230000_ehf_provider/migration.sql new file mode 100644 index 0000000..4331149 --- /dev/null +++ b/apps/api/prisma/migrations/20261021230000_ehf_provider/migration.sql @@ -0,0 +1,2 @@ +-- European handball (EHF club competitions) is its own source, beside the FPA's national games. +ALTER TYPE "SportsProvider" ADD VALUE IF NOT EXISTS 'EHF'; diff --git a/apps/api/prisma/schema.prisma b/apps/api/prisma/schema.prisma index 0759171..6f71885 100644 --- a/apps/api/prisma/schema.prisma +++ b/apps/api/prisma/schema.prisma @@ -62,6 +62,8 @@ model Organization { /// Face recognition is biometric data: off unless enabled with a recorded legal basis. biometricsEnabled Boolean @default(false) @map("biometrics_enabled") biometricsLegalBasis String? @map("biometrics_legal_basis") + /// Interior brackets. Off: the area is hidden and its routes refuse work. Sports ingest is unchanged. + realEstateEnabled Boolean @default(false) @map("real_estate_enabled") createdAt DateTime @default(now()) @map("created_at") updatedAt DateTime @updatedAt @map("updated_at") @@ -279,6 +281,7 @@ model Event { cloudFolders CloudFolder[] /// FTP logins sending everything to this event, whatever the camera's clock says ("Receber FTP aqui"). ftpTargets FtpAccount[] + teamSides ArchiveTeamSide[] @@index([organizationId, startsAt]) @@map("events") @@ -373,8 +376,8 @@ model Photo { width Int? height Int? capturedAt DateTime? @map("captured_at") - /// When it was taken, or the game's start, or when the file arrived. Face analysis finishes the last month of - /// this before the older archive. + /// When it was taken, or the game's start, or when the file arrived. Among photographs never read, face + /// analysis finishes the last month of this before the older archive. A second reading waits behind those. takenAt DateTime @default(now()) @map("taken_at") cameraMake String? @map("camera_make") cameraModel String? @map("camera_model") @@ -398,6 +401,8 @@ model Photo { embeddedIptc Json? @map("embedded_iptc") /// Face analysis: NONE (organization without biometrics), PENDING, DONE or FAILED. facesStatus FacesStatus @default(NONE) @map("faces_status") + /// Which squad-aware reread this photo has been sent through. 0: read before the season squads. + facesPass Int @default(0) @map("faces_pass") /// When the event was asked to the front of the face queue. Null waits behind every boosted photo. facesBoostedAt DateTime? @map("faces_boosted_at") /// Autopilot queue (docs/photo-editing-rules.md): NONE unless the event's autopilot took this photo. @@ -697,6 +702,7 @@ model FaceGroup { person Person? @relation("confirmed", fields: [personId], references: [id], onDelete: SetNull) suggested Person? @relation("suggested", fields: [suggestedPersonId], references: [id], onDelete: SetNull) faces Face[] + videoFaces VideoFace[] rejections FaceGroupRejection[] @@index([eventId]) @@ -1258,6 +1264,7 @@ enum SportsProvider { FPF // resultados.fpf.pt (football below the Liga: teams, fixtures, line-ups per match) FPA // ws.fpa.pt (handball: teams and fixtures) UEFA // match.uefa.com (club competitions: fixtures, referee teams, line-ups with numbers and headshots) + EHF // ehfcl/ehfel/ehfec.eurohandball.com (club handball: fixtures, match-sheet squads and staff) } model SportsCompetition { @@ -1635,15 +1642,21 @@ model CloudSource { lastScanAt DateTime? @map("last_scan_at") nextScanAt DateTime? @map("next_scan_at") lastError String? @map("last_error") + /// When the worker last wrote this archive's teams. Null until that first write: the site keeps loading. + directoryBuiltAt DateTime? @map("directory_built_at") + /// Set when a match, a club alias or a known team changed. The worker rewrites the teams, then clears it. + directoryDirtyAt DateTime? @map("directory_dirty_at") createdAt DateTime @default(now()) @map("created_at") updatedAt DateTime @updatedAt @map("updated_at") organization Organization @relation(fields: [organizationId], references: [id], onDelete: Cascade) folders CloudFolder[] files CloudFile[] + videos CloudVideo[] grants ArchiveGrant[] faceActions ArchiveFaceAction[] clubAliases ArchiveClubAlias[] + teamSides ArchiveTeamSide[] @@index([organizationId]) @@map("cloud_sources") @@ -1661,6 +1674,8 @@ model CloudFolder { parentId String? @map("parent_id") @db.Uuid /// Images directly inside. photoCount Int @default(0) @map("photo_count") + /// Videos directly inside (a gallery can hold photos, videos or both). + videoCount Int @default(0) @map("video_count") eventId String? @map("event_id") @db.Uuid /// How the event was found: FIXTURE (the official game), NAME (from the folder name), MANUAL, or null. matchedBy String? @map("matched_by") @@ -1679,6 +1694,7 @@ model CloudFolder { galleryFolder CloudFolder? @relation("GalleryMembers", fields: [galleryFolderId], references: [id], onDelete: SetNull) galleryMembers CloudFolder[] @relation("GalleryMembers") files CloudFile[] + videos CloudVideo[] grants ArchiveGrantFolder[] @@unique([sourceId, fileId]) @@ -1717,6 +1733,81 @@ model CloudFile { @@map("cloud_files") } +/// A video in an archive folder. The original stays on the cloud; the archive keeps a web copy (H.264 MP4, at most +/// 1080p, faststart), a poster and a thumbnail under `storageKey` (a folder: web.mp4, poster.jpg, thumb.jpg). +model CloudVideo { + id String @id @default(uuid()) @db.Uuid + sourceId String @map("source_id") @db.Uuid + folderId String @map("folder_id") @db.Uuid + fileId String @map("file_id") + path String + etag String? + size BigInt? + /// PENDING (to make its web copy), WORKING, DONE, FAILED. + status String @default("PENDING") + attempts Int @default(0) + error String? + durationMs Int? @map("duration_ms") + width Int? + height Int? + /// The camera's time, when the file says it. + capturedAt DateTime? @map("captured_at") + /// Folder of its files in storage ("/videos/"), set once made. + storageKey String? @map("storage_key") + /// Size of the web copy. + webBytes BigInt? @map("web_bytes") + /// Faces in the video (frames through the same engine as the photos): NONE (organization without biometrics), + /// PENDING, RUNNING, DONE, FAILED. + facesStatus FacesStatus @default(NONE) @map("faces_status") + createdAt DateTime @default(now()) @map("created_at") + updatedAt DateTime @updatedAt @map("updated_at") + + source CloudSource @relation(fields: [sourceId], references: [id], onDelete: Cascade) + folder CloudFolder @relation(fields: [folderId], references: [id], onDelete: Cascade) + faces VideoFace[] + + @@unique([sourceId, fileId]) + @@index([status, sourceId]) + @@index([folderId, status, path]) + @@index([facesStatus]) + @@map("cloud_videos") +} + +/// One appearance of a face in an archive video: the same face followed through consecutive frames (each frame +/// analysed by the same engine as the photos). It joins the event's face groups like a photo's face, so naming, +/// suggestions, "não é" and false positives are the photos' own. +model VideoFace { + id String @id @default(uuid()) @db.Uuid + videoId String @map("video_id") @db.Uuid + groupId String? @map("group_id") @db.Uuid + /// When it is on screen (ms from the start), and the frame it is clearest in. + startMs Int @map("start_ms") + endMs Int @map("end_ms") + atMs Int @map("at_ms") + /// Box in that frame, in fractions (0 to 1, y down). + x0 Float + y0 Float + x1 Float + y1 Float + score Float + sharpness Float? + /// Mean of the appearance's sharp embeddings (unit length), from `model`. + embedding Float[] @default([]) + model String + /// Frames it was found in. + frames Int + /// That frame as a JPEG in storage (shown when the face is reviewed). + frameKey String @map("frame_key") + createdAt DateTime @default(now()) @map("created_at") + + video CloudVideo @relation(fields: [videoId], references: [id], onDelete: Cascade) + group FaceGroup? @relation(fields: [groupId], references: [id], onDelete: SetNull) + + @@index([videoId]) + @@index([groupId]) + @@map("video_faces") +} + /// What one viewer may see, written when they sign in. Later pages read this row; they do not call the cloud again. /// Shares stay as they were at sign-in until the session ends. model ArchiveGrant { @@ -1811,3 +1902,20 @@ model ArchiveClubAlias { @@unique([sourceId, aliasKey]) @@map("archive_club_aliases") } + +/// One side of one game in an archive, under the single name the teams list shows. Written by the worker. +model ArchiveTeamSide { + sourceId String @map("source_id") @db.Uuid + eventId String @map("event_id") @db.Uuid + /// The side as the event stores it (or one club of a "A / B" side). What the gallery filter matches. + raw String + /// The directory's name for it. + name String + + source CloudSource @relation(fields: [sourceId], references: [id], onDelete: Cascade) + event Event @relation(fields: [eventId], references: [id], onDelete: Cascade) + + @@id([sourceId, eventId, raw]) + @@index([sourceId, name]) + @@map("archive_team_sides") +} diff --git a/apps/api/src/app.ts b/apps/api/src/app.ts index f76cb86..1db9910 100644 --- a/apps/api/src/app.ts +++ b/apps/api/src/app.ts @@ -26,6 +26,7 @@ import { registerUploadRoutes } from "./library/uploads.js"; import { IngestService } from "./ingest/service.js"; import { CorrectionRecorder } from "./autopilot/learning.js"; import { registerAutopilotRoutes } from "./autopilot/routes.js"; +import { registerRealEstateRoutes } from "./realestate/routes.js"; import { registerDevelopRoutes } from "./develop/routes.js"; import { DevelopService } from "./develop/service.js"; import { registerFaceRoutes } from "./faces/routes.js"; @@ -111,7 +112,7 @@ export async function buildApp({ config, db, realtime, fetchImpl, reporter: give const secrets = config.DELIVERY_SECRET_KEY ? new SecretBox(config.DELIVERY_SECRET_KEY) : undefined; const sports = new SportsService({ db, storage, log: app.log, fetch: fetchImpl ?? fetch }); // Archive clouds: the API connects them, matches galleries and streams originals; the worker walks and indexes. - const archive = new ArchiveService({ db, secrets, log: app.log, syncSquads: (id) => sports.syncEventSquads(id), ligaSeason: (season) => sports.importLigaSeason(season), storageRoot: config.STORAGE_ROOT, minFreeBytes: config.ARCHIVE_MIN_FREE_GB * 1e9, ...(fetchImpl && { fetchImpl }) }); + const archive = new ArchiveService({ db, secrets, log: app.log, syncSquads: (id) => sports.syncEventSquads(id), ligaSeason: (season) => sports.importLigaSeason(season), storageRoot: config.STORAGE_ROOT, minFreeBytes: config.ARCHIVE_MIN_FREE_GB * 1e9, storage, ...(fetchImpl && { fetchImpl }) }); const delivery = new DeliveryService({ db, storage, secrets, broadcaster, log: app.log, originals: archive, ...(fetchImpl && { fetchImpl }) }); registerErrorHandler(app); @@ -196,6 +197,7 @@ export async function buildApp({ config, db, realtime, fetchImpl, reporter: give const develop = new DevelopService({ db, storage, signer, broadcaster, log: app.log, onHumanEdit: (id) => corrections.schedule(id) }); await registerDevelopRoutes(app, { db, sessions, develop }); await registerAutopilotRoutes(app, { db, sessions }); + await registerRealEstateRoutes(app, { db, sessions }); // Shop: the public sites read galleries and place orders; the worker renders the bought files. const print = new PrintService({ db, storage, signer, broadcaster, log: app.log, secret: config.JWT_SECRET, secrets, stripeApiUrl: config.STRIPE_API_URL, ...(fetchImpl && { fetchImpl }) }); const notifications = new Notifications(db, (err) => app.log.warn({ err }, "notifications: not written")); diff --git a/apps/api/src/archive/clubs.test.ts b/apps/api/src/archive/clubs.test.ts new file mode 100644 index 0000000..8f3c810 --- /dev/null +++ b/apps/api/src/archive/clubs.test.ts @@ -0,0 +1,84 @@ +import { describe, expect, it } from "vitest"; +import { teamSideRows } from "./directory.js"; +import { clubTeamIds, isNationalSide, isTeam, teamMatcher } from "./match.js"; +import { clubKind } from "./people.js"; +import { isSquadSide, officialClub, sameClubName } from "../sports/fpa-siglas.js"; + +describe("one club, from the sigla list", () => { + it("joins the sigla and the name, and a sponsor written after a slash", () => { + expect(officialClub("SLB")).toBe("SL Benfica"); + expect(sameClubName("SL BENFICA")).toBe("SL Benfica"); + expect(sameClubName("Benfica")).toBe("SL Benfica"); + expect(sameClubName("Sport Lisboa e Benfica")).toBe("SL Benfica"); + expect(sameClubName("AAAS")).toBe("Águas Santas Milaneza"); + expect(sameClubName("Águas Santas")).toBe("Águas Santas Milaneza"); + expect(sameClubName("AGUAS SANTAS")).toBe("Águas Santas Milaneza"); + expect(sameClubName("FC PORTO / SOFARMA")).toBe("FC Porto"); + expect(sameClubName("SCP")).toBe("Sporting CP"); + expect(sameClubName("Sporting")).toBe("Sporting CP"); + }); + + it("does not join a youth side, or two clubs, or a different Benfica", () => { + expect(isSquadSide("SL BENFICA 'A'")).toBe(true); + expect(isSquadSide("Benfica B")).toBe(true); + expect(isSquadSide("SLB")).toBe(false); + expect(sameClubName("SL BENFICA 'A'")).toBeUndefined(); + expect(sameClubName("Benfica B")).toBeUndefined(); + expect(sameClubName("C BENFICA C BRANCO")).toBeUndefined(); + expect(sameClubName("Benfica / Porto")).toBeUndefined(); + expect(sameClubName("ALMADA AC / EXT. GIL EANES")).toBeUndefined(); + }); + + it("keeps a club code that is also a country code, and names real countries", () => { + expect(sameClubName("BEL")).toBe("CF Os Belenenses"); + expect(sameClubName("MAR")).toBe("Marítimo Madeira Andebol SAD"); + expect(isNationalSide("BEL")).toBe(false); + expect(isNationalSide("MAR")).toBe(false); + expect(isNationalSide("Espanha")).toBe(true); + expect(isNationalSide("Spain")).toBe(true); + expect(isNationalSide("ESP")).toBe(true); + expect(isNationalSide("Marrocos")).toBe(true); + expect(isNationalSide("Bélgica")).toBe(true); + expect(clubKind("Espanha")).toBe("national"); + expect(clubKind("Espanha Feminina")).toBe("national"); + expect(clubKind("SL Benfica")).toBe("club"); + expect(clubKind("BEL")).toBe("club"); + }); + + it("stores one label for the sigla and the name, and a country apart from the clubs", () => { + const rows = teamSideRows( + [ + { id: "1", home: "SLB", away: "AAAS" }, + { id: "2", home: "SL Benfica", away: "Águas Santas" }, + { id: "3", home: "ESP", away: "Portugal" }, + { id: "4", home: "SL BENFICA 'A'", away: "C BENFICA C BRANCO" }, + { id: "5", home: "BEL", away: "MAR" }, + ], + teamMatcher([]), + new Map(), + ); + const name = (id: string, raw: string) => rows.find((row) => row.eventId === id && row.raw === raw)?.name; + expect(name("1", "SLB")).toBe("SL Benfica"); + expect(name("2", "SL Benfica")).toBe("SL Benfica"); + expect(name("1", "AAAS")).toBe("Águas Santas Milaneza"); + expect(name("2", "Águas Santas")).toBe("Águas Santas Milaneza"); + expect(name("3", "ESP")).toBe("Espanha"); + expect(name("3", "Portugal")).toBe("Portugal"); + expect(name("4", "SL BENFICA 'A'")).toBe("SL BENFICA 'A'"); + expect(name("4", "C BENFICA C BRANCO")).toBe("C BENFICA C BRANCO"); + expect(name("5", "BEL")).toBe("CF Os Belenenses"); + expect(name("5", "MAR")).toBe("Marítimo Madeira Andebol SAD"); + const rowsOf = (side: string) => + clubTeamIds(side, [ + { id: "senior", name: "SL BENFICA", abbreviation: null, slug: "sl-benfica" }, + { id: "again", name: "SL Benfica", abbreviation: "SLB", slug: "sl-benfica-2" }, + { id: "youth", name: "SL BENFICA 'A'", abbreviation: null, slug: "sl-benfica-a" }, + { id: "other", name: "C BENFICA C BRANCO", abbreviation: null, slug: "c-benfica" }, + ]).map((team) => team.id); + expect(rowsOf("SLB").sort()).toEqual(["again", "senior"]); + expect(rowsOf("SL BENFICA 'A'")).toEqual([]); + expect(isTeam("MAR", { name: "Marítimo Madeira Andebol SAD", abbreviation: null, slug: "maritimo" })).toBe(true); + expect(isTeam("SLB", { name: "Sporting CP", abbreviation: "SCP", slug: "sporting-cp" })).toBe(false); + expect(isTeam("AAAS", { name: "AA Águas Santas 'B'", abbreviation: null, slug: "aa-b" })).toBe(false); + }); +}); diff --git a/apps/api/src/archive/corrupt-source.test.ts b/apps/api/src/archive/corrupt-source.test.ts new file mode 100644 index 0000000..000f6b9 --- /dev/null +++ b/apps/api/src/archive/corrupt-source.test.ts @@ -0,0 +1,84 @@ +import { mkdtemp, writeFile, rm } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { afterEach, describe, expect, it } from "vitest"; +import { + assertDownloadComplete, + CorruptSource, + IncompleteDownload, + isCorruptSourceMessage, + isDecodableImage, +} from "./corrupt-source.js"; + +describe("corrupt / incomplete archive sources (BIT-31621)", () => { + const dirs: string[] = []; + afterEach(async () => { + await Promise.all(dirs.splice(0).map((d) => rm(d, { recursive: true, force: true }))); + }); + + it("recognises ffprobe moov / invalid-data messages as corrupt sources", () => { + expect( + isCorruptSourceMessage( + "ffprobe exited 1: [mov,mp4,m4a,3gp,3g2,mj2 @ 0x5c2e6ee11e00] moov atom not found | /tmp/x.mp4: Invalid data found when processing input", + ), + ).toBe(true); + expect(isCorruptSourceMessage("Input file has corrupt header")).toBe(true); + expect(isCorruptSourceMessage("premature end of JPEG")).toBe(true); + expect(isCorruptSourceMessage("Input file contains unsupported image format")).toBe(true); + expect(isCorruptSourceMessage("VipsForeignLoad: \"/tmp/x/original.jpg\" is not a known file format")).toBe(true); + expect(isCorruptSourceMessage("ffmpeg exited 234: Stream map '0:v:0' matches no streams")).toBe(false); + expect(isCorruptSourceMessage("GET /a failed: 503")).toBe(false); + }); + + it("isDecodableImage accepts real JPEG/PNG/WebP and rejects HEIC/RAW/error bodies (BIT-31229)", async () => { + const dir = await mkdtemp(path.join(tmpdir(), "pr-corrupt-")); + dirs.push(dir); + const jpeg = path.join(dir, "a.jpg"); + await writeFile(jpeg, Buffer.from([0xff, 0xd8, 0xff, 0xe0, 0x00, 0x10, 0x4a, 0x46, 0x49, 0x46])); + await expect(isDecodableImage(jpeg)).resolves.toBe(true); + const png = path.join(dir, "a.png"); + await writeFile(png, Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d])); + await expect(isDecodableImage(png)).resolves.toBe(true); + const webp = path.join(dir, "a.webp"); + await writeFile(webp, Buffer.from([0x52, 0x49, 0x46, 0x46, 0x00, 0x00, 0x00, 0x00, 0x57, 0x45, 0x42, 0x50])); + await expect(isDecodableImage(webp)).resolves.toBe(true); + // HEIC (ISO BMFF ftyp heic) saved with a .jpg name: not decodable here. + const heic = path.join(dir, "heic.jpg"); + await writeFile(heic, Buffer.from([0x00, 0x00, 0x00, 0x18, 0x66, 0x74, 0x79, 0x70, 0x68, 0x65, 0x69, 0x63])); + await expect(isDecodableImage(heic)).resolves.toBe(false); + // An error body (JSON) written where an image was expected. + const errBody = path.join(dir, "err.jpg"); + await writeFile(errBody, Buffer.from('{"error":"not found"}')); + await expect(isDecodableImage(errBody)).resolves.toBe(false); + // A truncated/empty file is not decodable. + const empty = path.join(dir, "empty.jpg"); + await writeFile(empty, Buffer.alloc(0)); + await expect(isDecodableImage(empty)).resolves.toBe(false); + }); + + it("passes when downloaded size matches the walk size", async () => { + const dir = await mkdtemp(path.join(tmpdir(), "pr-corrupt-")); + dirs.push(dir); + const file = path.join(dir, "a.mp4"); + await writeFile(file, Buffer.alloc(12)); + await expect(assertDownloadComplete(file, 12n)).resolves.toBeUndefined(); + await expect(assertDownloadComplete(file, null)).resolves.toBeUndefined(); + }); + + it("throws IncompleteDownload when bytes on disk differ from the walk size", async () => { + const dir = await mkdtemp(path.join(tmpdir(), "pr-corrupt-")); + dirs.push(dir); + const file = path.join(dir, "a.mp4"); + await writeFile(file, Buffer.alloc(4)); + await expect(assertDownloadComplete(file, 100n)).rejects.toBeInstanceOf(IncompleteDownload); + await expect(assertDownloadComplete(file, 100n)).rejects.toMatchObject({ + message: "incomplete_download:4/100", + }); + }); + + it("names CorruptSource for permanent cloud damage", () => { + const err = new CorruptSource(); + expect(err.name).toBe("CorruptSource"); + expect(err.message).toBe("corrupt_source"); + }); +}); diff --git a/apps/api/src/archive/corrupt-source.ts b/apps/api/src/archive/corrupt-source.ts new file mode 100644 index 0000000..9614c78 --- /dev/null +++ b/apps/api/src/archive/corrupt-source.ts @@ -0,0 +1,71 @@ +import { open, stat } from "node:fs/promises"; + +/** + * Damaged file in the cloud (broken JPEG/MP4, moov missing), not a codec/tool bug. + * Mark FAILED with no retry until the walk sees a new etag; log at info — never the error hub. + */ +export class CorruptSource extends Error { + constructor(reason = "corrupt_source") { + super(reason); + this.name = "CorruptSource"; + } +} + +/** + * Downloaded bytes do not match the size the walk stored (truncated GET / still uploading). + * Requeue and retry later; after MAX_ATTEMPTS mark FAILED as corrupt_source. + */ +export class IncompleteDownload extends Error { + constructor(got: bigint, expected: bigint) { + super(`incomplete_download:${got}/${expected}`); + this.name = "IncompleteDownload"; + } +} + +/** ffprobe/ffmpeg/sharp messages that mean the cloud file itself is damaged, not our pipeline. */ +export function isCorruptSourceMessage(message: string): boolean { + return /moov atom not found|premature end|not a known file format|corrupt (?:jpeg )?header|Corrupt JPEG|Input file has corrupt header|Input file contains unsupported image format|unsupported image format|Invalid data found when processing input/i.test( + message, + ); +} + +/** + * Magic bytes of image formats sharp/libvips can decode in this build. A .jpg whose bytes are not one of these is + * a mislabelled HEIC/RAW or an error body written as an image — sharp would throw on it (BIT-31229). + */ +const DECODABLE_IMAGE: { offset: number; bytes: number[] }[] = [ + { offset: 0, bytes: [0xff, 0xd8, 0xff] }, // JPEG + { offset: 0, bytes: [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a] }, // PNG + { offset: 0, bytes: [0x47, 0x49, 0x46, 0x38] }, // GIF + { offset: 0, bytes: [0x42, 0x4d] }, // BMP + { offset: 0, bytes: [0x49, 0x49, 0x2a, 0x00] }, // TIFF little-endian + { offset: 0, bytes: [0x4d, 0x4d, 0x00, 0x2a] }, // TIFF big-endian + { offset: 8, bytes: [0x57, 0x45, 0x42, 0x50] }, // WebP (RIFF....WEBP) +]; + +/** + * True if the file's magic bytes are a format sharp can decode here. Used before vips so a mislabelled .jpg + * (HEIC/RAW or an error body saved as an image) is marked FAILED once at info level, not one hub ticket per file. + * Unreadable files return true so the existing download/stat flow surfaces the real error. + */ +export async function isDecodableImage(file: string): Promise { + let handle; + try { + handle = await open(file, "r"); + const buf = Buffer.alloc(12); + const { bytesRead } = await handle.read(buf, 0, 12, 0); + if (bytesRead < 4) return false; + return DECODABLE_IMAGE.some(({ offset, bytes }) => offset + bytes.length <= bytesRead && bytes.every((b, i) => buf[offset + i] === b)); + } catch { + return true; + } finally { + await handle?.close().catch(() => undefined); + } +} + +/** Downloaded bytes must match the WebDAV size the walk stored (truncated GET → retry later). */ +export async function assertDownloadComplete(file: string, expected: bigint | null): Promise { + if (expected === null) return; + const got = BigInt((await stat(file)).size); + if (got !== expected) throw new IncompleteDownload(got, expected); +} diff --git a/apps/api/src/archive/directory.ts b/apps/api/src/archive/directory.ts new file mode 100644 index 0000000..288a1ba --- /dev/null +++ b/apps/api/src/archive/directory.ts @@ -0,0 +1,91 @@ +import { Prisma } from "../generated/prisma/client.js"; +import type { Db } from "../db.js"; +import { shownClub } from "./labels.js"; +import { directorySides, type TeamMatch } from "./match.js"; +import { clubKey } from "./people.js"; + +/** One stored side of one game: the name as written, and the one name the directory shows. */ +export interface TeamSideRow { + eventId: string; + raw: string; + name: string; +} + +const fold = (value: string) => + value + .normalize("NFD") + .replace(/[\u0300-\u036f]/g, "") + .toLowerCase() + .replace(/[^a-z0-9]+/g, " ") + .trim(); + +/** + * The rows the worker stores. Same naming as the old on-request directory: a date or number before the name is + * dropped, a known team becomes its official name, and "Juntar nomes" wins. Two spellings of one club are one label. + */ +export function teamSideRows( + games: Iterable<{ id: string; home: string; away: string }>, + canonical: TeamMatch, + aliasOf: ReadonlyMap, +): TeamSideRow[] { + const rows: TeamSideRow[] = []; + const byKey = new Map(); + for (const game of games) { + const seen = new Set(); + const sides = [game.home, game.away].flatMap((side) => (side ? directorySides(side, (name) => canonical.knownName(name)) : [])); + for (const raw of sides) { + if (!raw || seen.has(raw)) continue; + seen.add(raw); + // The sigla list and the country names win over whichever spelling the folder used. "Juntar nomes" still wins. + let name = shownClub(raw) ?? canonical(raw); + if (aliasOf.size) name = aliasOf.get(clubKey(raw)) ?? aliasOf.get(clubKey(name)) ?? name; + const key = fold(name); + const label = byKey.get(key) ?? name; + byKey.set(key, label); + rows.push({ eventId: game.id, raw, name: label }); + } + } + return rows; +} + +/** A viewer's games: published, with photos, not an occasion folder, and inside the folders they may see. */ +function visibleGame(sourceId: string, visible: string[] | "all"): Prisma.Sql { + const scope = visible === "all" ? Prisma.sql`TRUE` : visible.length ? Prisma.sql`f.id = ANY(${visible}::uuid[])` : Prisma.sql`FALSE`; + return Prisma.sql` + EXISTS ( + SELECT 1 FROM cloud_folders f + WHERE f.event_id = s.event_id + AND f.source_id = ${sourceId}::uuid + AND f.published + AND (f.photo_count > 0 OR f.video_count > 0) + AND f.matched_by IS DISTINCT FROM 'FOLDER' + AND ${scope} + )`; +} + +/** Teams already stored for this source, counted once per game the viewer may see. Empty when nothing is stored yet. */ +export async function readStoredTeams( + db: Db, + sourceId: string, + visible: string[] | "all", +): Promise<{ name: string; galleries: number }[]> { + const rows = await db.$queryRaw<{ name: string; galleries: number }[]>` + SELECT s.name, count(DISTINCT s.event_id)::int AS galleries + FROM archive_team_sides s + WHERE s.source_id = ${sourceId}::uuid + AND ${visibleGame(sourceId, visible)} + GROUP BY s.name + ORDER BY galleries DESC, s.name`; + return rows.map((row) => ({ name: row.name, galleries: Number(row.galleries) })); +} + +/** Folder names a stored team was written as, so the gallery filter finds every game of it. */ +export async function readStoredRaws(db: Db, sourceId: string, team: string, visible: string[] | "all"): Promise { + const rows = await db.$queryRaw<{ raw: string }[]>` + SELECT DISTINCT s.raw + FROM archive_team_sides s + WHERE s.source_id = ${sourceId}::uuid + AND s.name = ${team} + AND ${visibleGame(sourceId, visible)}`; + return rows.map((row) => row.raw); +} diff --git a/apps/api/src/archive/gallery.ts b/apps/api/src/archive/gallery.ts index c5edbc2..67287e1 100644 --- a/apps/api/src/archive/gallery.ts +++ b/apps/api/src/archive/gallery.ts @@ -49,6 +49,7 @@ export interface StoredGallery { /** The folder above the gallery (a tournament with a gallery per day or group). */ group: string | null; photoCount: number; + videoCount: number; startsAt: Date | null; home: string | null; away: string | null; @@ -76,7 +77,7 @@ export async function listStoredGalleries( const filters: Prisma.Sql[] = [ Prisma.sql`f.source_id = ${args.sourceId}::uuid`, Prisma.sql`f.published`, - Prisma.sql`f.photo_count > 0`, + Prisma.sql`(f.photo_count > 0 OR f.video_count > 0)`, Prisma.sql`f.event_id IS NOT NULL`, ]; if (args.visible !== "all") filters.push(Prisma.sql`f.id = ANY(${args.visible}::uuid[])`); @@ -96,9 +97,9 @@ export async function listStoredGalleries( const cardWhere = Prisma.join(cardFilters, " AND "); const order = args.sort === "photos" ? Prisma.sql`photo_count DESC, starts_at DESC NULLS LAST` : args.sort === "az" ? Prisma.sql`lower(COALESCE(home, path)), starts_at DESC NULLS LAST` : Prisma.sql`starts_at DESC NULLS LAST, path DESC`; - const rows = await db.$queryRaw<{ id: string; path: string; kind: GalleryKind; season: string | null; group_name: string | null; photo_count: number; starts_at: Date | null; home: string | null; away: string | null; competition: string | null; total: number }[]>` + const rows = await db.$queryRaw<{ id: string; path: string; kind: GalleryKind; season: string | null; group_name: string | null; photo_count: number; video_count: number; starts_at: Date | null; home: string | null; away: string | null; competition: string | null; total: number }[]>` WITH members AS ( - SELECT COALESCE(f.gallery_folder_id, f.id) AS gallery_id, f.photo_count, f.event_id, e.starts_at + SELECT COALESCE(f.gallery_folder_id, f.id) AS gallery_id, f.photo_count, f.video_count, f.event_id, e.starts_at FROM cloud_folders f JOIN events e ON e.id = f.event_id WHERE ${where} @@ -106,6 +107,7 @@ export async function listStoredGalleries( agg AS ( SELECT gallery_id, sum(photo_count)::int AS photo_count, + sum(video_count)::int AS video_count, count(DISTINCT event_id)::int AS n_events, (array_agg(DISTINCT event_id))[1] AS one_event, max(starts_at) AS latest @@ -113,7 +115,7 @@ export async function listStoredGalleries( GROUP BY gallery_id ), base AS ( - SELECT root.id, root.path, agg.photo_count, + SELECT root.id, root.path, agg.photo_count, agg.video_count, COALESCE(ev.starts_at, agg.latest) AS starts_at, ev.home, ev.away, ev.competition, CASE @@ -133,7 +135,7 @@ export async function listStoredGalleries( SELECT base.*, CASE WHEN season_start IS NULL THEN NULL ELSE season_start::text || '/' || lpad(((season_start + 1) % 100)::text, 2, '0') END AS season FROM base ) - SELECT id, path, kind, season, group_name, photo_count, starts_at, home, away, competition, count(*) OVER()::int AS total + SELECT id, path, kind, season, group_name, photo_count, video_count, starts_at, home, away, competition, count(*) OVER()::int AS total FROM cards WHERE ${cardWhere} ORDER BY ${order} @@ -151,6 +153,7 @@ export async function listStoredGalleries( season: row.season, group: row.group_name, photoCount: Number(row.photo_count), + videoCount: Number(row.video_count), startsAt: row.starts_at, home: row.home, away: row.away || null, @@ -180,7 +183,7 @@ export async function gallerySeasons(db: Db, sourceId: string, visible: string[] SELECT DISTINCT (extract(year FROM e.starts_at AT TIME ZONE 'Europe/Lisbon')::int - CASE WHEN extract(month FROM e.starts_at AT TIME ZONE 'Europe/Lisbon') >= 7 THEN 0 ELSE 1 END) AS s FROM cloud_folders f JOIN events e ON e.id = f.event_id - WHERE f.source_id = ${sourceId}::uuid AND f.published AND f.photo_count > 0 AND ${scope} + WHERE f.source_id = ${sourceId}::uuid AND f.published AND (f.photo_count > 0 OR f.video_count > 0) AND ${scope} ORDER BY s DESC`; return rows.map((r) => `${r.s}/${String((Number(r.s) + 1) % 100).padStart(2, "0")}`); } diff --git a/apps/api/src/archive/hub-noise.test.ts b/apps/api/src/archive/hub-noise.test.ts new file mode 100644 index 0000000..2a3c139 --- /dev/null +++ b/apps/api/src/archive/hub-noise.test.ts @@ -0,0 +1,52 @@ +import { mkdtemp, rm } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { describe, expect, it } from "vitest"; +import { isTransientStatus } from "../delivery/nextcloud.js"; +import { CloudClient } from "./nextcloud.js"; +import { ArchiveService } from "./service.js"; + +describe("isTransientStatus (BIT-31658 / BIT-31513)", () => { + it("covers lock, rate-limit and all 5xx including 502/504", () => { + for (const s of [0, 408, 423, 429, 500, 502, 503, 504]) expect(isTransientStatus(s)).toBe(true); + for (const s of [400, 401, 403, 404, 422]) expect(isTransientStatus(s)).toBe(false); + }); +}); + +describe("CloudClient 502 retry then success (BIT-31658)", () => { + it("retries a 502 blip on a download and succeeds", async () => { + let calls = 0; + const fetchImpl: typeof fetch = async (input) => { + const url = new URL(String(input)); + if (url.pathname.endsWith("/ocs/v2.php/cloud/user")) return Response.json({ ocs: { data: { id: "peter" } } }); + calls++; + return calls <= 2 ? new Response(null, { status: 502 }) : new Response(new Uint8Array(Buffer.from("hello")), { status: 200 }); + }; + const client = new CloudClient({ baseUrl: "https://cloud.test", username: "peter", password: "pw" }, fetchImpl); + const dir = await mkdtemp(path.join(tmpdir(), "pr-502-")); + try { + await client.download("/a.jpg", path.join(dir, "out.jpg")); + expect(calls).toBe(3); + } finally { + await rm(dir, { recursive: true, force: true }); + } + }); +}); + +describe("index failures reach the error hub once per burst (BIT-31658)", () => { + it("coalesces permanent failures into one warn with a count and a few paths", () => { + const warns: { obj: Record; msg: string }[] = []; + const log = { info() {}, debug() {}, error() {}, warn: (obj: Record, msg: string) => warns.push({ obj, msg }) }; + const service = new ArchiveService({ log } as never); + for (let i = 0; i < 7; i++) service.noteIndexFailure(new Error(`boom ${i}`), `/a/${i}.jpg`); + expect(warns).toEqual([]); + service.flushIndexFailures(); + expect(warns).toHaveLength(1); + expect(warns[0]!.msg).toBe("archive: 7 files failed indexing after retries"); + expect(warns[0]!.obj).toMatchObject({ count: 7, paths: ["/a/0.jpg", "/a/1.jpg", "/a/2.jpg", "/a/3.jpg", "/a/4.jpg"] }); + expect((warns[0]!.obj.err as Error).message).toBe("boom 0"); + // Nothing waiting: a second flush stays quiet. + service.flushIndexFailures(); + expect(warns).toHaveLength(1); + }); +}); diff --git a/apps/api/src/archive/labels.ts b/apps/api/src/archive/labels.ts new file mode 100644 index 0000000..1f14c48 --- /dev/null +++ b/apps/api/src/archive/labels.ts @@ -0,0 +1,12 @@ +import { nationalSideName } from "./match.js"; +import { isSquadSide, sameClubName } from "../sports/fpa-siglas.js"; + +/** + * The one name the archive shows for a side. A sigla or a sponsor form becomes the official club ("SLB" and + * "Águas Santas" are not two clubs). A country becomes its Portuguese name ("ESP" → Espanha). A youth side is + * left alone (null), and so is a name this does not know: the caller keeps the team it already resolved. + */ +export function shownClub(raw: string): string | null { + if (!raw.trim() || isSquadSide(raw)) return null; + return sameClubName(raw) ?? nationalSideName(raw); +} diff --git a/apps/api/src/archive/match.ts b/apps/api/src/archive/match.ts index f17ec61..3b15028 100644 --- a/apps/api/src/archive/match.ts +++ b/apps/api/src/archive/match.ts @@ -1,5 +1,5 @@ import { sameTeam, sameWords, words } from "../delivery/zerozero.js"; -import { officialSigla } from "../sports/fpa-siglas.js"; +import { officialClub, officialSigla, sameClubName } from "../sports/fpa-siglas.js"; /** * What a gallery folder's place and name say about its game. The archives are organised by season, competition @@ -396,6 +396,7 @@ const COUNTRIES: Record = { can: "Canadá", egy: "Egito", egypt: "Egito", tun: "Tunísia", alg: "Argélia", mar: "Marrocos", ang: "Angola", cpv: "Cabo Verde", jpn: "Japão", kor: "Coreia do Sul", chn: "China", qat: "Catar", ksa: "Arábia Saudita", bah: "Bahrein", kuw: "Kuwait", iri: "Irão", ind: "Índia", gbr: "Grã-Bretanha", eng: "Inglaterra", irl: "Irlanda", lux: "Luxemburgo", sui: "Suíça", + uru: "Uruguai", uruguay: "Uruguai", }; function countryName(name: string): string { @@ -404,9 +405,23 @@ function countryName(name: string): string { let countryNames: Set | null = null; +/** + * The Portuguese name when this side is a country ("ESP", "Spain", "Espanha" → Espanha). Null for a club, including + * a sigla that is also a country code ("MAR" is Marítimo, "BEL" is Belenenses). + */ +export function nationalSideName(name: string | null | undefined): string | null { + if (!name || sameClubName(name)) return null; + const n = fold(name.trim()); + if (!n) return null; + if (COUNTRIES[n]) return COUNTRIES[n]; + countryNames ??= new Set(Object.values(COUNTRIES).map(fold)); + if (!countryNames.has(n)) return null; + return Object.values(COUNTRIES).find((value) => fold(value) === n) ?? null; +} + /** A national team's side ("Portugal", "POR", "Seleção Nacional A") rather than a club. */ export function isNationalSide(name: string | null | undefined): boolean { - if (!name) return false; + if (!name || sameClubName(name)) return false; const n = fold(name.trim()); countryNames ??= new Set(Object.values(COUNTRIES).map(fold)); return !!COUNTRIES[n] || countryNames.has(n) || /sele[cç][aãoõ]/i.test(name); @@ -474,6 +489,25 @@ export const isVariantSide = (s: string) => s.normalize("NFD").replace(/[\u0300-\u036f]/g, ""), ); +/** Every team this side names. One hit is that club; several is ambiguous (the caller does not guess). */ +export function teamsNamed(name: string, teams: T[]): T[] { + return teams.filter((t) => isTeam(name, t)); +} + +/** + * Every stored row of this side's club ("SLB" and "SL BENFICA" are one club, including rows per season). + * One team when the side is not on the sigla list and exactly one team fits. None when it is ambiguous. + * A youth side is not the first team's rows. + */ +export function clubTeamIds(side: string, teams: T[]): T[] { + const club = sameClubName(side); + if (club) { + return teams.filter((team) => sameClubName(team.name) === club || (!!team.abbreviation && sameClubName(team.abbreviation) === club)); + } + const hits = teamsNamed(side, teams); + return hits.length === 1 ? hits : []; +} + export function isTeam(name: string, team: { name: string; abbreviation: string | null; slug: string }): boolean { const n = fold(name); if (!n) return false; @@ -486,6 +520,10 @@ export function isTeam(name: string, team: { name: string; abbreviation: string // ("Águas Santas Milaneza" is A, S, M), and these teams have no abbreviation of their own. const sigla = officialSigla(team.name); if (sigla && fold(sigla) === n) return true; + // "MAR" and "Marítimo" are one club on the sigla list, even when the stored name is not the initials. + const sideClub = officialClub(name); + const teamClub = officialClub(team.name); + if (sideClub && teamClub && sideClub === teamClub) return true; return name.trim().length <= 6 && !/\s/.test(name.trim()) && isInitials(name, team.name); } @@ -599,7 +637,8 @@ export type TeamMatch = ((name: string) => string) & { knownName(name: string): export function teamMatcher(teams: readonly TeamRef[]): TeamMatch { const prepared = teams.map((t) => { const sigla = officialSigla(t.name); - return { t, variant: isVariantSide(t.name), abbr: fold(t.abbreviation ?? ""), slug: fold(t.slug), name: fold(t.name), words: words(t.name), sigla: sigla ? fold(sigla) : "" }; + const club = officialClub(t.name) ?? ""; + return { t, variant: isVariantSide(t.name), abbr: fold(t.abbreviation ?? ""), slug: fold(t.slug), name: fold(t.name), words: words(t.name), sigla: sigla ? fold(sigla) : "", club }; }); const knownName = (raw: string): string | null => { const label = teamLabel(raw); @@ -609,6 +648,7 @@ export function teamMatcher(teams: readonly TeamRef[]): TeamMatch { const variant = isVariantSide(label); const nameWords = words(label); const short = label.trim().length <= 6 && !/\s/.test(label.trim()); + const sideClub = officialClub(label) ?? ""; const fits = new Map(); for (const p of prepared) { // The same tests as isTeam, in the same order. @@ -619,6 +659,7 @@ export function teamMatcher(teams: readonly TeamRef[]): TeamMatch { p.name === n || sameWords(nameWords, p.words) || (!!p.sigla && p.sigla === n) || + (!!sideClub && p.club === sideClub) || (short && isInitials(label, p.t.name)); if (fit) fits.set(p.name, p.t); } diff --git a/apps/api/src/archive/nextcloud.ts b/apps/api/src/archive/nextcloud.ts index 20a418d..5c2e12a 100644 --- a/apps/api/src/archive/nextcloud.ts +++ b/apps/api/src/archive/nextcloud.ts @@ -1,4 +1,5 @@ import { createWriteStream } from "node:fs"; +import { stat } from "node:fs/promises"; import { Readable } from "node:stream"; import { pipeline } from "node:stream/promises"; import { isTransientStatus, NextcloudError } from "../delivery/nextcloud.js"; @@ -218,12 +219,20 @@ export class CloudClient { return { self, children: entries.filter((e) => e !== self) }; } - /** Streams a file into `dest`. */ + /** Streams a file into `dest`. When Content-Length is present, refuse a short body (retry as transient 502). */ async download(path: string, dest: string): Promise { await this.resolveUser(); const res = await this.call("GET", this.davUrl(path)); if (!res.ok || !res.body) throw new NextcloudError(`GET ${path} failed: ${res.status}`, res.status); + const expected = res.headers.get("content-length"); await pipeline(Readable.fromWeb(res.body as never), createWriteStream(dest)); + if (expected != null && expected !== "") { + const want = Number(expected); + if (Number.isFinite(want) && want >= 0) { + const got = (await stat(dest)).size; + if (got !== want) throw new NextcloudError(`GET ${path} truncated: got ${got} want ${want}`, 502); + } + } } /** The response of a file download, for streaming it on (the editor's 100% view). */ diff --git a/apps/api/src/archive/people.ts b/apps/api/src/archive/people.ts index 05a0a5c..13ee955 100644 --- a/apps/api/src/archive/people.ts +++ b/apps/api/src/archive/people.ts @@ -7,9 +7,11 @@ import { boxInCrop, cropOfSettings } from "../faces/frame.js"; import { cosine, inFocus, THRESHOLDS } from "../faces/math.js"; import { notFound } from "../lib/errors.js"; import type { UrlSigner } from "../storage/storage.js"; -import { publishedPhotos } from "./gallery.js"; +import { gallerySeasons, publishedPhotos } from "./gallery.js"; +import { shownClub } from "./labels.js"; import { isNationalSide } from "./match.js"; import type { Viewer } from "./viewer.js"; +import { videoFaceCrop, videoScope } from "./video-faces.js"; /** * People in the archive, for its viewers: who appears in the galleries they may see (named from faces), all the @@ -29,7 +31,37 @@ interface Deps { const SourceParams = z.object({ sourceId: z.uuid() }); const PersonParams = SourceParams.extend({ personId: z.uuid() }); const FaceParams = SourceParams.extend({ faceId: z.uuid() }); -const PeopleQuery = z.object({ q: z.string().trim().max(80).optional(), club: z.string().trim().max(120).optional() }); +const PeopleQuery = z.object({ + q: z.string().trim().max(80).optional(), + club: z.string().trim().max(120).optional(), + season: z.string().trim().max(16).optional(), +}); + +/** "2025/26", "2025/2026" or "20252026" → 2025. Null when it is not a season, so the list stays everyone. */ +export function seasonYear(raw: string | null | undefined): number | null { + const s = (raw ?? "").trim(); + if (!s) return null; + const slash = /^(\d{4})\s*\/\s*(\d{2}|\d{4})$/.exec(s); + if (slash) { + const start = Number(slash[1]); + const end = Number(slash[2]); + if (slash[2]!.length === 4) return end === start + 1 ? start : null; + if (end === (start + 1) % 100) return start; + return null; + } + const compact = /^(\d{4})(\d{4})$/.exec(s.replace(/\s/g, "")); + if (compact && Number(compact[2]) === Number(compact[1]) + 1) return Number(compact[1]); + return null; +} + +/** The event's season, July to June in Lisbon, when a year was asked for. */ +function inSeason(year: number | null): Prisma.Sql { + if (year == null) return Prisma.sql`TRUE`; + return Prisma.sql`( + extract(year FROM e.starts_at AT TIME ZONE 'Europe/Lisbon')::int + - CASE WHEN extract(month FROM e.starts_at AT TIME ZONE 'Europe/Lisbon') >= 7 THEN 0 ELSE 1 END + ) = ${year}`; +} const PhotosQuery = z.object({ level: z.enum(["all", "confirmed"]).default("all"), limit: z.coerce.number().int().min(1).max(600).default(300) }); /** How club names are compared: lowercase, no accents, single spaces. */ @@ -42,7 +74,10 @@ export function clubKind(name: string): "national" | "club" | "other" { const n = clubKey(name); if (!n || n === "sem clube" || n === "outros") return "other"; const base = name.trim().replace(/\s+(u|sub[- ]?)\d{2}$/i, "").replace(/\s+\((m|f|masc|fem)\)$/i, "").trim(); - return isNationalSide(name) || isNationalSide(base) ? "national" : "club"; + if (isNationalSide(name) || isNationalSide(base)) return "national"; + // "Espanha Feminina", "Portugal Sub-18": the country is the seleção, the rest is the squad. + const first = name.trim().split(/\s+/)[0] ?? ""; + return first && first !== name.trim() && isNationalSide(first) ? "national" : "club"; } /** The face, as a box in the preview's frame (an edited photo's preview is its crop). */ @@ -136,13 +171,15 @@ export async function registerArchivePeopleRoutes(app: FastifyInstance, deps: De const v = viewerOf(req, sourceId); const query = PeopleQuery.parse(req.query); const visible = await visibleFolders(v); - if (visible !== "all" && !visible.length) return { people: [], clubs: [] }; + if (visible !== "all" && !visible.length) return { people: [], clubs: [], seasons: [] }; const scope = visible === "all" ? Prisma.sql`cf.source_id = ${v.s}::uuid AND cf.status = 'DONE' AND cf.photo_id IS NOT NULL AND ${publishedPhotos}` : Prisma.sql`cf.source_id = ${v.s}::uuid AND cf.status = 'DONE' AND cf.photo_id IS NOT NULL AND cf.folder_id = ANY(${visible}::uuid[]) AND ${publishedPhotos}`; const folderLimit = visible === "all" ? Prisma.sql`cf.source_id = ${v.s}::uuid AND cf.published` : Prisma.sql`cf.source_id = ${v.s}::uuid AND cf.published AND cf.id = ANY(${visible}::uuid[])`; + const year = seasonYear(query.season); + const seasonSql = inSeason(year); const rows = await db.$queryRaw<{ id: string; name: string; club: string | null; number: string | null; reference: boolean; off: boolean; confirmed: bigint; probable: bigint }[]>` SELECT p.id, p.name, p.club, p.number, p.reference_key IS NOT NULL AS reference, p.recognition_off_at IS NOT NULL AS off, count(DISTINCT f.photo_id) FILTER (WHERE g.person_id = p.id) AS confirmed, @@ -151,16 +188,20 @@ export async function registerArchivePeopleRoutes(app: FastifyInstance, deps: De JOIN faces f ON f.group_id = g.id JOIN cloud_files cf ON cf.photo_id = f.photo_id JOIN people p ON p.id = coalesce(g.person_id, g.suggested_person_id) - WHERE g.ignored_at IS NULL AND ${scope} + JOIN events e ON e.id = g.event_id + WHERE g.ignored_at IS NULL AND ${scope} AND ${seasonSql} GROUP BY p.id`; const fold = (s: string) => s.normalize("NFD").replace(/[̀-ͯ]/g, "").toLowerCase(); // "Juntar nomes": other names of a club count as the club. const aliases = await db.archiveClubAlias.findMany({ where: { sourceId: v.s }, select: { aliasKey: true, alias: true, name: true } }); const aliasOf = new Map(aliases.map((a) => [a.aliasKey, a.name])); - const clubOf = (s: string) => aliasOf.get(clubKey(s)) ?? s; - const wanted = query.club ? clubKey(clubOf(query.club)) : null; + const labelOf = (s: string) => { + const base = shownClub(s) ?? s; + return aliasOf.get(clubKey(s)) ?? aliasOf.get(clubKey(base)) ?? base; + }; + const wanted = query.club ? clubKey(labelOf(query.club)) : null; const words = fold(query.q ?? "").split(/\s+/).filter(Boolean); - const shown = rows.filter((r) => (!wanted || (r.club && clubKey(clubOf(r.club)) === wanted)) && words.every((w) => fold(`${r.name} ${r.club ?? ""} ${r.number ?? ""}`).includes(w))); + const shown = rows.filter((r) => (!wanted || (r.club && clubKey(labelOf(r.club)) === wanted)) && words.every((w) => fold(`${r.name} ${r.club ?? ""} ${r.number ?? ""}`).includes(w))); // A face for those without a reference photo: their sharpest face in the visible photos. const noRef = shown.filter((r) => !r.reference).map((r) => r.id); const faces = noRef.length @@ -169,7 +210,8 @@ export async function registerArchivePeopleRoutes(app: FastifyInstance, deps: De FROM faces f JOIN face_groups g ON g.id = f.group_id JOIN cloud_files cf ON cf.photo_id = f.photo_id - WHERE coalesce(g.person_id, g.suggested_person_id) = ANY(${noRef}::uuid[]) AND g.ignored_at IS NULL AND ${scope} + JOIN events e ON e.id = g.event_id + WHERE coalesce(g.person_id, g.suggested_person_id) = ANY(${noRef}::uuid[]) AND g.ignored_at IS NULL AND ${scope} AND ${seasonSql} ORDER BY coalesce(g.person_id, g.suggested_person_id), (g.person_id IS NOT NULL) DESC, f.sharpness DESC NULLS LAST, f.score DESC` : []; const facePhotos = await db.photo.findMany({ where: { id: { in: faces.map((f) => f.photo_id) } }, select: { id: true, width: true, height: true, renderedSeq: true, developSnapshot: true } }); @@ -187,16 +229,16 @@ export async function registerArchivePeopleRoutes(app: FastifyInstance, deps: De FROM ( SELECT e.id AS event_id, e.home AS name FROM cloud_folders cf JOIN events e ON e.id = cf.event_id - WHERE ${folderLimit} AND cf.photo_count > 0 AND cf.matched_by IS DISTINCT FROM 'FOLDER' AND btrim(e.home) <> '' + WHERE ${folderLimit} AND cf.photo_count > 0 AND cf.matched_by IS DISTINCT FROM 'FOLDER' AND btrim(e.home) <> '' AND ${seasonSql} UNION ALL SELECT e.id, e.away FROM cloud_folders cf JOIN events e ON e.id = cf.event_id - WHERE ${folderLimit} AND cf.photo_count > 0 AND cf.matched_by IS DISTINCT FROM 'FOLDER' AND btrim(e.away) <> '' + WHERE ${folderLimit} AND cf.photo_count > 0 AND cf.matched_by IS DISTINCT FROM 'FOLDER' AND btrim(e.away) <> '' AND ${seasonSql} ) sides GROUP BY btrim(name)`; const clubs = new Map }>(); const add = (raw: string, people: number, games: number) => { - const name = clubOf(raw); + const name = labelOf(raw); const key = clubKey(name); const cur = clubs.get(key) ?? { name, people: 0, games: 0, also: new Set() }; cur.people += people; @@ -211,7 +253,7 @@ export async function registerArchivePeopleRoutes(app: FastifyInstance, deps: De .map((r) => ({ id: r.id, name: r.name, - club: r.club, + club: r.club ? labelOf(r.club) : null, number: r.number, photos: Number(r.confirmed), probable: Number(r.probable), @@ -223,6 +265,7 @@ export async function registerArchivePeopleRoutes(app: FastifyInstance, deps: De clubs: [...clubs.values()] .sort((a, b) => b.people - a.people || b.games - a.games || a.name.localeCompare(b.name)) .map(({ name, people, also }) => ({ name, people, kind: clubKind(name), ...(also.size && { also: [...also].sort() }) })), + seasons: await gallerySeasons(db, v.s, visible), }; }); @@ -260,7 +303,42 @@ export async function registerArchivePeopleRoutes(app: FastifyInstance, deps: De } const chosen = onePerPhoto(hits).slice(0, query.limit); const photos = scope ? await photoCards(chosen, scope) : []; + // The videos they appear in (named or probable), each with its clearest frame and every moment. + const visible = await visibleFolders(v); + const seen = + visible === "all" || visible.length + ? await db.$queryRaw<{ id: string; video_id: string; folder_id: string; name: string; confirmed: boolean; score: number | null; start_ms: number; end_ms: number; x0: number; y0: number; x1: number; y1: number; width: number | null; height: number | null; duration_ms: number | null; sharpness: number | null }[]>` + SELECT vf.id, vf.video_id, cv.folder_id, cv.path AS name, (g.person_id IS NOT NULL) AS confirmed, g.suggestion_score AS score, + vf.start_ms, vf.end_ms, vf.x0, vf.y0, vf.x1, vf.y1, cv.width, cv.height, cv.duration_ms, vf.sharpness + FROM video_faces vf + JOIN face_groups g ON g.id = vf.group_id AND g.ignored_at IS NULL + JOIN cloud_videos cv ON cv.id = vf.video_id AND ${videoScope(sourceId, visible)} + WHERE g.person_id = ${personId}::uuid OR (${query.level === "all"} AND g.person_id IS NULL AND g.suggested_person_id = ${personId}::uuid) + ORDER BY vf.start_ms` + : []; + const byVideo = new Map(); + for (const r of seen) byVideo.set(r.video_id, [...(byVideo.get(r.video_id) ?? []), r]); + const galleries = await galleryInfo(seen.map((r) => r.folder_id)); + const videos = [...byVideo.entries()].map(([videoId, list]) => { + const clearest = list.reduce((a, b) => ((b.sharpness ?? 0) > (a.sharpness ?? 0) ? b : a)); + return { + id: videoId, + name: clearest.name.split("/").pop(), + level: list.some((r) => r.confirmed) ? ("confirmed" as const) : ("probable" as const), + durationMs: clearest.duration_ms, + width: clearest.width, + height: clearest.height, + face: videoFaceCrop(signer, clearest), + moments: list.map((r) => ({ startMs: r.start_ms, endMs: r.end_ms })), + thumb: signer.videoUrl(videoId, "thumb"), + poster: signer.videoUrl(videoId, "poster"), + src: signer.videoUrl(videoId, "web"), + download: signer.videoUrl(videoId, "download"), + gallery: galleries.get(clearest.folder_id) ?? null, + }; + }); return { + videos, person: { id: person.id, name: person.name, club: person.club, number: person.number, reference: person.referenceKey ? signer.personUrl(person.id) : null }, counts: { confirmed: photos.filter((p) => p.level === "confirmed").length, probable: photos.filter((p) => p.level === "probable").length, similar: photos.filter((p) => p.level === "similar").length }, photos, diff --git a/apps/api/src/archive/review.ts b/apps/api/src/archive/review.ts index d0ad163..9ea6722 100644 --- a/apps/api/src/archive/review.ts +++ b/apps/api/src/archive/review.ts @@ -11,6 +11,7 @@ import type { FpaMember } from "../sports/providers.js"; import { galleryMemberIds } from "./gallery.js"; import { clubKey, faceBox } from "./people.js"; import type { Viewer } from "./viewer.js"; +import { videoFaceCrop, videoScope } from "./video-faces.js"; /** * Face review for archive viewers who may edit on the cloud. Rights come from the cloud, never from here: @@ -31,7 +32,7 @@ interface Deps { /** Handball: people by their federation licence (CIPA), for FPA archives. */ sports?: Pick | undefined; /** After "Juntar nomes": lists built with the old names are dropped. */ - onClubsChanged?: (sourceId: string) => void; + onClubsChanged?: (sourceId: string) => void | Promise; } const SourceParams = z.object({ sourceId: z.uuid() }); @@ -56,14 +57,28 @@ const Recognition = z.object({ enabled: z.boolean(), removeConfirmed: z.boolean( export async function registerArchiveReviewRoutes(app: FastifyInstance, deps: Deps) { const { db, signer, faces, viewerOf, editableFolders } = deps; - /** Indexed files of the source the viewer may edit, as a condition on `cf`; null when none. */ - const editScope = async (v: Viewer): Promise<{ sql: Prisma.Sql; all: boolean } | null> => { + /** + * Indexed files of the source the viewer may edit, as a condition on `cf` (photos) and on `cv` (videos); null when + * none. + */ + const editScope = async (v: Viewer): Promise<{ sql: Prisma.Sql; vsql: Prisma.Sql; vedit: Prisma.Sql; all: boolean } | null> => { const editable = await editableFolders(v); if (editable !== "all" && !editable.length) return null; const base = Prisma.sql`cf.source_id = ${v.s}::uuid AND cf.status = 'DONE' AND cf.photo_id IS NOT NULL`; - return editable === "all" ? { sql: base, all: true } : { sql: Prisma.sql`${base} AND cf.folder_id = ANY(${editable}::uuid[])`, all: false }; + return editable === "all" + ? { sql: base, vsql: videoScope(v.s, "all"), vedit: videoScope(v.s, "all", { edit: true }), all: true } + : { sql: Prisma.sql`${base} AND cf.folder_id = ANY(${editable}::uuid[])`, vsql: videoScope(v.s, editable), vedit: videoScope(v.s, editable, { edit: true }), all: false }; }; + /** + * What a face group holds within a scope: its photos' faces and its videos' appearances, one row each (`item` is + * the photo or the video), so a group of a video only is reviewed like any other. + */ + const members = (scope: { sql: Prisma.Sql; vsql: Prisma.Sql }) => Prisma.sql` + SELECT f.group_id, f.photo_id AS item, false AS video FROM faces f JOIN cloud_files cf ON cf.photo_id = f.photo_id AND ${scope.sql} + UNION ALL + SELECT vf.group_id, vf.video_id AS item, true AS video FROM video_faces vf JOIN cloud_videos cv ON cv.id = vf.video_id AND ${scope.vsql}`; + const log = (v: Viewer, action: string, data: { personId?: string | null; groupId?: string | null; faces?: number }) => db.archiveFaceAction.create({ data: { sourceId: v.s, viewer: v.n, action, personId: data.personId ?? null, groupId: data.groupId ?? null, faces: data.faces ?? 0 } }); @@ -78,9 +93,10 @@ export async function registerArchiveReviewRoutes(app: FastifyInstance, deps: De const scope = await editScope(v); if (!scope) return 0; const [row] = await db.$queryRaw<{ n: number }[]>` + WITH m AS (${members(scope)}) SELECT count(DISTINCT g.id)::int AS n - FROM face_groups g JOIN faces f ON f.group_id = g.id JOIN cloud_files cf ON cf.photo_id = f.photo_id - WHERE g.person_id IS NULL AND g.suggested_person_id IS NOT NULL AND g.ignored_at IS NULL AND ${scope.sql}`; + FROM face_groups g JOIN m ON m.group_id = g.id + WHERE g.person_id IS NULL AND g.suggested_person_id IS NOT NULL AND g.ignored_at IS NULL`; return row?.n ?? 0; })() : 0; @@ -131,13 +147,13 @@ export async function registerArchiveReviewRoutes(app: FastifyInstance, deps: De /** Handball archives look people up by licence. Kept a while: typing a number asks once per number. */ const fpaArchive = (source: { look: string | null }) => !!deps.sports && source.look === "fpa"; - const members = new Map }>(); + const memberCache = new Map }>(); const memberOf = (licence: string): Promise => { - const hit = members.get(licence); + const hit = memberCache.get(licence); if (hit && Date.now() - hit.at < 30 * 60_000) return hit.member; const member = deps.sports!.fpa.member(licence).catch(() => null); - members.set(licence, { at: Date.now(), member }); - if (members.size > 500) for (const [k, m] of members) if (Date.now() - m.at > 30 * 60_000) members.delete(k); + memberCache.set(licence, { at: Date.now(), member }); + if (memberCache.size > 500) for (const [k, m] of memberCache) if (Date.now() - m.at > 30 * 60_000) memberCache.delete(k); return member; }; const memberOut = (m: FpaMember) => { @@ -182,7 +198,7 @@ export async function registerArchiveReviewRoutes(app: FastifyInstance, deps: De const source = await db.cloudSource.findUnique({ where: { id: sourceId }, select: { organizationId: true, look: true } }); if (!source || !fpaArchive(source)) throw notFound("fpa_not_available"); const done = await deps.sports!.personFromFpaLicence(source.organizationId, licence); - members.delete(licence); + memberCache.delete(licence); await log(v, done.created ? "person_from_licence" : "person_licence_update", { personId: done.person.id }); return { person: { ...done.person, licence, reference: done.reference }, created: done.created, member: memberOut(done.member) }; }); @@ -203,7 +219,7 @@ export async function registerArchiveReviewRoutes(app: FastifyInstance, deps: De const folder = await db.cloudFolder.findFirst({ where: { id: query.gallery, sourceId: v.s }, include: { event: true } }); if (!folder) throw notFound("gallery_not_found"); const ids = await galleryMemberIds(db, v.s, folder); - scope = { sql: Prisma.sql`${editable.sql} AND cf.folder_id = ANY(${ids}::uuid[])`, all: false }; + scope = { sql: Prisma.sql`${editable.sql} AND cf.folder_id = ANY(${ids}::uuid[])`, vsql: Prisma.sql`${editable.vsql} AND cv.folder_id = ANY(${ids}::uuid[])`, vedit: Prisma.sql`${editable.vedit} AND cv.folder_id = ANY(${ids}::uuid[])`, all: false }; gallery = { id: folder.id, title: folder.event ? eventName(folder.event) : (folder.path.split("/").filter(Boolean).pop() ?? folder.path) }; } const condition: Record, Prisma.Sql> = { @@ -215,11 +231,12 @@ export async function registerArchiveReviewRoutes(app: FastifyInstance, deps: De }; const person = query.person ? Prisma.sql`AND (g.person_id = ${query.person}::uuid OR g.suggested_person_id = ${query.person}::uuid OR EXISTS (SELECT 1 FROM face_group_rejections r WHERE r.group_id = g.id AND r.person_id = ${query.person}::uuid))` : Prisma.empty; const [groups, counts, queue] = await Promise.all([ - db.$queryRaw<{ id: string; event_id: string; person_id: string | null; suggested_person_id: string | null; suggestion_score: number | null; ignored_at: Date | null; size: number; photos: number }[]>` - SELECT g.id, g.event_id, g.person_id, g.suggested_person_id, g.suggestion_score, g.ignored_at, g.size, count(DISTINCT f.photo_id)::int AS photos + db.$queryRaw<{ id: string; event_id: string; person_id: string | null; suggested_person_id: string | null; suggestion_score: number | null; ignored_at: Date | null; size: number; photos: number; videos: number }[]>` + WITH m AS (${members(scope)}) + SELECT g.id, g.event_id, g.person_id, g.suggested_person_id, g.suggestion_score, g.ignored_at, g.size, + count(DISTINCT m.item) FILTER (WHERE NOT m.video)::int AS photos, count(DISTINCT m.item) FILTER (WHERE m.video)::int AS videos FROM face_groups g - JOIN faces f ON f.group_id = g.id - JOIN cloud_files cf ON cf.photo_id = f.photo_id AND ${scope.sql} + JOIN m ON m.group_id = g.id WHERE ${condition[query.status]} ${person} GROUP BY g.id ORDER BY g.suggestion_score DESC NULLS LAST, g.size DESC, g.id @@ -232,14 +249,13 @@ export async function registerArchiveReviewRoutes(app: FastifyInstance, deps: De WHEN g.suggested_person_id IS NOT NULL THEN 'suggested' WHEN EXISTS (SELECT 1 FROM face_group_rejections r WHERE r.group_id = g.id) THEN 'rejected' WHEN g.size >= 2 THEN 'unnamed' END AS status - FROM face_groups g JOIN faces f ON f.group_id = g.id JOIN cloud_files cf ON cf.photo_id = f.photo_id AND ${scope.sql} + FROM face_groups g JOIN (${members(scope)}) m ON m.group_id = g.id WHERE TRUE ${person} ) s WHERE s.status IS NOT NULL GROUP BY s.status`, db.$queryRaw<{ id: string; name: string; club: string | null; number: string | null; reference: boolean; groups: number }[]>` SELECT p.id, p.name, p.club, p.number, p.reference_key IS NOT NULL AS reference, count(DISTINCT g.id)::int AS groups FROM face_groups g - JOIN faces f ON f.group_id = g.id - JOIN cloud_files cf ON cf.photo_id = f.photo_id AND ${scope.sql} + JOIN (${members(scope)}) m ON m.group_id = g.id JOIN people p ON p.id = g.suggested_person_id WHERE g.person_id IS NULL AND g.ignored_at IS NULL GROUP BY p.id ORDER BY count(DISTINCT g.id) DESC, p.name LIMIT 200`, @@ -260,6 +276,16 @@ export async function registerArchiveReviewRoutes(app: FastifyInstance, deps: De where: { id: { in: [...new Set(samples.map((s) => s.photo_id))] } }, select: { id: true, width: true, height: true, renderedSeq: true, developSnapshot: true }, }); + // And the clearest appearances in its videos (the frame each is clearest in). + const videoSamples = ids.length + ? await db.$queryRaw<{ group_id: string; id: string; video_id: string; at_ms: number; x0: number; y0: number; x1: number; y1: number; width: number | null; height: number | null }[]>` + SELECT group_id, id, video_id, at_ms, x0, y0, x1, y1, width, height FROM ( + SELECT vf.group_id, vf.id, vf.video_id, vf.at_ms, vf.x0, vf.y0, vf.x1, vf.y1, cv.width, cv.height, + row_number() OVER (PARTITION BY vf.group_id ORDER BY vf.sharpness DESC NULLS LAST, vf.score DESC) AS rank + FROM video_faces vf JOIN cloud_videos cv ON cv.id = vf.video_id AND ${scope.vsql} + WHERE vf.group_id = ANY(${ids}::uuid[]) + ) s WHERE rank <= 8` + : []; const photoById = new Map(photos.map((p) => [p.id, p])); const peopleIds = [...new Set(groups.flatMap((g) => [g.person_id, g.suggested_person_id]).filter((x): x is string => !!x))]; const [people, events, rejections] = await Promise.all([ @@ -284,19 +310,25 @@ export async function registerArchiveReviewRoutes(app: FastifyInstance, deps: De id: g.id, size: g.size, photos: g.photos, + videos: g.videos, score: g.suggestion_score, person: personOut(g.person_id), suggested: personOut(g.suggested_person_id), ignored: !!g.ignored_at, notThem: rejections.filter((r) => r.groupId === g.id).map((r) => ({ id: r.person.id, name: r.person.name, by: r.by })), event: e ? { title: eventName(e), startsAt: e.startsAt } : null, - faces: samples - .filter((s) => s.group_id === g.id) - .flatMap((s) => { - const p = photoById.get(s.photo_id); - if (!p) return []; - return [{ id: s.id, photoId: s.photo_id, src: signer.url(s.photo_id, "preview", p.renderedSeq), box: faceBox(s, p), aspect: p.width && p.height ? p.width / p.height : 1.5 }]; - }), + faces: (() => { + const fromPhotos = samples + .filter((s) => s.group_id === g.id) + .flatMap((s) => { + const p = photoById.get(s.photo_id); + if (!p) return []; + return [{ id: s.id, photoId: s.photo_id as string | null, src: signer.url(s.photo_id, "preview", p.renderedSeq), box: faceBox(s, p), aspect: p.width && p.height ? p.width / p.height : 1.5 }]; + }); + const fromVideos = videoSamples.filter((s) => s.group_id === g.id).map((s) => ({ id: s.id, photoId: null, video: { id: s.video_id, atMs: s.at_ms }, ...videoFaceCrop(signer, s) })); + // Both kinds on the card when the group has both. + return [...fromPhotos.slice(0, fromVideos.length ? 6 : 8), ...fromVideos].slice(0, 8); + })(), }; }), }; @@ -311,11 +343,15 @@ export async function registerArchiveReviewRoutes(app: FastifyInstance, deps: De if (!scope) throw forbidden("archive_edit_required"); const group = await db.faceGroup.findFirst({ where: { id: groupId, organization: { cloudSources: { some: { id: sourceId } } } } }); if (!group) throw notFound("group_not_found"); - // Every photo of the group must be one the viewer may edit (in this source). + // Every photo and video of the group must be one the viewer may edit (in this source). const [rights] = await db.$queryRaw<{ total: number; editable: number }[]>` - SELECT count(DISTINCT f.photo_id)::int AS total, - count(DISTINCT f.photo_id) FILTER (WHERE EXISTS (SELECT 1 FROM cloud_files cf WHERE cf.photo_id = f.photo_id AND ${scope.sql}))::int AS editable - FROM faces f WHERE f.group_id = ${groupId}::uuid`; + SELECT count(*)::int AS total, count(*) FILTER (WHERE ok)::int AS editable FROM ( + SELECT DISTINCT f.photo_id AS item, EXISTS (SELECT 1 FROM cloud_files cf WHERE cf.photo_id = f.photo_id AND ${scope.sql}) AS ok + FROM faces f WHERE f.group_id = ${groupId}::uuid + UNION + SELECT DISTINCT vf.video_id AS item, EXISTS (SELECT 1 FROM cloud_videos cv WHERE cv.id = vf.video_id AND ${scope.vedit}) AS ok + FROM video_faces vf WHERE vf.group_id = ${groupId}::uuid + ) items`; if (!rights || rights.total === 0 || rights.editable < rights.total) throw forbidden("archive_edit_required"); try { if (body.action === "confirm") { @@ -406,7 +442,7 @@ export async function registerArchiveReviewRoutes(app: FastifyInstance, deps: De }), ), ]); - deps.onClubsChanged?.(sourceId); + await deps.onClubsChanged?.(sourceId); await log(v, "club_merge", { faces: keys.length }); return { name: into, merged: keys.length }; }); @@ -418,7 +454,7 @@ export async function registerArchiveReviewRoutes(app: FastifyInstance, deps: De if ((await editableFolders(v)) !== "all") throw forbidden("archive_edit_all_required"); const { name } = Unmerge.parse(req.body); const { count } = await db.archiveClubAlias.deleteMany({ where: { sourceId, aliasKey: clubKey(name) } }); - deps.onClubsChanged?.(sourceId); + await deps.onClubsChanged?.(sourceId); if (count) await log(v, "club_unmerge", {}); return { removed: count }; }); diff --git a/apps/api/src/archive/routes.ts b/apps/api/src/archive/routes.ts index 6482cc1..b07c037 100644 --- a/apps/api/src/archive/routes.ts +++ b/apps/api/src/archive/routes.ts @@ -7,7 +7,7 @@ import type { Db } from "../db.js"; import { NextcloudError } from "../delivery/nextcloud.js"; import type { CloudSource } from "../generated/prisma/client.js"; import { AppError, badRequest, conflict, notFound } from "../lib/errors.js"; -import { ARCHIVE_LOOKS, ArchiveRejected, BYTES_PER_PHOTO, diskSpace, normalisePath, type ArchiveService, type RematchReport } from "./service.js"; +import { ARCHIVE_LOOKS, ArchiveRejected, BYTES_PER_PHOTO, diskSpace, GALLERY, normalisePath, type ArchiveService, type RematchReport } from "./service.js"; const OrgParams = z.object({ orgId: z.uuid() }); const SourceParams = z.object({ sourceId: z.uuid() }); @@ -60,11 +60,26 @@ export async function registerArchiveRoutes(app: FastifyInstance, deps: { db: Db const counts = async (sourceIds: string[]) => { if (!sourceIds.length) return new Map>(); const files = await db.cloudFile.groupBy({ by: ["sourceId", "status"], where: { sourceId: { in: sourceIds } }, _count: { _all: true } }); - const folders = await db.cloudFolder.groupBy({ by: ["sourceId", "matchedBy"], where: { sourceId: { in: sourceIds }, photoCount: { gt: 0 } }, _count: { _all: true } }); + const folders = await db.cloudFolder.groupBy({ by: ["sourceId", "matchedBy"], where: { sourceId: { in: sourceIds }, ...GALLERY }, _count: { _all: true } }); + const videos = await db.cloudVideo.groupBy({ by: ["sourceId", "status"], where: { sourceId: { in: sourceIds } }, _count: { _all: true } }); + // Faces in the videos made (videos waiting for their copy are not waiting for faces yet). + const videoFaces = await db.cloudVideo.groupBy({ by: ["sourceId", "facesStatus"], where: { sourceId: { in: sourceIds }, status: "DONE", facesStatus: { not: "NONE" } }, _count: { _all: true } }); // The pace: images indexed in the last 15 minutes, per hour. const recent = await db.cloudFile.groupBy({ by: ["sourceId"], where: { sourceId: { in: sourceIds }, status: "DONE", updatedAt: { gte: new Date(Date.now() - 15 * 60_000) } }, _count: { _all: true } }); const out = new Map>(); - const get = (id: string) => out.get(id) ?? out.set(id, { pending: 0, done: 0, failed: 0, galleries: 0, games: 0, named: 0, unmatched: 0, perHour: 0 }).get(id)!; + const get = (id: string) => out.get(id) ?? out.set(id, { pending: 0, done: 0, failed: 0, failedCorrupt: 0, galleries: 0, games: 0, named: 0, unmatched: 0, perHour: 0, videos: 0, videosPending: 0, videosFailed: 0, videoFacesPending: 0, videoFacesDone: 0, videoFacesFailed: 0 }).get(id)!; + for (const v of videos) { + const c = get(v.sourceId); + if (v.status === "DONE") c.videos! += v._count._all; + else if (v.status === "FAILED") c.videosFailed! += v._count._all; + else c.videosPending! += v._count._all; + } + for (const v of videoFaces) { + const c = get(v.sourceId); + if (v.facesStatus === "DONE") c.videoFacesDone! += v._count._all; + else if (v.facesStatus === "FAILED") c.videoFacesFailed! += v._count._all; + else c.videoFacesPending! += v._count._all; + } for (const r of recent) get(r.sourceId).perHour = r._count._all * 4; for (const f of files) { const c = get(f.sourceId); @@ -72,6 +87,19 @@ export async function registerArchiveRoutes(app: FastifyInstance, deps: { db: Db else if (f.status === "FAILED") c.failed! += f._count._all; else c.pending! += f._count._all; } + // Damaged cloud files (BIT-31658): shown as "corrompido" in the archive UI, not as a tool bug. + const corruptFiles = await db.cloudFile.groupBy({ + by: ["sourceId"], + where: { sourceId: { in: sourceIds }, status: "FAILED", error: { in: ["corrupt_source", "no_video_stream"] } }, + _count: { _all: true }, + }); + const corruptVideos = await db.cloudVideo.groupBy({ + by: ["sourceId"], + where: { sourceId: { in: sourceIds }, status: "FAILED", error: { in: ["corrupt_source", "no_video_stream"] } }, + _count: { _all: true }, + }); + for (const r of corruptFiles) get(r.sourceId).failedCorrupt! += r._count._all; + for (const r of corruptVideos) get(r.sourceId).failedCorrupt! += r._count._all; for (const f of folders) { const c = get(f.sourceId); c.galleries! += f._count._all; @@ -95,7 +123,7 @@ export async function registerArchiveRoutes(app: FastifyInstance, deps: { db: Db nextScanAt: s.nextScanAt, lastError: s.lastError, loginUrl: loginUrl ?? archive.pendingLoginUrl(s), - counts: { pending: 0, done: 0, failed: 0, galleries: 0, games: 0, named: 0, unmatched: 0, perHour: 0, ...c }, + counts: { pending: 0, done: 0, failed: 0, failedCorrupt: 0, galleries: 0, games: 0, named: 0, unmatched: 0, perHour: 0, videos: 0, videosPending: 0, videosFailed: 0, videoFacesPending: 0, videoFacesDone: 0, videoFacesFailed: 0, ...c }, }); const loadSource = async (req: Parameters[1], sourceId: string, role: "EDITOR" | "ADMIN") => { @@ -176,6 +204,8 @@ export async function registerArchiveRoutes(app: FastifyInstance, deps: { db: Db const { sourceId } = SourceParams.parse(req.params); await loadSource(req, sourceId, "EDITOR"); await db.cloudFile.updateMany({ where: { sourceId, status: "FAILED" }, data: { status: "PENDING", attempts: 0 } }); + // Videos too (one that waited for ffmpeg is made once it is installed). + await db.cloudVideo.updateMany({ where: { sourceId, status: "FAILED" }, data: { status: "PENDING", attempts: 0 } }); const source = await db.cloudSource.update({ where: { id: sourceId }, data: { nextScanAt: new Date() } }); return serialize(source, (await counts([source.id])).get(source.id)); }); @@ -216,7 +246,7 @@ export async function registerArchiveRoutes(app: FastifyInstance, deps: { db: Db const folders = await db.cloudFolder.findMany({ where: { sourceId, - photoCount: { gt: 0 }, + AND: [GALLERY], ...(query.state === "games" && { matchedBy: { in: ["FIXTURE", "MANUAL"] } }), ...(query.state === "unmatched" && { OR: [{ matchedBy: { in: ["NAME", "FOLDER"] } }, { matchedBy: null }] }), ...(query.state === "named" && { matchedBy: "NAME" }), @@ -237,6 +267,7 @@ export async function registerArchiveRoutes(app: FastifyInstance, deps: { db: Db id: f.id, path: f.path.startsWith(root) ? f.path.slice(root.length) || "/" : f.path, photoCount: f.photoCount, + videoCount: f.videoCount, indexed: indexed.get(f.id) ?? 0, matchedBy: f.matchedBy, event: f.event ? { id: f.event.id, name: eventName(f.event), startsAt: f.event.startsAt, competition: f.event.competition, fixtureId: f.event.fixtureId } : null, diff --git a/apps/api/src/archive/season-year.test.ts b/apps/api/src/archive/season-year.test.ts new file mode 100644 index 0000000..17cb76d --- /dev/null +++ b/apps/api/src/archive/season-year.test.ts @@ -0,0 +1,14 @@ +import { describe, expect, it } from "vitest"; +import { seasonYear } from "./people.js"; + +describe("seasonYear", () => { + it("reads a season label and leaves anything else as every season", () => { + expect(seasonYear("2025/26")).toBe(2025); + expect(seasonYear("1999/00")).toBe(1999); + expect(seasonYear("2025/2026")).toBe(2025); + expect(seasonYear("20252026")).toBe(2025); + expect(seasonYear("")).toBeNull(); + expect(seasonYear("2025/27")).toBeNull(); + expect(seasonYear(undefined)).toBeNull(); + }); +}); diff --git a/apps/api/src/archive/service.ts b/apps/api/src/archive/service.ts index 716d3dd..f45abe8 100644 --- a/apps/api/src/archive/service.ts +++ b/apps/api/src/archive/service.ts @@ -1,11 +1,11 @@ import { readCameraInfo } from "../ingest/exif.js"; import { createHash } from "node:crypto"; import { createReadStream } from "node:fs"; -import { mkdtemp, rm, stat, statfs } from "node:fs/promises"; +import { mkdir, mkdtemp, readdir, rm, stat, statfs } from "node:fs/promises"; import { tmpdir } from "node:os"; import path from "node:path"; import { NEWSROOM_TEMPLATE, GENERAL_TEMPLATE } from "@photoreport/metadata"; -import sharp from "sharp"; +import sharp, { type Metadata } from "sharp"; import type { Db } from "../db.js"; import { NextcloudError } from "../delivery/nextcloud.js"; import type { SecretBox } from "../delivery/secrets.js"; @@ -13,9 +13,27 @@ import type { CloudFolder, CloudSource } from "../generated/prisma/client.js"; import type { IngestLogger, IngestService } from "../ingest/service.js"; import { ingestWindow } from "../library/events.js"; import { waitUntil } from "../lib/idle.js"; +import type { LocalStorage } from "../storage/storage.js"; import { CloudClient, cleanBase, pollLogin, startLogin, type CloudEntry } from "./nextcloud.js"; +import { + assertDownloadComplete, + CorruptSource, + IncompleteDownload, + isCorruptSourceMessage, + isDecodableImage, +} from "./corrupt-source.js"; +import { makeWebCopy, VIDEO, VIDEO_FILES, VideoToolMissing, VideoUnsupported, type VideoTools } from "./video.js"; +import { teamSideRows } from "./directory.js"; import { galleryAssignments } from "./gallery.js"; -import { canonicalTeam, competitionLabel, describeFolder, exhibitionName, type FolderGame, isExhibition, isInitials, isTeamName, knownVersus, lisbonDay, parseFolder, pastOrToday, pickFixture, seasonOf, slashSides } from "./match.js"; +import { canonicalTeam, competitionLabel, describeFolder, exhibitionName, type FolderGame, isExhibition, isInitials, isTeamName, knownVersus, lisbonDay, parseFolder, pastOrToday, pickFixture, seasonOf, slashSides, teamMatcher } from "./match.js"; + +export { + assertDownloadComplete, + CorruptSource, + IncompleteDownload, + isCorruptSourceMessage, + isDecodableImage, +} from "./corrupt-source.js"; export const IMAGE = /\.(jpe?g)$/i; /** How long the person has to authorise in their cloud (Nextcloud keeps the flow 20 minutes). */ @@ -53,6 +71,8 @@ export interface ArchiveDeps { ligaSeason?: (season: string) => Promise; /** The FPA's national games of a season (slow: run in the background, the galleries matched again after). */ fpaSeason?: (season: string) => Promise; + /** EHF club competitions of a season (Champions League, European League, European Cup), read when a gallery names one. */ + ehfSeason?: (season: string) => Promise; /** Brings the squads of a game's teams into the event (names for faces and codes). */ syncSquads?: (eventId: string) => Promise; fetchImpl?: typeof fetch; @@ -63,6 +83,10 @@ export interface ArchiveDeps { cpuSlots?: number; /** Clouds' folders mounted on this machine (read from disk, not downloaded): see `localDirs`. */ localDirs?: LocalDir[]; + /** Where videos' web copies are kept (the worker makes them; anyone dropping a video removes its files). */ + storage?: LocalStorage; + /** ffmpeg and ffprobe, for videos' web copies. */ + videoTools?: VideoTools; } /** The looks an archive's site can have (its owner's colours and type); none is PhotoReport's own. */ @@ -145,11 +169,36 @@ interface LoginState { */ export class ArchiveService { private readonly cpu: Slots; + /** Permanent index failures coalesced so the hub gets one ticket per burst, not one per photo (BIT-31658). */ + private failBatch = { count: 0, sample: null as Error | null, paths: [] as string[] }; + private failFlush: ReturnType | null = null; constructor(private readonly deps: ArchiveDeps) { this.cpu = new Slots(Math.max(1, deps.cpuSlots ?? Number.MAX_SAFE_INTEGER)); } + /** Remember a permanent index failure; flushed shortly after the burst settles (or on the next poll). */ + noteIndexFailure(err: Error, filePath: string): void { + this.failBatch.count++; + this.failBatch.sample ??= err; + if (this.failBatch.paths.length < 5) this.failBatch.paths.push(filePath); + if (this.failFlush) clearTimeout(this.failFlush); + this.failFlush = setTimeout(() => this.flushIndexFailures(), 5_000); + this.failFlush.unref?.(); + } + + /** One aggregated warn for the error hub after retries are exhausted (BIT-31658). */ + flushIndexFailures(): void { + if (this.failFlush) { + clearTimeout(this.failFlush); + this.failFlush = null; + } + const { count, sample, paths } = this.failBatch; + if (!count) return; + this.failBatch = { count: 0, sample: null, paths: [] }; + this.deps.log.warn({ err: sample, count, paths }, `archive: ${count} files failed indexing after retries`); + } + private get fetchImpl(): typeof fetch { return this.deps.fetchImpl ?? fetch; } @@ -247,6 +296,8 @@ export class ArchiveService { async disconnect(sourceId: string): Promise { const source = await this.deps.db.cloudSource.findUniqueOrThrow({ where: { id: sourceId } }); if (source.secretEnc) await this.client(source).revoke(); + // Videos' web copies are the archive's own: they go with it. + await this.dropVideoFiles(await this.deps.db.cloudVideo.findMany({ where: { sourceId }, select: { storageKey: true } })); // The photos stay in the library (their events too); only the link to the cloud goes. await this.deps.db.cloudSource.delete({ where: { id: sourceId } }); } @@ -317,10 +368,13 @@ export class ArchiveService { } let folder = known ? await db.cloudFolder.update({ where: { id: known.id }, data: { path: self.path, parentId: parent?.id ?? null, seenAt: new Date() } }) - : await db.cloudFolder.create({ data: { sourceId: source.id, fileId: self.fileId, path: self.path, parentId: parent?.id ?? null } }); + : await db.cloudFolder.create({ + data: { sourceId: source.id, fileId: self.fileId, path: self.path, parentId: parent?.id ?? null, ...(parent && !parent.published ? { published: false } : {}) }, + }); const dirs = children.filter((c) => c.isDir); const images = children.filter((c) => !c.isDir && IMAGE.test(c.name)); + const videos = children.filter((c) => !c.isDir && VIDEO.test(c.name)); // Images: new ones queued, changed ones queued again, moved ones follow. const existing = await db.cloudFile.findMany({ where: { sourceId: source.id, fileId: { in: images.map((i) => i.fileId) } } }); @@ -339,6 +393,26 @@ export class ArchiveService { } await db.cloudFile.deleteMany({ where: { folderId: folder.id, fileId: { notIn: images.map((i) => i.fileId) } } }); + // Videos the same way: new and changed ones get their web copy made (again), moved ones follow. + const knownVideos = await db.cloudVideo.findMany({ where: { sourceId: source.id, fileId: { in: videos.map((v) => v.fileId) } } }); + const videoById = new Map(knownVideos.map((v) => [v.fileId, v])); + for (const vid of videos) { + const v = videoById.get(vid.fileId); + const size = vid.size === null ? null : BigInt(vid.size); + if (!v) { + await db.cloudVideo.create({ data: { sourceId: source.id, folderId: folder.id, fileId: vid.fileId, path: vid.path, etag: vid.etag, size } }); + stats.queued++; + } else if (v.etag !== vid.etag) { + await db.cloudVideo.update({ where: { id: v.id }, data: { folderId: folder.id, path: vid.path, etag: vid.etag, size, status: "PENDING", attempts: 0, error: null } }); + stats.queued++; + } else if (v.path !== vid.path || v.folderId !== folder.id) { + await db.cloudVideo.update({ where: { id: v.id }, data: { folderId: folder.id, path: vid.path } }); + } + } + const goneVideos = { folderId: folder.id, fileId: { notIn: videos.map((v) => v.fileId) } }; + await this.dropVideoFiles(await db.cloudVideo.findMany({ where: goneVideos, select: { storageKey: true } })); + await db.cloudVideo.deleteMany({ where: goneVideos }); + // Sub-folders gone from the cloud go from here too, with everything filed under them. The parent link is not a // foreign key, so deleting only the child would leave its tree behind. const gone = await db.cloudFolder.findMany({ @@ -347,12 +421,15 @@ export class ArchiveService { }); if (gone.length) { const tree = gone.flatMap((g) => [{ id: g.id }, { path: { startsWith: `${g.path}/` } }]); + // Their videos' web copies go with them. + await this.dropVideoFiles(await db.cloudVideo.findMany({ where: { sourceId: source.id, folder: { OR: tree } }, select: { storageKey: true } })); await db.cloudFolder.updateMany({ where: { sourceId: source.id, OR: tree }, data: { galleryFolderId: null } }); await db.cloudFolder.deleteMany({ where: { sourceId: source.id, OR: tree } }); } - folder = await db.cloudFolder.update({ where: { id: folder.id }, data: { photoCount: images.length } }); - if (images.length && !folder.eventId && !folder.matchedBy) await this.matchFolder(source, folder, self); + folder = await db.cloudFolder.update({ where: { id: folder.id }, data: { photoCount: images.length, videoCount: videos.length } }); + if ((images.length || videos.length) && !folder.eventId && !folder.matchedBy) await this.matchFolder(source, folder, self); + if (gone.length) await this.markDirectoryDirty(source.id); for (const d of dirs.sort((a, b) => b.name.localeCompare(a.name))) await this.walk(source, client, d.path, folder, stats, full, d); // Marked read only when everything below is: a walk cut short reads the rest next time. @@ -416,6 +493,7 @@ export class ArchiveService { async matchFolder(source: CloudSource, folder: CloudFolder, entry?: CloudEntry): Promise { const { eventId, matchedBy } = await this.eventOf(source, folder, entry?.modifiedAt ?? null); await this.deps.db.cloudFolder.update({ where: { id: folder.id }, data: { eventId, matchedBy } }); + await this.markDirectoryDirty(source.id); return eventId; } @@ -521,7 +599,7 @@ export class ArchiveService { async takeOffFutureGames(now = new Date()): Promise { const { db, log } = this.deps; const folders = await db.cloudFolder.findMany({ - where: { photoCount: { gt: 0 }, OR: [{ matchedBy: null }, { matchedBy: { not: "MANUAL" } }], event: { startsAt: { gt: new Date(now.getTime() + 6 * 3600_000) } } }, + where: { AND: [GALLERY, { OR: [{ matchedBy: null }, { matchedBy: { not: "MANUAL" } }] }], event: { startsAt: { gt: new Date(now.getTime() + 6 * 3600_000) } } }, include: { source: true }, }); let moved = 0; @@ -548,9 +626,8 @@ export class ArchiveService { const folders = await db.cloudFolder.findMany({ where: { sourceId, - photoCount: { gt: 0 }, + AND: [GALLERY, ...(part === "rest" ? [{ OR: [{ matchedBy: null }, { matchedBy: { not: "FIXTURE" as const } }] }] : [])], ...(part === "fixtures" && { matchedBy: "FIXTURE" }), - ...(part === "rest" && { OR: [{ matchedBy: null }, { matchedBy: { not: "FIXTURE" } }] }), }, }); let moved = 0; @@ -701,6 +778,13 @@ export class ArchiveService { this.seasonsAsked.add(`FPA|${season}`); this.fpaSeasonInBackground(season); } + // An EHF folder ("EHF Champions League/…/20261021 - RK Partizan AdmiralBet x FC Porto") needs that season's + // calendar before it can be the official game. One read, then this folder and the ones after it can match. + const ehf = game.parents.some((p) => /^ehf\b/i.test(p.trim())); + if (season && ehf && this.deps.ehfSeason && !this.seasonsAsked.has(`EHF|${season}`)) { + this.seasonsAsked.add(`EHF|${season}`); + await this.deps.ehfSeason(season).catch((err) => this.deps.log.warn({ err, season }, "archive: ehf season not read")); + } const fixtures = await this.deps.db.sportsFixture.findMany({ where: { // Never a game still to be played. @@ -769,8 +853,10 @@ export class ArchiveService { const e = await db.event.findUnique({ where: { id: current }, select: { home: true, away: true, homeShort: true, awayShort: true, startsAt: true, fixtureId: true, archivedAt: true, competition: true } }); if (e && !e.fixtureId && e.archivedAt && (!g.season || seasonOf(lisbonDay(e.startsAt)) === g.season) && (!day || lisbonDay(e.startsAt) === day) && isTeamName(g.home, e.home, e.homeShort) && (g.away ? isTeamName(g.away, e.away, e.awayShort) : !e.away)) { // The same teams, now named better ("01.23 Leixões SC" → "Leixões SC"): the event takes the names. - if (e.home !== g.home || e.away !== g.away || (g.competitionName && e.competition !== g.competitionName)) + if (e.home !== g.home || e.away !== g.away || (g.competitionName && e.competition !== g.competitionName)) { await db.event.update({ where: { id: current }, data: { home: g.home, away: g.away, homeShort: g.homeShort ?? e.homeShort, awayShort: g.awayShort ?? e.awayShort, ...(g.competitionName && { competition: g.competitionName }) } }); + if (e.home !== g.home || e.away !== g.away) await this.markDirectoryDirty(source.id); + } return current; } } @@ -832,7 +918,15 @@ export class ArchiveService { eventId = await this.eventForFixture(folder.source, fixture); } const previous = folder.eventId; - const updated = await db.cloudFolder.update({ where: { id: folderId }, data: { eventId, matchedBy } }); + let updated: CloudFolder; + try { + updated = await db.cloudFolder.update({ where: { id: folderId }, data: { eventId, matchedBy } }); + } catch (err) { + // The event just checked above was deleted in the gap before this write landed: same outcome as it + // never having been found, a clean rejection instead of a raw foreign key error bubbling up. + if ((err as { code?: string }).code === "P2003") throw new ArchiveRejected("event_not_found"); + throw err; + } const files = await db.cloudFile.findMany({ where: { folderId, photoId: { not: null } }, select: { photoId: true } }); const ids = files.map((f) => f.photoId!); if (ids.length) { @@ -845,11 +939,22 @@ export class ArchiveService { // Their faces belonged to the other event's groups: taken out of them, and found again in the new event. await db.face.deleteMany({ where: { photoId: { in: moving } } }); await db.photo.updateMany({ where: { id: { in: moving }, facesStatus: { in: ["DONE", "FAILED", "RUNNING"] } }, data: { facesStatus: "PENDING" } }); - if (previous) await db.faceGroup.deleteMany({ where: { eventId: previous, faces: { none: {} } } }); + if (previous) await db.faceGroup.deleteMany({ where: { eventId: previous, faces: { none: {} }, videoFaces: { none: {} } } }); } } + // Its videos' faces were in the other event's groups too: looked for again in the new event. + // Also from no event at all: their faces could not be put in any group until now. + const moved = previous !== eventId ? await db.cloudVideo.findMany({ where: { folderId, facesStatus: { in: ["DONE", "FAILED", "RUNNING"] } }, select: { id: true } }) : []; + if (moved.length) { + const frames = await db.videoFace.findMany({ where: { videoId: { in: moved.map((v) => v.id) } }, select: { frameKey: true } }); + await db.videoFace.deleteMany({ where: { videoId: { in: moved.map((v) => v.id) } } }); + await db.cloudVideo.updateMany({ where: { id: { in: moved.map((v) => v.id) } }, data: { facesStatus: "PENDING" } }); + for (const f of frames) if (this.deps.storage) await this.deps.storage.remove(f.frameKey).catch(() => undefined); + if (previous) await db.faceGroup.deleteMany({ where: { eventId: previous, faces: { none: {} }, videoFaces: { none: {} } } }); + } // An event the archive made and that nothing uses any more goes. if (previous && previous !== eventId) await this.dropIfEmpty(previous); + if (previous !== eventId || folder.matchedBy !== matchedBy) await this.markDirectoryDirty(folder.sourceId); return updated; } @@ -912,6 +1017,7 @@ export class ArchiveService { const { db, log } = this.deps; const walks = await db.cloudSource.updateMany({ where: { status: "SCANNING" }, data: { status: "READY", nextScanAt: new Date() } }); if (walks.count) log.info({ count: walks.count }, "archive: resuming interrupted walks"); + await db.cloudVideo.updateMany({ where: { status: "WORKING" }, data: { status: "PENDING" } }); return db.cloudFile.updateMany({ where: { status: "WORKING" }, data: { status: "PENDING" } }).then((r) => r.count); } @@ -998,8 +1104,13 @@ export class ArchiveService { if (!original) { original = path.join(dir, "original.jpg"); await this.client(file.source).download(file.path, original); + await assertDownloadComplete(original, file.size); } const from = original; + // A .jpg that is not really a JPEG (HEIC/RAW, or an error body saved as an image) makes sharp/vips throw + // "unsupported image format" — caught by the magic bytes here, before vips, so it fails once at info and + // never reaches the error hub as one ticket per file (BIT-31229). + if (!(await isDecodableImage(from))) throw new CorruptSource("unsupported_image_format"); // The official game's day against the day the photos were taken: a folder matched to the wrong game is // taken off it (and its photos go to an event of their own) before anything is added. if (file.folder.matchedBy === "FIXTURE") { @@ -1016,7 +1127,13 @@ export class ArchiveService { const outcome = await this.cpu.run(async () => { const size = (await stat(from)).size; const sha256 = await hashFile(from); - const meta = await sharp(from).metadata(); + let meta: Metadata; + try { + meta = await sharp(from).metadata(); + } catch (err) { + if (isCorruptSourceMessage((err as Error).message)) throw new CorruptSource(); + throw err; + } const turned = (meta.orientation ?? 1) >= 5; const width = turned ? meta.height : meta.width; const height = turned ? meta.width : meta.height; @@ -1033,7 +1150,10 @@ export class ArchiveService { }); }); if (outcome.status === "failed") { - await db.cloudFile.update({ where: { id: fileId }, data: { status: "FAILED", error: outcome.error, photoId: outcome.photoId } }); + const corrupt = !!outcome.error && isCorruptSourceMessage(outcome.error); + await db.cloudFile.update({ where: { id: fileId }, data: { status: "FAILED", error: corrupt ? "corrupt_source" : outcome.error, photoId: outcome.photoId } }); + if (corrupt) log.info({ fileId, path: file.path }, "archive: image corrupt in cloud, marked failed"); + else this.noteIndexFailure(new Error(outcome.error ?? "ingest_failed"), file.path); return; } await db.cloudFile.update({ where: { id: fileId }, data: { status: "DONE", photoId: outcome.photoId, error: null } }); @@ -1042,19 +1162,127 @@ export class ArchiveService { const message = (err as Error).message; const transient = err instanceof NextcloudError && err.transient; const gone = err instanceof NextcloudError && err.status === 404; - const retry = !gone && (transient || file.attempts < MAX_ATTEMPTS); - await db.cloudFile.update({ where: { id: fileId }, data: { status: retry ? "PENDING" : "FAILED", error: message, ...(transient && { attempts: { decrement: 1 } }) } }); + const incomplete = err instanceof IncompleteDownload; + const corrupt = err instanceof CorruptSource || (!incomplete && isCorruptSourceMessage(message)); + // Incomplete downloads retry later; confirmed corrupt sources fail once (BIT-31621). + const retry = !gone && !corrupt && (transient || file.attempts < MAX_ATTEMPTS); + const error = corrupt || (!retry && incomplete) ? "corrupt_source" : message; + await db.cloudFile.update({ where: { id: fileId }, data: { status: retry ? "PENDING" : "FAILED", error, ...(transient && { attempts: { decrement: 1 } }) } }); // A file moved since the walk: read its folder again next time. if (gone) await db.cloudFolder.update({ where: { id: file.folderId }, data: { etag: null } }); // A transient blip is given a free retry and costs nothing (BIT-31513): logged at info so it never reaches // the error hub as a warning, unlike a real decoding/matching failure or one burning the attempt budget. - if (transient) log.info({ err, fileId, path: file.path }, "archive: image download blipped, requeued for a free retry"); - else log.warn({ err, fileId, path: file.path }, "archive: image not indexed"); + // Corrupt / incomplete sources are expected cloud damage — info only (BIT-31621), never one hub ticket per file. + if (corrupt || (!retry && incomplete)) log.info({ err, fileId, path: file.path }, "archive: image source corrupt, marked failed"); + else if (transient) log.info({ err, fileId, path: file.path }, "archive: image download blipped, requeued for a free retry"); + else if (incomplete) log.info({ err, fileId, path: file.path }, "archive: image download incomplete, requeued"); + // Permanent failures go to the hub as one warn per burst (BIT-31658); a retry left in the budget is info. + else if (!retry) this.noteIndexFailure(err instanceof Error ? err : new Error(message), file.path); + else log.info({ err, fileId, path: file.path, attempts: file.attempts }, "archive: image not indexed, will retry"); } finally { await rm(dir, { recursive: true, force: true }); } } + // --- videos ---------------------------------------------------------------------------------------------------- + + /** Videos waiting for their web copy, newest season first (like the photos), then by game and name. */ + async claimVideos(limit: number): Promise { + if (limit <= 0 || !this.deps.storage || !this.deps.videoTools) return []; + if (await this.diskLow()) return []; + const rows = await this.deps.db.$queryRaw<{ id: string }[]>` + UPDATE cloud_videos SET status = 'WORKING', attempts = attempts + 1, updated_at = now() + WHERE id IN ( + SELECT v.id FROM cloud_videos v + JOIN cloud_sources s ON s.id = v.source_id AND s.status IN ('READY', 'SCANNING') + JOIN cloud_folders d ON d.id = v.folder_id + LEFT JOIN events e ON e.id = d.event_id + WHERE v.status = 'PENDING' + ORDER BY coalesce(substring(v.path from '(20[0-9]{2})[_-]20[0-9]{2}'), '20' || substring(v.path from '([0-9]{2})[_-][0-9]{2}(/|$| )')) DESC NULLS LAST, + e.starts_at DESC NULLS LAST, v.path + LIMIT ${limit} + FOR UPDATE OF v SKIP LOCKED + ) + RETURNING id`; + return rows.map((r) => r.id); + } + + /** + * One video: read from the cloud (or its mount), its web copy, poster and thumbnail made with ffmpeg and kept in + * storage. The original never leaves the cloud. Without ffmpeg on this machine the video waits (FAILED with the + * reason; "Analisar agora" tries again once it is installed). + */ + async indexVideo(videoId: string): Promise { + const { db, log } = this.deps; + const { storage, videoTools } = this.deps; + if (!storage || !videoTools) throw new Error("videos need storage and ffmpeg"); + const video = await db.cloudVideo.findUniqueOrThrow({ where: { id: videoId }, include: { source: true } }); + const dir = await mkdtemp(path.join(tmpdir(), "pr-archive-video-")); + try { + let original = await this.localFile(video.source.baseUrl, video.path, video.size); + if (!original) { + original = path.join(dir, `original${path.posix.extname(video.path).toLowerCase()}`); + await this.client(video.source).download(video.path, original); + // Walk size vs bytes on disk: truncated GET / still-uploading → retry later (BIT-31621). + await assertDownloadComplete(original, video.size); + } + const out = path.join(dir, "out"); + await mkdir(out); + const made = await this.cpu.run(() => makeWebCopy(videoTools, original, out)); + const key = storage.videoKey(video.source.organizationId, video.id); + // The new files take the place of an older copy (a changed video); the faces' frames are left to the face worker. + for (const name of Object.values(VIDEO_FILES)) await storage.remove(`${key}/${name}`); + for (const name of await readdir(out)) if (name !== "frame.jpg") await storage.adopt(path.join(out, name), `${key}/${name}`); + // Its faces next, like a photo's: only where the organization has face recognition on. + const org = await db.organization.findUnique({ where: { id: video.source.organizationId }, select: { biometricsEnabled: true } }); + await db.cloudVideo.update({ + where: { id: videoId }, + data: { + status: "DONE", + error: null, + storageKey: key, + durationMs: made.durationMs, + width: made.width, + height: made.height, + capturedAt: made.capturedAt, + webBytes: BigInt(made.webBytes), + facesStatus: org?.biometricsEnabled ? "PENDING" : "NONE", + }, + }); + } catch (err) { + const message = (err as Error).message; + const transient = err instanceof NextcloudError && err.transient; + const gone = err instanceof NextcloudError && err.status === 404; + const missing = err instanceof VideoToolMissing; + const unsupported = err instanceof VideoUnsupported; + const incomplete = err instanceof IncompleteDownload; + // moov atom not found / Invalid data… = damaged MP4 in the cloud, not an ffmpeg bug (BIT-31621). + const corrupt = err instanceof CorruptSource || (!incomplete && isCorruptSourceMessage(message)); + // No video stream / missing tools / gone from cloud / damaged source: mark FAILED once; retries cannot help. + const retry = !gone && !missing && !unsupported && !corrupt && (transient || video.attempts < MAX_ATTEMPTS); + const error = corrupt || (!retry && incomplete) ? "corrupt_source" : message; + await db.cloudVideo.update({ where: { id: videoId }, data: { status: retry ? "PENDING" : "FAILED", error, ...(transient && { attempts: { decrement: 1 } }) } }); + if (gone) await db.cloudFolder.update({ where: { id: video.folderId }, data: { etag: null } }); + if (corrupt || (!retry && incomplete)) log.info({ err, videoId, path: video.path }, "archive: video source corrupt, marked failed"); + else if (transient) log.info({ err, videoId, path: video.path }, "archive: video download blipped, requeued for a free retry"); + else if (incomplete) log.info({ err, videoId, path: video.path }, "archive: video download incomplete, requeued"); + else if (unsupported) log.info({ videoId, path: video.path }, "archive: not a video stream, marked failed"); + // ffmpeg missing on the host is for someone to fix: it stays a warning of its own. + else if (missing) log.warn({ err, videoId, path: video.path }, "archive: video not indexed"); + else if (!retry) this.noteIndexFailure(err instanceof Error ? err : new Error(message), video.path); + else log.info({ err, videoId, path: video.path, attempts: video.attempts }, "archive: video not indexed, will retry"); + } finally { + await rm(dir, { recursive: true, force: true }); + } + } + + /** A video's files in storage, when it is dropped (gone from the cloud, the cloud disconnected). */ + private async dropVideoFiles(videos: { storageKey: string | null }[]): Promise { + const storage = this.deps.storage; + if (!storage) return; + for (const v of videos) if (v.storageKey) await rm(storage.resolve(v.storageKey), { recursive: true, force: true }).catch(() => undefined); + } + // --- originals ------------------------------------------------------------------------------------------------- private async cloudFileOf(photoId: string) { @@ -1113,8 +1341,71 @@ export class ArchiveService { const cf = await this.cloudFileOf(photoId); return cf ? this.client(cf.source).open(cf.path) : null; } + + /** + * The teams list is stale: a gallery moved, a side was renamed, or two club names were joined. The worker rewrites + * it. A request never does. + */ + async markDirectoryDirty(sourceId: string): Promise { + await this.deps.db.cloudSource.updateMany({ where: { id: sourceId }, data: { directoryDirtyAt: new Date() } }); + } + + /** + * Rewrites one archive's teams from its games. Clears the dirty mark only when nothing newer arrived while this + * was reading, so a match that lands mid-write is not lost. + */ + async rebuildDirectory(sourceId: string): Promise { + const started = new Date(); + const { db } = this.deps; + const source = await db.cloudSource.findUnique({ where: { id: sourceId }, select: { id: true, look: true, baseUrl: true } }); + if (!source) return 0; + const liga = source.look === "liga" || /liga/i.test(source.baseUrl); + const teams = await db.sportsTeam.findMany({ + where: liga ? { provider: "LIGA" } : { provider: { not: "LIGA" }, sport: { not: "futebol" } }, + select: { name: true, abbreviation: true, slug: true }, + }); + const aliases = await db.archiveClubAlias.findMany({ where: { sourceId }, select: { aliasKey: true, name: true } }); + const folders = await db.cloudFolder.findMany({ + where: { sourceId, matchedBy: { not: "FOLDER" }, eventId: { not: null } }, + select: { event: { select: { id: true, home: true, away: true } } }, + }); + const games = new Map(); + for (const folder of folders) if (folder.event) games.set(folder.event.id, folder.event); + const rows = teamSideRows(games.values(), teamMatcher(teams), new Map(aliases.map((alias) => [alias.aliasKey, alias.name]))); + await db.$transaction(async (tx) => { + await tx.archiveTeamSide.deleteMany({ where: { sourceId } }); + const chunk = 2000; + for (let i = 0; i < rows.length; i += chunk) { + await tx.archiveTeamSide.createMany({ + data: rows.slice(i, i + chunk).map((row) => ({ sourceId, eventId: row.eventId, raw: row.raw, name: row.name })), + }); + } + await tx.cloudSource.updateMany({ + where: { id: sourceId, OR: [{ directoryDirtyAt: null }, { directoryDirtyAt: { lte: started } }] }, + data: { directoryBuiltAt: new Date(), directoryDirtyAt: null }, + }); + }, { timeout: 60_000, maxWait: 60_000 }); + return rows.length; + } + + /** One archive whose teams were never stored, or have changed. */ + async rebuildDue(): Promise { + const due = await this.deps.db.$queryRaw<{ id: string }[]>` + SELECT id FROM cloud_sources + WHERE directory_built_at IS NULL OR directory_dirty_at IS NOT NULL + ORDER BY directory_built_at NULLS FIRST + LIMIT 1`; + const sourceId = due[0]?.id; + if (!sourceId) return false; + const sides = await this.rebuildDirectory(sourceId); + this.deps.log.info({ sourceId, sides }, "archive: team directory stored"); + return true; + } } +/** A gallery folder: one with photos, videos, or both. */ +export const GALLERY = { OR: [{ photoCount: { gt: 0 } }, { videoCount: { gt: 0 } }] }; + /** "/FPA/Fotos/" → "/FPA/Fotos". */ export const normalisePath = (p: string) => "/" + p.trim().replace(/\\/g, "/").replace(/^\/+|\/+$/g, ""); @@ -1135,10 +1426,12 @@ const BURST_BACKLOG = 500; export class ArchiveWorker { private inFlight = 0; + private videosInFlight = 0; private timer: NodeJS.Timeout | undefined; private stopped = false; private scanning = false; private ticking = false; + private directories = false; constructor( private readonly service: ArchiveService, @@ -1149,10 +1442,20 @@ export class ArchiveWorker { intervalMs: number; log: IngestLogger; pressure?: { allow(full: number, burst?: boolean): number }; + /** Videos made at once (each ffmpeg uses several cores). 0: none on this worker. */ + videos?: number; }, ) {} start(): void { + // The teams list is a stored read. Write it at once: the check below can take a long time, and the site waits. + this.directories = true; + void this.service + .rebuildDue() + .catch((err) => this.opts.log.warn({ err }, "archive: team directory not stored")) + .finally(() => { + this.directories = false; + }); // Before the first round, so an interrupted walk is picked up by it. const ready = this.service .leaveLiveEvents() @@ -1172,6 +1475,8 @@ export class ArchiveWorker { try { await ready; try { + // Failures from the previous burst (indexes finish after claim); coalesce hub noise (BIT-31658). + this.service.flushIndexFailures(); if (!this.scanning) { this.scanning = true; // Walking runs beside the indexing (a big first walk should not hold the queue back). @@ -1182,6 +1487,15 @@ export class ArchiveWorker { this.scanning = false; }); } + if (!this.directories) { + this.directories = true; + void this.service + .rebuildDue() + .catch((err) => this.opts.log.warn({ err }, "archive: team directory not stored")) + .finally(() => { + this.directories = false; + }); + } // Bulk work: less of it while the machine is busy with live games, all of it when quiet. const burst = !!this.opts.burst && (await this.backlog()) > BURST_BACKLOG; const full = burst ? this.opts.burst! : this.opts.concurrency; @@ -1193,6 +1507,14 @@ export class ArchiveWorker { this.inFlight--; }); } + // Videos beside the photos, a few at a time: they are few, and each one is long work. + const videoIds = await this.service.claimVideos((this.opts.videos ?? 1) - this.videosInFlight); + for (const id of videoIds) { + this.videosInFlight++; + void this.service.indexVideo(id).finally(() => { + this.videosInFlight--; + }); + } } catch (err) { this.opts.log.warn({ err }, "archive: poll failed"); } @@ -1220,7 +1542,8 @@ export class ArchiveWorker { async stop(timeoutMs = 25_000): Promise { this.stopped = true; if (this.timer) clearTimeout(this.timer); - const drained = await waitUntil(() => !this.ticking && !this.scanning && this.inFlight === 0, { timeoutMs }); - if (!drained) this.opts.log.warn({ inFlight: this.inFlight, scanning: this.scanning }, "archive: stop timed out with work still running"); + const drained = await waitUntil(() => !this.ticking && !this.scanning && !this.directories && this.inFlight === 0 && this.videosInFlight === 0, { timeoutMs }); + this.service.flushIndexFailures(); + if (!drained) this.opts.log.warn({ inFlight: this.inFlight, videos: this.videosInFlight, scanning: this.scanning }, "archive: stop timed out with work still running"); } } diff --git a/apps/api/src/archive/team-name.test.ts b/apps/api/src/archive/team-name.test.ts new file mode 100644 index 0000000..c0f2b41 --- /dev/null +++ b/apps/api/src/archive/team-name.test.ts @@ -0,0 +1,18 @@ +import { describe, expect, it } from "vitest"; +import { teamsNamed } from "./match.js"; + +const team = (name: string, slug = name) => ({ id: slug, name, abbreviation: null as string | null, slug }); + +describe("teamsNamed", () => { + const clubs = [team("CD Feirense", "cd-feirense"), team("SC Farense", "sc-farense"), team("Sporting CP", "sporting-cp"), team("Sporting CP B", "sporting-cp-b")]; + + it("names Feirense and not Farense", () => { + expect(teamsNamed("CD Feirense", clubs).map((t) => t.name)).toEqual(["CD Feirense"]); + expect(teamsNamed("SC Farense", clubs).map((t) => t.name)).toEqual(["SC Farense"]); + }); + + it("keeps a senior side off its B team", () => { + expect(teamsNamed("Sporting CP", clubs).map((t) => t.name)).toEqual(["Sporting CP"]); + expect(teamsNamed("Sporting CP B", clubs).map((t) => t.name)).toEqual(["Sporting CP B"]); + }); +}); diff --git a/apps/api/src/archive/video-faces.ts b/apps/api/src/archive/video-faces.ts new file mode 100644 index 0000000..51195d8 --- /dev/null +++ b/apps/api/src/archive/video-faces.ts @@ -0,0 +1,63 @@ +import { Prisma } from "../generated/prisma/client.js"; +import type { Db } from "../db.js"; +import type { UrlSigner } from "../storage/storage.js"; + +/** + * Faces in archive videos as the viewers see them: each appearance (a face followed through frames) is in an event's + * face group like a photo's face, so it is named (the group is confirmed), probable (the group has a suggestion) or + * nobody yet. Only videos of published folders count. + */ +export interface VideoPerson { + id: string; + name: string; + level: "confirmed" | "probable"; + /** First time on screen, and every appearance (to jump to each). */ + startMs: number; + moments: { startMs: number; endMs: number }[]; +} + +/** Who appears in each of these videos, named or probable, with when. */ +export async function peopleInVideos(db: Db, videoIds: string[]): Promise> { + const out = new Map(); + if (!videoIds.length) return out; + const rows = await db.$queryRaw<{ video_id: string; person_id: string; name: string; confirmed: boolean; start_ms: number; end_ms: number }[]>` + SELECT vf.video_id, p.id AS person_id, p.name, (g.person_id IS NOT NULL) AS confirmed, vf.start_ms, vf.end_ms + FROM video_faces vf + JOIN face_groups g ON g.id = vf.group_id AND g.ignored_at IS NULL + JOIN people p ON p.id = COALESCE(g.person_id, g.suggested_person_id) + WHERE vf.video_id = ANY(${videoIds}::uuid[]) + ORDER BY vf.start_ms`; + for (const r of rows) { + const list = out.get(r.video_id) ?? []; + let person = list.find((p) => p.id === r.person_id); + if (!person) { + person = { id: r.person_id, name: r.name, level: r.confirmed ? "confirmed" : "probable", startMs: r.start_ms, moments: [] }; + list.push(person); + } + person.moments.push({ startMs: r.start_ms, endMs: r.end_ms }); + out.set(r.video_id, list); + } + for (const list of out.values()) list.sort((a, b) => (a.level === b.level ? a.startMs - b.startMs : a.level === "confirmed" ? -1 : 1)); + return out; +} + +/** + * A video scope on `cv` like the photos' on `cf`: the source and (unless all) these folders. What viewers see is + * only made videos of published folders; what an editor may change (`edit`) is every video of their folders, as for + * the photos, so a video being made again or a folder taken off the site never locks a face group. + */ +export function videoScope(sourceId: string, folders: string[] | "all", opts: { edit?: boolean } = {}): Prisma.Sql { + const base = opts.edit + ? Prisma.sql`cv.source_id = ${sourceId}::uuid` + : Prisma.sql`cv.source_id = ${sourceId}::uuid AND cv.status = 'DONE' AND EXISTS (SELECT 1 FROM cloud_folders pub WHERE pub.id = cv.folder_id AND pub.published)`; + return folders === "all" ? base : Prisma.sql`${base} AND cv.folder_id = ANY(${folders}::uuid[])`; +} + +/** An appearance as a face crop: its frame (signed), the box in it and the frame's shape. */ +export function videoFaceCrop(signer: UrlSigner, f: { id: string; x0: number; y0: number; x1: number; y1: number; width: number | null; height: number | null }) { + return { + src: signer.videoFaceUrl(f.id), + box: { x0: f.x0, y0: f.y0, x1: f.x1, y1: f.y1 }, + aspect: f.width && f.height ? f.width / f.height : 16 / 9, + }; +} diff --git a/apps/api/src/archive/video.test.ts b/apps/api/src/archive/video.test.ts new file mode 100644 index 0000000..bbf697f --- /dev/null +++ b/apps/api/src/archive/video.test.ts @@ -0,0 +1,176 @@ +import { execFileSync } from "node:child_process"; +import { mkdtemp, rm, stat } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { afterAll, beforeAll, describe, expect, it } from "vitest"; +import { UrlSigner } from "../storage/storage.js"; +import { findVideoTools, makeWebCopy, parseRange, posterAt, readProbe, requireVideoStream, VIDEO, VideoToolMissing, VideoUnsupported, webCopyArgs, probe } from "./video.js"; + +describe("archive videos", () => { + it("knows a video by its name", () => { + for (const name of ["Golo 1.MP4", "a.mov", "clip.m4v", "00001.MTS", "x.mkv", "y.webm"]) expect(VIDEO.test(name)).toBe(true); + for (const name of ["foto.jpg", "notes.txt", "mp4", "video.mp4.part"]) expect(VIDEO.test(name)).toBe(false); + }); + + it("answers the ranges a player asks for", () => { + expect(parseRange(undefined, 1000)).toBeNull(); + expect(parseRange("bytes=0-", 1000)).toEqual({ start: 0, end: 999 }); + expect(parseRange("bytes=0-1", 1000)).toEqual({ start: 0, end: 1 }); + expect(parseRange("bytes=500-2000", 1000)).toEqual({ start: 500, end: 999 }); + expect(parseRange("bytes=-100", 1000)).toEqual({ start: 900, end: 999 }); + expect(parseRange("bytes=-5000", 1000)).toEqual({ start: 0, end: 999 }); + expect(parseRange("bytes=1000-", 1000)).toBe("bad"); + expect(parseRange("bytes=9-3", 1000)).toBe("bad"); + expect(parseRange("bytes=-", 1000)).toBe("bad"); + expect(parseRange("items=0-1", 1000)).toBe("bad"); + // Several at once: the whole file instead. + expect(parseRange("bytes=0-1,5-9", 1000)).toBeNull(); + }); + + it("reads length, size, sound and the camera's time", () => { + const info = readProbe({ + format: { duration: "12.480000", tags: { creation_time: "2025-09-13T18:42:10.000000Z" } }, + streams: [ + { codec_type: "video", width: 1920, height: 1080 }, + { codec_type: "audio" }, + ], + }); + expect(info).toEqual({ + durationMs: 12480, + width: 1920, + height: 1080, + capturedAt: new Date("2025-09-13T18:42:10.000Z"), + hasAudio: true, + hasVideo: true, + }); + // A camera that never had its clock set. + expect(readProbe({ format: { tags: { creation_time: "1970-01-01T00:00:00Z" } }, streams: [{ codec_type: "video" }] }).capturedAt).toBeNull(); + expect(readProbe({ streams: [] })).toMatchObject({ durationMs: null, width: null, hasAudio: false, hasVideo: false }); + // Audio-only container (wrong extension or silent movie stripped to sound). + expect(readProbe({ format: { duration: "3.0" }, streams: [{ codec_type: "audio" }] })).toMatchObject({ + hasAudio: true, + hasVideo: false, + width: null, + height: null, + }); + }); + + it("refuses indexing when there is no video stream", () => { + expect(() => requireVideoStream({ hasVideo: true })).not.toThrow(); + expect(() => requireVideoStream({ hasVideo: false })).toThrow(VideoUnsupported); + expect(() => requireVideoStream({ hasVideo: false })).toThrow("no_video_stream"); + }); + + it("makes an H.264 web copy that starts at once, with or without sound", () => { + const withSound = webCopyArgs("in.mov", "out.mp4", { audio: true }); + expect(withSound).toEqual(expect.arrayContaining(["libx264", "+faststart", "aac", "0:a:0"])); + expect(withSound.at(-1)).toBe("out.mp4"); + const silent = webCopyArgs("in.mov", "out.mp4", { audio: false }); + expect(silent).toContain("-an"); + expect(silent).not.toContain("0:a:0"); + }); + + it("takes the poster a second in, sooner in a short clip", () => { + expect(posterAt(null)).toBe(0); + expect(posterAt(60_000)).toBe(1); + expect(posterAt(4_000)).toBe(0.4); + }); + + it("signs a video's links apart from the photos'", () => { + let now = 1_800_000_000_000; + const signer = new UrlSigner("x".repeat(40), 3600, () => now); + const url = new URL(signer.videoUrl("6c0b1b55-6d1f-4c2a-9f0e-0f5a3c1b2d3e", "web"), "http://h"); + const exp = Number(url.searchParams.get("exp")); + const sig = url.searchParams.get("sig")!; + expect(url.pathname).toBe("/v1/files/videos/6c0b1b55-6d1f-4c2a-9f0e-0f5a3c1b2d3e/web"); + expect(signer.verifyVideo("6c0b1b55-6d1f-4c2a-9f0e-0f5a3c1b2d3e", "web", exp, sig)).toBe(true); + // Another file of the same video, another video, or a photo: not with this signature. + expect(signer.verifyVideo("6c0b1b55-6d1f-4c2a-9f0e-0f5a3c1b2d3e", "download", exp, sig)).toBe(false); + expect(signer.verifyVideo("00000000-6d1f-4c2a-9f0e-0f5a3c1b2d3e", "web", exp, sig)).toBe(false); + expect(signer.verify("6c0b1b55-6d1f-4c2a-9f0e-0f5a3c1b2d3e", "preview", exp, sig)).toBe(false); + now += 3 * 3600_000; + expect(signer.verifyVideo("6c0b1b55-6d1f-4c2a-9f0e-0f5a3c1b2d3e", "web", exp, sig)).toBe(false); + }); + + it("uses the static ffmpeg the deploy installs when the configuration names none", () => { + const at = new Set(["/home/pr/.local/ffmpeg/ffmpeg", "/home/pr/.local/ffmpeg/ffprobe"]); + expect(findVideoTools({ ffmpeg: "ffmpeg", ffprobe: "ffprobe" }, "/home/pr", (f) => at.has(f))).toEqual({ ffmpeg: "/home/pr/.local/ffmpeg/ffmpeg", ffprobe: "/home/pr/.local/ffmpeg/ffprobe" }); + // On PATH (none in the home), or named in .env: as configured. + expect(findVideoTools({ ffmpeg: "ffmpeg", ffprobe: "ffprobe" }, "/home/pr", () => false)).toEqual({ ffmpeg: "ffmpeg", ffprobe: "ffprobe" }); + expect(findVideoTools({ ffmpeg: "/opt/ff/ffmpeg", ffprobe: "/opt/ff/ffprobe" }, "/home/pr", (f) => at.has(f))).toEqual({ ffmpeg: "/opt/ff/ffmpeg", ffprobe: "/opt/ff/ffprobe" }); + }); + + it("says when ffmpeg is not installed", async () => { + await expect(probe({ ffmpeg: "ffmpeg-not-here", ffprobe: "ffprobe-not-here" }, "x.mp4")).rejects.toBeInstanceOf(VideoToolMissing); + }); +}); + +const hasFfmpeg = (() => { + try { + execFileSync("ffmpeg", ["-version"], { stdio: "ignore" }); + execFileSync("ffprobe", ["-version"], { stdio: "ignore" }); + return true; + } catch { + return false; + } +})(); + +describe.skipIf(!hasFfmpeg)("archive videos with ffmpeg", () => { + const tools = { ffmpeg: "ffmpeg", ffprobe: "ffprobe" }; + let dir: string; + beforeAll(async () => { + dir = await mkdtemp(path.join(tmpdir(), "pr-video-test-")); + }); + afterAll(async () => { + await rm(dir, { recursive: true, force: true }); + }); + + const clip = (name: string, size: string, audio: boolean) => { + const file = path.join(dir, name); + execFileSync("ffmpeg", [ + "-hide_banner", "-loglevel", "error", "-y", + "-f", "lavfi", "-i", `testsrc=size=${size}:rate=10:duration=2`, + ...(audio ? ["-f", "lavfi", "-i", "sine=frequency=440:duration=2"] : []), + "-c:v", "mpeg4", ...(audio ? ["-c:a", "aac", "-shortest"] : []), + "-metadata", "creation_time=2025-09-13T18:42:10Z", + file, + ]); + return file; + }; + + it("brings a big landscape video down to 1080p, with sound, poster and thumbnail", async () => { + const out = path.join(dir, "landscape"); + await import("node:fs/promises").then((fs) => fs.mkdir(out)); + const made = await makeWebCopy(tools, clip("big.mov", "2560x1440", true), out); + expect(made).toMatchObject({ width: 1920, height: 1080, hasAudio: true }); + expect(made.durationMs).toBeGreaterThan(1500); + expect(made.capturedAt?.toISOString()).toBe("2025-09-13T18:42:10.000Z"); + expect(made.webBytes).toBe((await stat(path.join(out, "web.mp4"))).size); + for (const f of ["poster.jpg", "thumb.jpg"]) expect((await stat(path.join(out, f))).size).toBeGreaterThan(0); + }, 60_000); + + it("keeps a phone's portrait video upright and a small one as it is", async () => { + const portrait = path.join(dir, "portrait"); + const small = path.join(dir, "small"); + await import("node:fs/promises").then(async (fs) => { + await fs.mkdir(portrait); + await fs.mkdir(small); + }); + expect(await makeWebCopy(tools, clip("tall.mp4", "1440x2560", false), portrait)).toMatchObject({ width: 1080, height: 1920, hasAudio: false }); + expect(await makeWebCopy(tools, clip("small.mp4", "640x360", false), small)).toMatchObject({ width: 640, height: 360 }); + }, 60_000); + + it("marks audio-only files unsupported instead of failing on -map 0:v:0", async () => { + const audioOnly = path.join(dir, "sound.mp4"); + execFileSync("ffmpeg", [ + "-hide_banner", "-loglevel", "error", "-y", + "-f", "lavfi", "-i", "sine=frequency=440:duration=1", + "-c:a", "aac", + audioOnly, + ]); + const out = path.join(dir, "audio-only-out"); + await import("node:fs/promises").then((fs) => fs.mkdir(out)); + await expect(makeWebCopy(tools, audioOnly, out)).rejects.toBeInstanceOf(VideoUnsupported); + await expect(makeWebCopy(tools, audioOnly, out)).rejects.toThrow("no_video_stream"); + }, 30_000); +}); diff --git a/apps/api/src/archive/video.ts b/apps/api/src/archive/video.ts new file mode 100644 index 0000000..74a3863 --- /dev/null +++ b/apps/api/src/archive/video.ts @@ -0,0 +1,230 @@ +import { spawn } from "node:child_process"; +import { createReadStream, existsSync } from "node:fs"; +import { readdir, stat } from "node:fs/promises"; +import path from "node:path"; +import type { FastifyReply } from "fastify"; +import sharp from "sharp"; + +/** + * Videos in the archive (docs/archive.md, "Vídeos"). The original stays on the cloud; the archive keeps a web copy + * every browser plays (H.264 + AAC in MP4, the short side at most 1080 px, faststart so it starts before it has + * all arrived), a poster for the large view and a thumbnail for the grid. Made with ffmpeg on the worker. + */ +export const VIDEO = /\.(mp4|m4v|mov|mts|m2ts|mkv|avi|webm)$/i; + +/** The files of a video's web copy, inside its storage folder. */ +export const VIDEO_FILES = { web: "web.mp4", poster: "poster.jpg", thumb: "thumb.jpg" } as const; +export type VideoVariant = keyof typeof VIDEO_FILES | "download"; +export const VIDEO_VARIANTS = ["web", "poster", "thumb", "download"] as const satisfies readonly VideoVariant[]; + +/** Long side of the poster (the large view before play) and of the grid's thumbnail. */ +const POSTER_SIZE = 1280; +const THUMB_SIZE = 480; +/** The short side of the web copy: 1080p for a landscape video, 1080 wide for a phone's portrait one. */ +export const WEB_SHORT_SIDE = 1080; + +export class VideoToolMissing extends Error { + constructor(tool: string) { + super(`${tool}_missing`); + } +} + +/** + * Source has no usable video stream (audio-only, corrupt container, wrong extension). + * Indexing should mark FAILED without retry — ffmpeg `-map 0:v:0` cannot succeed. + */ +export class VideoUnsupported extends Error { + constructor(reason = "no_video_stream") { + super(reason); + this.name = "VideoUnsupported"; + } +} + +export interface VideoTools { + ffmpeg: string; + ffprobe: string; +} + +export interface VideoInfo { + durationMs: number | null; + width: number | null; + height: number | null; + capturedAt: Date | null; + hasAudio: boolean; + hasVideo: boolean; +} + +/** + * The tools to use: the ones named in the configuration; with the defaults ("ffmpeg" on PATH), the static build the + * deploy puts in the user's home (`~/.local/ffmpeg`, infra/deploy/deploy.sh) when it is there. + */ +export function findVideoTools(configured: VideoTools, home: string, exists: (file: string) => boolean = existsSync): VideoTools { + const local = (name: "ffmpeg" | "ffprobe") => { + const file = path.join(home, ".local", "ffmpeg", name); + return configured[name] === name && exists(file) ? file : configured[name]; + }; + return { ffmpeg: local("ffmpeg"), ffprobe: local("ffprobe") }; +} + +/** ffmpeg's arguments for the web copy (tested on their own). */ +export function webCopyArgs(input: string, output: string, opts: { audio: boolean }): string[] { + // Scales down only: the short side to WEB_SHORT_SIDE at most, the other to keep the shape (even, as H.264 needs). + // ffmpeg turns a phone's rotated video upright on the way (autorotate), so width and height are as shown. + const s = WEB_SHORT_SIDE; + const scale = `scale=w='if(gte(iw,ih),-2,min(${s},iw))':h='if(gte(iw,ih),min(${s},ih),-2)'`; + return [ + "-hide_banner", + "-nostdin", + "-loglevel", + "error", + "-y", + "-i", + input, + "-map", + "0:v:0", + ...(opts.audio ? ["-map", "0:a:0"] : []), + "-vf", + `${scale},format=yuv420p`, + "-c:v", + "libx264", + "-preset", + "veryfast", + "-crf", + "23", + "-profile:v", + "high", + ...(opts.audio ? ["-c:a", "aac", "-b:a", "128k", "-ac", "2"] : ["-an"]), + "-movflags", + "+faststart", + "-max_muxing_queue_size", + "1024", + output, + ]; +} + +/** Where to take the poster from: a second in, or a tenth of a short clip. */ +export function posterAt(durationMs: number | null): number { + if (!durationMs || durationMs <= 0) return 0; + return Math.min(1, durationMs / 10000); +} + +function run(bin: string, args: string[], tool: string): Promise { + return new Promise((resolve, reject) => { + const child = spawn(bin, args, { stdio: ["ignore", "pipe", "pipe"] }); + let out = ""; + let err = ""; + child.stdout.on("data", (d: Buffer) => (out += d.toString())); + child.stderr.on("data", (d: Buffer) => { + // Only the end matters (ffmpeg says why it stopped last). + err = (err + d.toString()).slice(-4000); + }); + child.on("error", (e: NodeJS.ErrnoException) => reject(e.code === "ENOENT" ? new VideoToolMissing(tool) : e)); + child.on("close", (code) => (code === 0 ? resolve(out) : reject(new Error(`${tool} exited ${code}: ${err.trim().split("\n").slice(-3).join(" | ")}`)))); + }); +} + +interface ProbeJson { + format?: { duration?: string; tags?: Record }; + streams?: { codec_type?: string; width?: number; height?: number; duration?: string; tags?: Record }[]; +} + +/** What ffprobe says of a file: length, size as stored, the camera's time, whether it has sound. */ +export async function probe(tools: VideoTools, file: string): Promise { + const json = JSON.parse(await run(tools.ffprobe, ["-v", "error", "-print_format", "json", "-show_format", "-show_streams", file], "ffprobe")) as ProbeJson; + return readProbe(json); +} + +export function readProbe(json: ProbeJson): VideoInfo { + const streams = json.streams ?? []; + const video = streams.find((s) => s.codec_type === "video"); + const seconds = Number(json.format?.duration ?? video?.duration); + const tags = { ...(video?.tags ?? {}), ...(json.format?.tags ?? {}) }; + // Apple's own tag keeps the time zone; creation_time is UTC. A camera that never had its clock set says 1970 or 1904. + const raw = tags["com.apple.quicktime.creationdate"] ?? tags.creation_time ?? null; + const when = raw ? new Date(raw) : null; + const capturedAt = when && !Number.isNaN(when.getTime()) && when.getUTCFullYear() >= 2000 && when.getTime() < Date.now() + 86_400_000 ? when : null; + return { + durationMs: Number.isFinite(seconds) && seconds > 0 ? Math.round(seconds * 1000) : null, + width: video?.width ?? null, + height: video?.height ?? null, + capturedAt, + hasAudio: streams.some((s) => s.codec_type === "audio"), + hasVideo: !!video, + }; +} + +/** Refuse sources with no video stream before ffmpeg `-map 0:v:0` (cryptic exit 234). */ +export function requireVideoStream(info: Pick): void { + if (!info.hasVideo) throw new VideoUnsupported(); +} + +/** + * The web copy, poster and thumbnail of `input`, written into `dir`. What it answers is read from the copy (its + * size is the one shown, upright), with the original's camera time. + */ +export async function makeWebCopy(tools: VideoTools, input: string, dir: string): Promise { + const original = await probe(tools, input); + requireVideoStream(original); + const web = path.join(dir, VIDEO_FILES.web); + await run(tools.ffmpeg, webCopyArgs(input, web, { audio: original.hasAudio }), "ffmpeg"); + const copy = await probe(tools, web); + const frame = path.join(dir, "frame.jpg"); + // The most typical frame among the first ones after the start (thumbnail filter), not a black first frame. + await run(tools.ffmpeg, ["-hide_banner", "-nostdin", "-loglevel", "error", "-y", "-ss", String(posterAt(copy.durationMs)), "-i", web, "-vf", "thumbnail=30", "-frames:v", "1", "-q:v", "2", frame], "ffmpeg"); + await sharp(frame).resize(POSTER_SIZE, POSTER_SIZE, { fit: "inside", withoutEnlargement: true }).jpeg({ quality: 85 }).toFile(path.join(dir, VIDEO_FILES.poster)); + await sharp(frame).resize(THUMB_SIZE, THUMB_SIZE, { fit: "inside", withoutEnlargement: true }).jpeg({ quality: 80 }).toFile(path.join(dir, VIDEO_FILES.thumb)); + return { ...copy, capturedAt: original.capturedAt, webBytes: (await stat(web)).size }; +} + +/** + * Frames of a video at `fps` a second (JPEG, the video's own size), for face analysis: the files in time order; + * frame i is at i / fps seconds from the start of the part read (`part`: from, and how long; the whole video + * without it). + */ +export async function extractFrames(tools: VideoTools, input: string, dir: string, fps: number, part?: { fromMs: number; lengthMs: number }): Promise { + const window = part ? ["-ss", (part.fromMs / 1000).toFixed(3), "-t", (part.lengthMs / 1000).toFixed(3)] : []; + await run(tools.ffmpeg, ["-hide_banner", "-nostdin", "-loglevel", "error", "-y", ...window, "-i", input, "-vf", `fps=${fps}`, "-q:v", "3", path.join(dir, "frame_%06d.jpg")], "ffmpeg"); + return (await readdir(dir)).filter((f) => /^frame_\d+\.jpg$/.test(f)).sort().map((f) => path.join(dir, f)); +} + +/** A `Range: bytes=…` header against a file's size: the part to send, `null` for the whole file, `"bad"` when it cannot be met. */ +export function parseRange(header: string | undefined, size: number): { start: number; end: number } | null | "bad" { + if (!header) return null; + const m = /^bytes=(\d*)-(\d*)$/.exec(header.trim()); + // Several ranges at once are not worth it for a player: the whole file. + if (!m) return header.includes(",") ? null : "bad"; + const [, a, b] = m; + if (a === "" && b === "") return "bad"; + let start: number; + let end: number; + if (a === "") { + // The last N bytes. + const n = Number(b); + if (!n) return "bad"; + start = Math.max(0, size - n); + end = size - 1; + } else { + start = Number(a); + end = b === "" ? size - 1 : Math.min(Number(b), size - 1); + } + if (start >= size || start > end) return "bad"; + return { start, end }; +} + +/** + * Sends a file the way video players ask for it: whole, or the part named by `Range` (206), so the player can + * start at once and jump to any moment. + */ +export async function sendFile(reply: FastifyReply, file: string, range: string | undefined, headers: Record): Promise { + const size = (await stat(file)).size; + for (const [k, v] of Object.entries(headers)) reply.header(k, v); + reply.header("accept-ranges", "bytes"); + const part = parseRange(range, size); + if (part === "bad") return reply.code(416).header("content-range", `bytes */${size}`).send(); + if (!part) return reply.header("content-length", String(size)).send(createReadStream(file)); + return reply + .code(206) + .header("content-range", `bytes ${part.start}-${part.end}/${size}`) + .header("content-length", String(part.end - part.start + 1)) + .send(createReadStream(file, { start: part.start, end: part.end })); +} diff --git a/apps/api/src/archive/viewer.ts b/apps/api/src/archive/viewer.ts index 6143557..97ca34a 100644 --- a/apps/api/src/archive/viewer.ts +++ b/apps/api/src/archive/viewer.ts @@ -11,12 +11,14 @@ import type { LocalStorage, UrlSigner } from "../storage/storage.js"; import { CloudClient, pollLogin, startLogin } from "./nextcloud.js"; import { GALLERY_KINDS, galleryMemberIds, gallerySeasons, listStoredGalleries, publishedPhotos, seasonOf } from "./gallery.js"; import type { SportsService } from "../sports/service.js"; -import { directorySides, teamMatcher, type TeamMatch } from "./match.js"; +import { readStoredRaws, readStoredTeams } from "./directory.js"; import type { FaceService } from "../faces/service.js"; -import { clubKey, faceBox, facesOfPhotos, registerArchivePeopleRoutes } from "./people.js"; +import { clubKind, faceBox, facesOfPhotos, registerArchivePeopleRoutes } from "./people.js"; import { registerArchiveDownloadRoutes } from "./downloads.js"; import { registerArchiveReviewRoutes } from "./review.js"; import type { ArchiveService } from "./service.js"; +import { sendFile, VIDEO_FILES, VIDEO_VARIANTS } from "./video.js"; +import { peopleInVideos } from "./video-faces.js"; /** * The archive for people outside the organization (the federation, the clubs, the press): they sign in with @@ -81,6 +83,8 @@ export class ViewerTokens { const SourceParams = z.object({ sourceId: z.uuid() }); const FolderParams = z.object({ folderId: z.uuid() }); const PhotoParams = z.object({ photoId: z.uuid() }); +const VideoFileParams = z.object({ videoId: z.uuid(), variant: z.enum(VIDEO_VARIANTS) }); +const VideoFileQuery = z.object({ exp: z.coerce.number().int(), sig: z.string().min(10).max(200) }); const GalleryQuery = z.object({ offset: z.coerce.number().int().min(0).default(0), limit: z.coerce.number().int().min(1).max(60).default(48), @@ -288,14 +292,6 @@ export async function registerArchiveViewerRoutes( return Prisma.sql`cf.source_id = ${sourceId}::uuid AND cf.status = 'DONE' AND cf.photo_id IS NOT NULL AND cf.folder_id = ANY(${visible}::uuid[]) AND ${publishedPhotos}`; }; - const folderWhere = (v: Viewer, visible: string[] | "all") => ({ - sourceId: v.s, - photoCount: { gt: 0 }, - eventId: { not: null }, - published: true, - ...(visible !== "all" && { id: { in: visible } }), - }); - /** What the sign-in page shows: the cloud's name and address. */ app.get("/v1/archive/:sourceId", async (req) => { const { sourceId } = SourceParams.parse(req.params); @@ -391,78 +387,14 @@ export async function registerArchiveViewerRoutes( return reply.code(204).send(); }); - /** - * The teams of the viewer's games under one name each: without the date or number a folder put before it ("01.23 - * Leixões SC"), and the known team's official name when exactly one fits ("SCP", "Sporting" → "Sporting CP"). - * Each with the names its galleries use, so filtering by it finds them all. - */ - /** - * Each source's folder team names and the known team they are (`canonicalTeam` compares a name with every known - * team: thousands of games times every team blocked the API for minutes). One answer per name, kept for a while, - * shared by every viewer of the source. - */ - const canonicalNames = new Map; names: Map }>(); - const CANONICAL_TTL_MS = 6 * 3600_000; - const DIRECTORY_WAIT_MS = 10_000; - const teamGroups = async (sourceId: string, games: Iterable<{ home: string; away: string }>): Promise; galleries: number }>> => { - let memo = canonicalNames.get(sourceId); - if (!memo || Date.now() - memo.at > CANONICAL_TTL_MS) { - const known = (async () => { - const source = await db.cloudSource.findUnique({ where: { id: sourceId }, select: { look: true, baseUrl: true } }); - const liga = source?.look === "liga" || /liga/i.test(source?.baseUrl ?? ""); - return teamMatcher(await db.sportsTeam.findMany({ where: liga ? { provider: "LIGA" } : { provider: { not: "LIGA" }, sport: { not: "futebol" } }, select: { name: true, abbreviation: true, slug: true } })); - })(); - known.catch(() => canonicalNames.delete(sourceId)); - memo = { at: Date.now(), known, names: new Map() }; - canonicalNames.set(sourceId, memo); - } - const canonical = await memo.known; - // "Juntar nomes" in this archive: another name of a club is the club. - const aliasOf = new Map((await db.archiveClubAlias.findMany({ where: { sourceId }, select: { aliasKey: true, name: true } })).map((a) => [a.aliasKey, a.name])); - const out = new Map; galleries: number }>(); - const byKey = new Map(); - const fold = (x: string) => x.normalize("NFD").replace(/[\u0300-\u036f]/g, "").toLowerCase().replace(/[^a-z0-9]+/g, " ").trim(); - let fresh = 0; - for (const g of games) - for (const raw of [g.home, g.away].flatMap((side) => (side ? directorySides(side, (n) => canonical.knownName(n)) : []))) { - if (!raw) continue; - let name = memo.names.get(raw); - if (name === undefined) { - name = canonical(raw); - memo.names.set(raw, name); - // Let other requests in between the new names (the first reading of a big archive). - if (++fresh % 25 === 0) await new Promise((r) => setImmediate(r)); - } - if (aliasOf.size) name = aliasOf.get(clubKey(raw)) ?? aliasOf.get(clubKey(name)) ?? name; - const key = fold(name); - const label = byKey.get(key) ?? name; - byKey.set(key, label); - const cur = out.get(label) ?? { names: new Set(), galleries: 0 }; - cur.names.add(raw); - cur.galleries++; - out.set(label, cur); - } - return out; - }; - - // The team names of every archive read once in the background after a start, so the first viewer of "Equipas" - // does not wait for them (and the proxy does not give up first). - const warmTeams = async () => { - const sources = await db.cloudSource.findMany({ where: { secretEnc: { not: null } }, select: { id: true } }); - for (const s of sources) { - const rows = await db.cloudFolder.findMany({ where: { sourceId: s.id, matchedBy: { not: "FOLDER" } }, select: { event: { select: { home: true, away: true } } } }); - await teamGroups(s.id, rows.flatMap((r) => (r.event ? [r.event] : []))); - } - }; if (!process.env.VITEST) { app.addHook("onReady", async () => { - // Before the site is served: the cards are a read of this column. + // Before the site is served: the cards are a read of this column. Teams are the worker's table, not this. try { await deps.archive.assignGalleries(); } catch (err) { app.log.warn({ err }, "archive: galleries not stored"); } - setTimeout(() => void warmTeams().catch((err: Error) => app.log.warn({ err }, "archive teams warm-up failed")), 5_000).unref(); }); } @@ -473,12 +405,11 @@ export async function registerArchiveViewerRoutes( const query = ListQuery.parse(req.query); const visible = await visibleFolders(v); const words = (query.q ?? "").split(/\s+/).filter(Boolean); - // A team of the directory: every name its galleries use. + // A team of the stored directory: every name its games were written as. The literal name until that row exists. let teamNames: string[] = []; if (query.team) { - const rows = await db.cloudFolder.findMany({ where: { ...folderWhere(v, visible), matchedBy: { not: "FOLDER" } }, select: { event: { select: { home: true, away: true } } } }); - const groups = await teamGroups(sourceId, rows.flatMap((r) => (r.event ? [r.event] : []))); - teamNames = [...(groups.get(query.team)?.names ?? new Set([query.team]))]; + const raws = await readStoredRaws(db, sourceId, query.team, visible); + teamNames = raws.length ? raws : [query.team]; } // One card per game or session, from the gallery written when the folder was scanned. The parts are not more cards. const page = await listStoredGalleries(db, { @@ -503,6 +434,16 @@ export async function registerArchiveViewerRoutes( ORDER BY COALESCE(f.gallery_folder_id, f.id), cf.path` : []; const cover = new Map(covers.map((file) => [file.gallery_id, file.photo_id])); + // A gallery of videos only: its first video's frame. + const videoOnly = page.galleries.filter((g) => !cover.has(g.id) && g.videoCount > 0).map((g) => g.id); + const videoCovers = videoOnly.length + ? await db.$queryRaw<{ gallery_id: string; id: string }[]>` + SELECT DISTINCT ON (COALESCE(f.gallery_folder_id, f.id)) COALESCE(f.gallery_folder_id, f.id) AS gallery_id, v.id + FROM cloud_videos v JOIN cloud_folders f ON f.id = v.folder_id + WHERE COALESCE(f.gallery_folder_id, f.id) = ANY(${videoOnly}::uuid[]) AND f.published AND v.status = 'DONE' + ORDER BY COALESCE(f.gallery_folder_id, f.id), v.path` + : []; + const videoCover = new Map(videoCovers.map((c) => [c.gallery_id, c.id])); // The seasons there are, for the filter (with the first page only). const seasons = query.offset === 0 ? await remembered(sourceId, "seasons", visible, () => gallerySeasons(db, sourceId, visible)) : undefined; return { @@ -525,36 +466,28 @@ export async function registerArchiveViewerRoutes( season: gallery.season, group: gallery.group, photoCount: gallery.photoCount, - cover: photoId ? signer.url(photoId, "thumb") : null, - coverLarge: photoId ? signer.url(photoId, "preview") : null, + videoCount: gallery.videoCount, + cover: photoId ? signer.url(photoId, "thumb") : videoCover.has(gallery.id) ? signer.videoUrl(videoCover.get(gallery.id)!, "thumb") : null, + coverLarge: photoId ? signer.url(photoId, "preview") : videoCover.has(gallery.id) ? signer.videoUrl(videoCover.get(gallery.id)!, "poster") : null, }; }), }; }); /** - * The teams in the viewer's games (for the directory and the search). Quick: folders and their events. The - * players named on photos are a scan of the photos, so they come apart (`/directory/players`) and the page shows - * the teams without waiting for them. + * The teams in the viewer's games. Written by the worker (`archive_team_sides`); this is only a read, and only + * of games this viewer may see. The players named on photos are a scan of the photos, so they come apart + * (`/directory/players`). */ app.get("/v1/archive/:sourceId/directory", async (req) => { const { sourceId } = SourceParams.parse(req.params); const v = viewerOf(req, sourceId); const visible = await visibleFolders(v); - const reading = remembered(sourceId, "teams", visible, async () => { - const folders = await db.cloudFolder.findMany({ where: { ...folderWhere(v, visible), matchedBy: { not: "FOLDER" } }, select: { event: { select: { id: true, home: true, away: true } } } }); - // Teams of games only (a session or a day of an event is named in "home" too), each game counted once. - const games = new Map(); - for (const f of folders) if (f.event) games.set(f.event.id, f.event); - return [...(await teamGroups(sourceId, games.values()))] - .map(([name, g]) => ({ name, galleries: g.galleries })) - .sort((a, b) => b.galleries - a.galleries || a.name.localeCompare(b.name)); - }); - // The first reading of a big archive can take a while: say so (the page asks again) rather than let the proxy - // time out. The reading goes on and is kept for the next ask. - const teams = await Promise.race([reading, new Promise((r) => setTimeout(() => r(null), DIRECTORY_WAIT_MS).unref())]); - if (!teams) return { teams: [], preparing: true }; - return { teams }; + const source = await db.cloudSource.findUnique({ where: { id: sourceId }, select: { directoryBuiltAt: true } }); + // The worker has not written this archive's teams yet. The page keeps its spinner; this answer is a read. + if (!source?.directoryBuiltAt) return { teams: [], ready: false }; + const teams = await readStoredTeams(db, sourceId, visible); + return { teams: teams.map((team) => ({ ...team, kind: clubKind(team.name) })), ready: true }; }); /** The players named on the viewer's photos (a session's folder per athlete, the editors' tags). */ @@ -644,6 +577,15 @@ export async function registerArchiveViewerRoutes( ORDER BY p.name` : Promise.resolve([]), ]); + // The gallery's videos come with its first page (they are few); not when it is filtered by a person or a player, + // whose faces and names are only on the photos for now. + const videos = + query.offset === 0 && !query.player && !query.person + ? await db.cloudVideo.findMany({ where: { folderId: { in: ids }, status: "DONE", storageKey: { not: null } }, orderBy: { path: "asc" }, take: 200 }) + : []; + const videoTotal = await db.cloudVideo.count({ where: { folderId: { in: ids }, status: "DONE", storageKey: { not: null } } }); + // Who appears in each video (named, or probable), and when: the player jumps to them. + const inVideos = await peopleInVideos(db, videos.map((x) => x.id)); const facePhotos = await db.photo.findMany({ where: { id: { in: sharpest.map((f) => f.photo_id) } }, select: { id: true, width: true, height: true, renderedSeq: true, developSnapshot: true }, @@ -669,7 +611,14 @@ export async function registerArchiveViewerRoutes( GROUP BY ROLLUP (f.photo_id)` : []; const pendingOf = new Map(waiting.filter((w) => w.photo_id).map((w) => [w.photo_id!, Number(w.n)])); - const pending = reviews ? Number(waiting.find((w) => !w.photo_id)?.n ?? 0) : undefined; + // And the appearances in the gallery's videos waiting for one. + const [videoWaiting] = reviews + ? await db.$queryRaw<{ n: number }[]>` + SELECT count(*)::int AS n FROM video_faces vf + JOIN face_groups g ON g.id = vf.group_id AND g.person_id IS NULL AND g.suggested_person_id IS NOT NULL AND g.ignored_at IS NULL + JOIN cloud_videos cv ON cv.id = vf.video_id AND cv.folder_id = ANY(${ids}::uuid[]) AND cv.status = 'DONE'` + : []; + const pending = reviews ? Number(waiting.find((w) => !w.photo_id)?.n ?? 0) + Number(videoWaiting?.n ?? 0) : undefined; return { id: shown.id, ...(pending !== undefined && { pending }), @@ -691,6 +640,21 @@ export async function registerArchiveViewerRoutes( people: named.map((p) => ({ id: p.id, name: p.name, count: Number(p.count), face: faceOf.get(p.id) ?? null })), /** Everyone named in this game, so a gallery can offer them even when this part has only some. */ roster: roster.map((p) => ({ id: p.id, name: p.name, club: p.club, number: p.number, here: Number(p.here), inGame: Number(p.in_game) })), + videoTotal, + videos: videos.map((x) => ({ + id: x.id, + name: x.path.split("/").pop(), + durationMs: x.durationMs, + width: x.width, + height: x.height, + capturedAt: x.capturedAt, + thumb: signer.videoUrl(x.id, "thumb"), + poster: signer.videoUrl(x.id, "poster"), + src: signer.videoUrl(x.id, "web"), + download: signer.videoUrl(x.id, "download"), + people: inVideos.get(x.id) ?? [], + ...(onCloud && { cloudUrl: `${base}/f/${x.fileId}` }), + })), photos: files.map((f) => ({ id: f.photo!.id, name: f.path.split("/").pop(), @@ -726,8 +690,54 @@ export async function registerArchiveViewerRoutes( return { id: file.photo.id, faces: faces.get(file.photo.id) ?? [] }; }); + /** + * A video's files by signed URL (`