diff --git a/Cargo.lock b/Cargo.lock index 9424d1d..4a7f58f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -61,12 +61,56 @@ dependencies = [ "libc", ] +[[package]] +name = "anstream" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "824a212faf96e9acacdbd09febd34438f8f711fb84e09a8916013cd7815ca28d" +dependencies = [ + "anstyle", + "anstyle-parse", + "anstyle-query", + "anstyle-wincon", + "colorchoice", + "is_terminal_polyfill", + "utf8parse", +] + [[package]] name = "anstyle" version = "1.0.14" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000" +[[package]] +name = "anstyle-parse" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52ce7f38b242319f7cabaa6813055467063ecdc9d355bbb4ce0c68908cd8130e" +dependencies = [ + "utf8parse", +] + +[[package]] +name = "anstyle-query" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "anstyle-wincon" +version = "3.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d" +dependencies = [ + "anstyle", + "once_cell_polyfill", + "windows-sys 0.61.2", +] + [[package]] name = "anyhow" version = "1.0.103" @@ -463,9 +507,9 @@ checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" [[package]] name = "cfg_aliases" -version = "0.2.1" +version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "613afe47fcd5fac7ccf1db93babcb082c5994d996f20b8b159f2ad1658eb5724" +checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527" [[package]] name = "chacha20" @@ -518,6 +562,7 @@ version = "4.6.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f09628afdcc538b57f3c6341e9c8e9970f18e4a481690a64974d7023bd33548b" dependencies = [ + "anstream", "anstyle", "clap_lex", "strsim", @@ -556,6 +601,12 @@ dependencies = [ "thiserror 2.0.18", ] +[[package]] +name = "colorchoice" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570" + [[package]] name = "combine" version = "4.6.7" @@ -777,38 +828,17 @@ dependencies = [ ] [[package]] -name = "darling" -version = "0.20.11" +name = "dashmap" +version = "6.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fc7f46116c46ff9ab3eb1597a45688b6715c6e628b5c133e288e709a29bcb4ee" +checksum = "e6361d5c062261c78a176addb82d4c821ae42bed6089de0e12603cd25de2059c" dependencies = [ - "darling_core", - "darling_macro", -] - -[[package]] -name = "darling_core" -version = "0.20.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0d00b9596d185e565c2207a0b01f8bd1a135483d02d9b7b0a54b11da8d53412e" -dependencies = [ - "fnv", - "ident_case", - "proc-macro2", - "quote", - "strsim", - "syn 2.0.118", -] - -[[package]] -name = "darling_macro" -version = "0.20.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fc34b93ccb385b40dc71c6fceac4b2ad23662c7eeb248cf10d529b7e055b6ead" -dependencies = [ - "darling_core", - "quote", - "syn 2.0.118", + "cfg-if", + "crossbeam-utils", + "hashbrown 0.14.5", + "lock_api", + "once_cell", + "parking_lot_core", ] [[package]] @@ -834,7 +864,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ccc2776f0c61eca1ca32528f85548abd1a4be8fb53d1b21c013e4f18da1e7090" dependencies = [ "data-encoding", - "syn 2.0.118", + "syn 1.0.109", ] [[package]] @@ -879,37 +909,6 @@ version = "0.5.8" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7cd812cc2bc1d69d4764bd80df88b4317eaef9e773c75226407d9bc0876b211c" -[[package]] -name = "derive_builder" -version = "0.20.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "507dfb09ea8b7fa618fcf76e953f4f5e192547945816d5358edffe39f6f94947" -dependencies = [ - "derive_builder_macro", -] - -[[package]] -name = "derive_builder_core" -version = "0.20.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2d5bcf7b024d6835cfb3d473887cd966994907effbe9227e8c8219824d06c4e8" -dependencies = [ - "darling", - "proc-macro2", - "quote", - "syn 2.0.118", -] - -[[package]] -name = "derive_builder_macro" -version = "0.20.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ab63b0e2bf4d5928aff72e83a7dace85d7bba5fe12dcc3c5a572d78caffd3f3c" -dependencies = [ - "derive_builder_core", - "syn 2.0.118", -] - [[package]] name = "derive_more" version = "2.1.1" @@ -958,6 +957,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2" dependencies = [ "block-buffer 0.12.1", + "const-oid 0.10.2", "crypto-common 0.2.2", ] @@ -1474,6 +1474,12 @@ dependencies = [ "byteorder", ] +[[package]] +name = "hashbrown" +version = "0.14.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1" + [[package]] name = "hashbrown" version = "0.15.5" @@ -1861,12 +1867,6 @@ dependencies = [ "zerovec", ] -[[package]] -name = "ident_case" -version = "1.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39" - [[package]] name = "identity-hash" version = "0.1.0" @@ -1966,9 +1966,9 @@ dependencies = [ [[package]] name = "iroh" -version = "1.0.1" +version = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1a2e38557969901f8b356d1ebd882253bab98cc81500d53e7bcbf33f56082303" +checksum = "460de6bc52163b41b1646931f2897e5ab986f0966ade444467fec25024751a72" dependencies = [ "backon", "blake3", @@ -2017,9 +2017,9 @@ dependencies = [ [[package]] name = "iroh-base" -version = "1.0.1" +version = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "61cdf012298adc13f5c2c821ad87214fecc9ac54c751301d45bf62b229a85da1" +checksum = "6be73e16ee21c923aca9b3121aaa0db936f7c7ecc156ff47b8dac944c68d59a8" dependencies = [ "curve25519-dalek", "data-encoding", @@ -2077,9 +2077,9 @@ dependencies = [ [[package]] name = "iroh-dns" -version = "1.0.1" +version = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4c24b83aae5ed4eced1c3724204c083c28c84c5d225a88e277eceeccce3dc3bd" +checksum = "46f6a9b39d18e6345f5c151afd299f2488e2cb5c520fe41b107b6bd3dc4c3349" dependencies = [ "arc-swap", "cfg_aliases", @@ -2118,12 +2118,20 @@ version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "291065721ad7c477b972e581bbc528df031dc8eb5e39fe1ff3300ae5dfb157ef" dependencies = [ + "http-body-util", + "hyper", + "hyper-util", "iroh-metrics-derive", "itoa", "n0-error", "portable-atomic", + "reqwest", + "rustls", + "rustls-platform-verifier", "ryu", "serde", + "tokio", + "tokio-util", "tracing", ] @@ -2141,13 +2149,15 @@ dependencies = [ [[package]] name = "iroh-relay" -version = "1.0.1" +version = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9f16a5505939f9250297ff2f1210b5142d13618f496eab03ce3f964fc47e2e2b" +checksum = "24bd586cf927f7b700f56ec3639b53cb5fa901ce284784051ff71092bfbf8193" dependencies = [ "blake3", "bytes", "cfg_aliases", + "clap", + "dashmap", "data-encoding", "derive_more", "getrandom 0.4.3", @@ -2168,19 +2178,29 @@ dependencies = [ "pin-project", "postcard", "rand 0.10.2", + "rcgen", + "reloadable-state", "reqwest", "rustls", + "rustls-cert-file-reader", + "rustls-cert-reloadable-resolver", "rustls-pki-types", "serde", "serde_bytes", + "serde_json", + "sha1 0.11.0", + "simdutf8", "strum", + "time", "tokio", "tokio-rustls", + "tokio-rustls-acme", "tokio-util", "tokio-websockets", + "toml 1.1.2+spec-1.1.0", "tracing", + "tracing-subscriber", "url", - "vergen-gitcl", "webpki-roots", "ws_stream_wasm", ] @@ -2264,6 +2284,12 @@ dependencies = [ "tracing", ] +[[package]] +name = "is_terminal_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" + [[package]] name = "itoa" version = "1.0.18" @@ -2714,9 +2740,9 @@ dependencies = [ [[package]] name = "noq" -version = "1.0.1" +version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4bf95190af1bd4a00a10e8255ca0c8ddd9e9a9f5e79151d7a7eb6d56aff5dc89" +checksum = "e11803df44ac03a30988d61585ea50885d5428e42da944fe1e498799da7886a2" dependencies = [ "bytes", "cfg_aliases", @@ -2736,9 +2762,9 @@ dependencies = [ [[package]] name = "noq-proto" -version = "1.0.1" +version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "aa6c890013591e709a3e45dd53501351b7e27e7ff3c7e9fc3dce43e300e7e9d3" +checksum = "334c3c9833f7b2c573cceb9896ddc7aaeb58c8807cbb63211b24d1fe88bf866e" dependencies = [ "aes-gcm", "bytes", @@ -2765,9 +2791,9 @@ dependencies = [ [[package]] name = "noq-udp" -version = "1.0.1" +version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3137a52df66c20090a889828d1c655f21f52294cba64e5c4fbb04fc83eee7c8e" +checksum = "bde7a5d5102f1cff03d482240f0ed20551661f63663620f4b26112ed751165e9" dependencies = [ "cfg_aliases", "libc", @@ -2879,15 +2905,6 @@ dependencies = [ "syn 2.0.118", ] -[[package]] -name = "num_threads" -version = "0.1.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5c7398b9c8b70908f6371f47ed36737907c87c52af34c268fed0bf0ceb92ead9" -dependencies = [ - "libc", -] - [[package]] name = "objc2" version = "0.6.4" @@ -2997,6 +3014,12 @@ dependencies = [ "portable-atomic", ] +[[package]] +name = "once_cell_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" + [[package]] name = "opaque-debug" version = "0.3.1" @@ -3539,6 +3562,23 @@ version = "0.8.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" +[[package]] +name = "reloadable-core" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1dc20ac1418988b60072d783c9f68e28a173fb63493c127952f6face3b40c6e0" + +[[package]] +name = "reloadable-state" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3853ef78d45b50f8b989896304a85239539d39b7f866a000e8846b9b72d74ce8" +dependencies = [ + "arc-swap", + "reloadable-core", + "tokio", +] + [[package]] name = "reqwest" version = "0.13.4" @@ -3562,6 +3602,8 @@ dependencies = [ "rustls", "rustls-pki-types", "rustls-platform-verifier", + "serde", + "serde_json", "sync_wrapper", "tokio", "tokio-rustls", @@ -3668,6 +3710,40 @@ dependencies = [ "zeroize", ] +[[package]] +name = "rustls-cert-file-reader" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8bb47c2a50fdfdaf95b0ac8b12620fc327da1fd4adbb30d0c56d866b005873ff" +dependencies = [ + "rustls-cert-read", + "rustls-pki-types", + "thiserror 2.0.18", + "tokio", +] + +[[package]] +name = "rustls-cert-read" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dd46e8c5ae4de3345c4786a83f99ec7aff287209b9e26fa883c473aeb28f19d5" +dependencies = [ + "rustls-pki-types", +] + +[[package]] +name = "rustls-cert-reloadable-resolver" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe1baa8a3a1f05eaa9fc55aed4342867f70e5c170ea3bfed1b38c51a4857c0c8" +dependencies = [ + "futures-util", + "reloadable-state", + "rustls", + "rustls-cert-read", + "thiserror 2.0.18", +] + [[package]] name = "rustls-native-certs" version = "0.8.4" @@ -3898,6 +3974,15 @@ dependencies = [ "zmij", ] +[[package]] +name = "serde_spanned" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6662b5879511e06e8999a8a235d848113e942c9124f211511b16466ee2995f26" +dependencies = [ + "serde_core", +] + [[package]] name = "serde_urlencoded" version = "0.7.1" @@ -3931,6 +4016,17 @@ dependencies = [ "digest 0.10.7", ] +[[package]] +name = "sha1" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aacc4cc499359472b4abe1bf11d0b12e688af9a805fa5e3016f9a386dc2d0214" +dependencies = [ + "cfg-if", + "cpufeatures 0.3.0", + "digest 0.11.3", +] + [[package]] name = "sha1_smol" version = "1.0.1" @@ -4234,7 +4330,7 @@ dependencies = [ "percent-encoding", "rand 0.8.6", "rsa", - "sha1", + "sha1 0.10.6", "sha2 0.10.9", "smallvec", "sqlx-core", @@ -4454,7 +4550,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" dependencies = [ "fastrand", - "getrandom 0.4.3", + "getrandom 0.3.4", "once_cell", "rustix", "windows-sys 0.61.2", @@ -4526,9 +4622,7 @@ checksum = "18dfaaeddcb932337b5e7866ee7d0ce9b76d2fd092997146f187ec09b4558a50" dependencies = [ "deranged", "js-sys", - "libc", "num-conv", - "num_threads", "powerfmt", "serde_core", "time-core", @@ -4614,6 +4708,34 @@ dependencies = [ "tokio", ] +[[package]] +name = "tokio-rustls-acme" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1af8573b15fdad8d66da116198cd8fd8d87ff62a67c1c6c3df7f62da1170793f" +dependencies = [ + "async-trait", + "base64", + "chrono", + "futures", + "log", + "num-bigint", + "pem", + "proc-macro2", + "rcgen", + "reqwest", + "ring", + "rustls", + "serde", + "serde_json", + "thiserror 2.0.18", + "time", + "tokio", + "tokio-rustls", + "webpki-roots", + "x509-parser", +] + [[package]] name = "tokio-stream" version = "0.1.18" @@ -4672,6 +4794,21 @@ dependencies = [ "serde", ] +[[package]] +name = "toml" +version = "1.1.2+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "81f3d15e84cbcd896376e6730314d59fb5a87f31e4b038454184435cd57defee" +dependencies = [ + "indexmap", + "serde_core", + "serde_spanned", + "toml_datetime", + "toml_parser", + "toml_writer", + "winnow 1.0.3", +] + [[package]] name = "toml_datetime" version = "1.1.1+spec-1.1.0" @@ -4702,6 +4839,12 @@ dependencies = [ "winnow 1.0.3", ] +[[package]] +name = "toml_writer" +version = "1.1.1+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "756daf9b1013ebe47a8776667b466417e2d4c5679d441c26230efd9ef78692db" + [[package]] name = "tower" version = "0.5.3" @@ -4915,7 +5058,7 @@ dependencies = [ "serde", "tempfile", "textwrap", - "toml", + "toml 0.5.11", "uniffi_internal_macros", "uniffi_meta", "uniffi_pipeline", @@ -4961,7 +5104,7 @@ dependencies = [ "quote", "serde", "syn 2.0.118", - "toml", + "toml 0.5.11", "uniffi_meta", ] @@ -5037,6 +5180,12 @@ version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be" +[[package]] +name = "utf8parse" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" + [[package]] name = "uuid" version = "1.23.4" @@ -5061,43 +5210,6 @@ version = "0.2.15" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426" -[[package]] -name = "vergen" -version = "9.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b849a1f6d8639e8de261e81ee0fc881e3e3620db1af9f2e0da015d4382ceaf75" -dependencies = [ - "anyhow", - "derive_builder", - "rustversion", - "vergen-lib", -] - -[[package]] -name = "vergen-gitcl" -version = "9.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "77ff3b5300a085d6bcd8fc96a507f706a28ae3814693236c9b409db71a1d15b9" -dependencies = [ - "anyhow", - "derive_builder", - "rustversion", - "time", - "vergen", - "vergen-lib", -] - -[[package]] -name = "vergen-lib" -version = "9.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b34a29ba7e9c59e62f229ae1932fb1b8fb8a6fdcc99215a641913f5f5a59a569" -dependencies = [ - "anyhow", - "derive_builder", - "rustversion", -] - [[package]] name = "version_check" version = "0.9.5" @@ -5117,6 +5229,7 @@ dependencies = [ "futures-lite", "iroh", "iroh-blobs", + "iroh-relay", "irpc", "irpc-iroh", "libc", @@ -5329,7 +5442,7 @@ version = "0.1.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" dependencies = [ - "windows-sys 0.61.2", + "windows-sys 0.48.0", ] [[package]] diff --git a/README.md b/README.md index 3172ea0..395adf5 100644 --- a/README.md +++ b/README.md @@ -50,6 +50,42 @@ mobile networks. If a direct path cannot be established, it can forward the same end-to-end encrypted connection through a relay. The relay forwards encrypted packets; it is not a VniDrop file store. +### Custom relay servers + +VniDrop uses Iroh's public relay and discovery infrastructure by default. In +**Settings → Network**, users can select one of four policies: + +- **Automatic (recommended):** use Iroh's public relays, with direct P2P/LAN + connections whenever possible. +- **Strict custom:** use only up to eight configured custom HTTPS relays or + direct connections. Startup reports an error if none of the custom relays can + be established. +- **Custom with direct fallback:** prefer the configured custom relays, but + continue with direct connections if they are unavailable. +- **Local only:** disable every relay and allow direct connections only, + primarily for devices on the same network. + +Strict custom, custom with direct fallback, and local only never use public +relays or public discovery, including relay addresses advertised by incoming +invitations. + +Applying a relay change restarts VniDrop's network engine, so active transfers +and shares must be stopped first. The app tests the new configuration and +restores the previous one if it cannot connect. Invitations created for an old +relay configuration may need to be shared again; stopped shares never expose +their stale invitations. If a long relay profile makes an invitation too large +for a QR code, use the native share action or export the invitation file. + +Relay credentials embedded in URLs are deliberately rejected and bearer-token +authentication is not currently supported. A self-hosted relay must either +accept the connecting endpoints or authorize their endpoint IDs independently; +the current device ID is shown in **Settings → Network** for this purpose. +Configure the same relay profile on participating devices. A custom relay needs +a TLS certificate issued by a publicly trusted WebPKI certificate authority; +private or enterprise CAs installed only in the operating system are not used +in this version. For resilient deployments, configure at least two relays in +different failure domains. + ## Why Iroh and `iroh-blobs`? VniDrop combines a networking layer with its own sharing rules: @@ -90,6 +126,7 @@ people, especially when using **Anyone with this transfer**. - Safe receive destinations that do not silently overwrite existing files - Native SwiftUI apps on iOS, iPadOS, and macOS; Compose apps on Android, Windows, and Linux +- Strict custom HTTPS relay profiles with safe apply and rollback - Opt-in diagnostics with transfer contents, invitations, and file paths excluded diff --git a/apple/Tests/AppModelTests.swift b/apple/Tests/AppModelTests.swift index 24da979..5f38949 100644 --- a/apple/Tests/AppModelTests.swift +++ b/apple/Tests/AppModelTests.swift @@ -20,6 +20,18 @@ final class AppModelTests: XCTestCase { _ = makeModel(core, preferences: Fixtures.preferences()) await waitUntil { core.state.isInitialized } XCTAssertTrue(core.state.isInitialized) + XCTAssertEqual(core.initializedNetworkConfigurations, [.automatic]) + } + + func testInitializesCoreWithSavedCustomRelayConfiguration() async { + let core = FakeCoreGateway() + let preferences = Fixtures.preferences() + let configuration = RelayConfiguration(mode: .strictCustom, relayURLs: ["https://relay.example"]) + preferences.setRelayConfiguration(configuration) + _ = makeModel(core, preferences: preferences) + + await waitUntil { core.state.isInitialized } + XCTAssertEqual(core.initializedNetworkConfigurations, [configuration]) } func testSelectDestination() { diff --git a/apple/Tests/AppPreferencesRepositoryTests.swift b/apple/Tests/AppPreferencesRepositoryTests.swift index b07d7fe..47d30f9 100644 --- a/apple/Tests/AppPreferencesRepositoryTests.swift +++ b/apple/Tests/AppPreferencesRepositoryTests.swift @@ -15,10 +15,11 @@ final class AppPreferencesRepositoryTests: XCTestCase { ) } - func testFallbacksWhenEmpty() { + func testMissingRelayProfileDefaultsToAutomatic() { let repo = AppPreferencesRepository(defaults: defaults(), fallback: fallback()) XCTAssertEqual(repo.preferences.username, "Default") XCTAssertEqual(repo.preferences.themeMode, .system) + XCTAssertEqual(repo.preferences.relayConfiguration, .automatic) } func testValuesPersistAndReload() { @@ -28,6 +29,10 @@ final class AppPreferencesRepositoryTests: XCTestCase { repo.setUsername("Bob") repo.setThemeMode(.dark) repo.setReceiveFolder(ReceiveFolder(kind: .iosSecurityScopedUrl, value: "file:///x", displayName: "Custom")) + repo.setRelayConfiguration(RelayConfiguration( + mode: .strictCustom, + relayURLs: ["https://relay-one.example", "https://relay-two.example:443"] + )) // A fresh repository over the same store reflects the persisted values. let reloaded = AppPreferencesRepository(defaults: store, fallback: fb) @@ -35,6 +40,40 @@ final class AppPreferencesRepositoryTests: XCTestCase { XCTAssertEqual(reloaded.preferences.themeMode, .dark) XCTAssertEqual(reloaded.preferences.receiveFolder.displayName, "Custom") XCTAssertEqual(reloaded.preferences.receiveFolder.kind, .iosSecurityScopedUrl) + XCTAssertEqual(reloaded.preferences.relayConfiguration, RelayConfiguration( + mode: .strictCustom, + relayURLs: ["https://relay-one.example", "https://relay-two.example:443"] + )) + XCTAssertNotNil(store.data(forKey: "relay_configuration")) + XCTAssertNil(store.object(forKey: "relay_mode")) + XCTAssertNil(store.object(forKey: "relay_urls")) + } + + func testCorruptedRelayProfileFailsClosed() { + let store = defaults() + store.set(Data("{".utf8), forKey: "relay_configuration") + + let repo = AppPreferencesRepository(defaults: store, fallback: fallback()) + + XCTAssertEqual( + repo.preferences.relayConfiguration, + RelayConfiguration(mode: .strictCustom, relayURLs: []) + ) + } + + func testUnknownRelayModeFailsClosed() { + let store = defaults() + store.set( + Data(#"{"mode":"future-mode","relayURLs":["https://relay.example"]}"#.utf8), + forKey: "relay_configuration" + ) + + let repo = AppPreferencesRepository(defaults: store, fallback: fallback()) + + XCTAssertEqual( + repo.preferences.relayConfiguration, + RelayConfiguration(mode: .strictCustom, relayURLs: []) + ) } func testResetReceiveFolderRestoresFallback() { diff --git a/apple/Tests/CoreRepositoryLifecycleTests.swift b/apple/Tests/CoreRepositoryLifecycleTests.swift new file mode 100644 index 0000000..7d0ce97 --- /dev/null +++ b/apple/Tests/CoreRepositoryLifecycleTests.swift @@ -0,0 +1,131 @@ +import Foundation +import XCTest +@preconcurrency import VnidropCore +@testable import VniDrop + +private enum BlockingCoreFactoryError: Error { + case stopped +} + +private final class BlockingCoreBindingFactory: CoreBindingFactory, @unchecked Sendable { + private let release = DispatchSemaphore(value: 0) + private let lock = NSLock() + private var initializeCallCount = 0 + private var initializationStarted = false + private var startWaiters: [CheckedContinuation] = [] + + var callCount: Int { + lock.lock() + defer { lock.unlock() } + return initializeCallCount + } + + func initialize( + appDataDir: String, + eventSink: CoreEventSink, + networkConfiguration: RelayConfiguration + ) throws -> VnidropCore { + lock.lock() + initializeCallCount += 1 + let call = initializeCallCount + initializationStarted = true + let waiters = startWaiters + startWaiters.removeAll() + lock.unlock() + waiters.forEach { $0.resume() } + + if call == 1 { + release.wait() + } + throw BlockingCoreFactoryError.stopped + } + + func waitUntilInitializationStarts() async { + await withCheckedContinuation { continuation in + lock.lock() + if initializationStarted { + lock.unlock() + continuation.resume() + } else { + startWaiters.append(continuation) + lock.unlock() + } + } + } + + func unblockInitialization() { + release.signal() + } +} + +@MainActor +final class CoreRepositoryLifecycleTests: XCTestCase { + func testIdleRequirementRejectsTransfersAndShares() throws { + XCTAssertNoThrow(try CoreNetworkLifecycle.requireIdle(activeTransfers: 0, activeShares: 0)) + XCTAssertThrowsError( + try CoreNetworkLifecycle.requireIdle(activeTransfers: 1, activeShares: 0) + ) { error in + XCTAssertEqual(error as? CoreNetworkLifecycleError, .activeNetworkWork) + } + XCTAssertThrowsError( + try CoreNetworkLifecycle.requireIdle(activeTransfers: 0, activeShares: 1) + ) { error in + XCTAssertEqual(error as? CoreNetworkLifecycleError, .activeNetworkWork) + } + } + + func testRestartSerializesInitializationAndRejectsNewNetworkWork() async { + let factory = BlockingCoreBindingFactory() + let repository = CoreRepository(coreFactory: factory) + let firstInitialization = Task { + await repository.initialize(appDataDir: "/tmp/first", networkConfiguration: .automatic) + } + await factory.waitUntilInitializationStarts() + + let safetyRelease = Task.detached { + try? await Task.sleep(nanoseconds: 1_000_000_000) + guard !Task.isCancelled else { return } + factory.unblockInitialization() + } + defer { + safetyRelease.cancel() + factory.unblockInitialization() + } + + let concurrentInitialization = await repository.initialize( + appDataDir: "/tmp/second", + networkConfiguration: RelayConfiguration(mode: .strictCustom, relayURLs: ["https://relay.example"]) + ) + assertLifecycleFailure(concurrentInitialization, equals: .transitionInProgress) + + let share = await repository.shareSources( + [], + transferName: "Blocked", + senderName: "Tester", + accessPolicy: .requireApproval + ) + assertLifecycleFailure(share, equals: .transitionInProgress) + + let receive = await repository.receive(ticket: "ticket", outputDir: "/tmp", receiverName: "Tester") + assertLifecycleFailure(receive, equals: .transitionInProgress) + XCTAssertEqual(factory.callCount, 1) + + factory.unblockInitialization() + guard case .failure(let error) = await firstInitialization.value else { + return XCTFail("The blocking factory should fail the first initialization") + } + XCTAssertTrue(error is BlockingCoreFactoryError) + } + + private func assertLifecycleFailure( + _ result: Result, + equals expected: CoreNetworkLifecycleError, + file: StaticString = #filePath, + line: UInt = #line + ) { + guard case .failure(let error) = result else { + return XCTFail("Expected lifecycle failure \(expected)", file: file, line: line) + } + XCTAssertEqual(error as? CoreNetworkLifecycleError, expected, file: file, line: line) + } +} diff --git a/apple/Tests/Fakes.swift b/apple/Tests/Fakes.swift index ed1e99d..d2e8520 100644 --- a/apple/Tests/Fakes.swift +++ b/apple/Tests/Fakes.swift @@ -25,6 +25,8 @@ final class FakeCoreGateway: CoreGateway { var cancelResult: Result = .success(()) var deleteResult: Result = .success(()) var clearReceiveHistoryResult: Result = .success(0) + var initializeResult: Result = .success(()) + var initializeResults: [Result] = [] // Recorded calls private(set) var responses: [(id: String, accepted: Bool, reason: String?)] = [] @@ -35,11 +37,18 @@ final class FakeCoreGateway: CoreGateway { private(set) var lastReceiveTicket: String? private(set) var lastReceiveReceiverName: String? private(set) var lastShareAccessPolicy: ShareAccessPolicy? + private(set) var initializedNetworkConfigurations: [RelayConfiguration] = [] func setState(_ state: CoreState) { stateSubject.send(state) } func emit(_ signal: CoreSignal) { signalsSubject.send(signal) } - func initialize(appDataDir: String) async -> Result { + func initialize( + appDataDir: String, + networkConfiguration: RelayConfiguration + ) async -> Result { + initializedNetworkConfigurations.append(networkConfiguration) + let result = initializeResults.isEmpty ? initializeResult : initializeResults.removeFirst() + guard case .success = result else { return result } var s = stateSubject.value s.isInitialized = true stateSubject.send(s) diff --git a/apple/Tests/RelayConfigurationTests.swift b/apple/Tests/RelayConfigurationTests.swift new file mode 100644 index 0000000..2196849 --- /dev/null +++ b/apple/Tests/RelayConfigurationTests.swift @@ -0,0 +1,121 @@ +import XCTest +@testable import VniDrop + +final class RelayConfigurationTests: XCTestCase { + func testCustomFallbackValidatesAndPreservesItsMode() throws { + let result = try RelayConfigurationValidator.validate( + mode: .customWithDirectFallback, + relayURLs: ["https://relay.example/"] + ) + + XCTAssertEqual( + result, + RelayConfiguration( + mode: .customWithDirectFallback, + relayURLs: ["https://relay.example"] + ) + ) + } + + func testLocalOnlyRetainsPreviouslySavedRelayURLs() throws { + let retained = ["https://relay.example"] + let result = try RelayConfigurationValidator.validate( + mode: .localOnly, + relayURLs: ["not a URL"], + retainedRelayURLs: retained + ) + + XCTAssertEqual(result, RelayConfiguration(mode: .localOnly, relayURLs: retained)) + } + + func testAutomaticModeIgnoresRelayDrafts() throws { + let result = try RelayConfigurationValidator.validate( + mode: .automatic, + relayURLs: ["not a URL"] + ) + XCTAssertEqual(result, .automatic) + } + + func testAutomaticModeRetainsPreviouslySavedRelayURLs() throws { + let result = try RelayConfigurationValidator.validate( + mode: .automatic, + relayURLs: ["not a URL"], + retainedRelayURLs: ["https://relay.example"] + ) + XCTAssertEqual(result, RelayConfiguration( + mode: .automatic, + relayURLs: ["https://relay.example"] + )) + } + + func testCustomModeTrimsValidHTTPSRelayURLs() throws { + let result = try RelayConfigurationValidator.validate( + mode: .strictCustom, + relayURLs: [" https://relay.example/ ", "https://backup.example:443"] + ) + XCTAssertEqual(result, RelayConfiguration( + mode: .strictCustom, + relayURLs: ["https://relay.example", "https://backup.example"] + )) + } + + func testCustomModeIgnoresEmptyURLRows() throws { + let result = try RelayConfigurationValidator.validate( + mode: .strictCustom, + relayURLs: ["", " ", "https://relay.example"] + ) + XCTAssertEqual(result.relayURLs, ["https://relay.example"]) + } + + func testCustomModeRequiresAtLeastOneRelay() { + XCTAssertThrowsError(try RelayConfigurationValidator.validate(mode: .strictCustom, relayURLs: [])) { error in + XCTAssertEqual(error as? RelayConfigurationValidationError, .missingURL) + } + } + + func testCustomModeRequiresHTTPS() { + XCTAssertThrowsError(try RelayConfigurationValidator.validate( + mode: .strictCustom, + relayURLs: ["http://relay.example"] + )) { error in + XCTAssertEqual(error as? RelayConfigurationValidationError, .httpsRequired(index: 0)) + } + } + + func testCustomModeRejectsCredentialsQueryFragmentAndPath() { + let invalidURLs = [ + "https://user:password@relay.example", + "https://relay.example?token=secret", + "https://relay.example#fragment", + "https://relay.example/custom/path", + "https://relay.example:0", + "https://relay.example:99999", + ] + for relayURL in invalidURLs { + XCTAssertThrowsError( + try RelayConfigurationValidator.validate(mode: .strictCustom, relayURLs: [relayURL]), + "Expected \(relayURL) to be rejected" + ) { error in + XCTAssertEqual(error as? RelayConfigurationValidationError, .invalidURL(index: 0)) + } + } + } + + func testCustomModeRejectsNormalizedDuplicate() { + XCTAssertThrowsError(try RelayConfigurationValidator.validate( + mode: .strictCustom, + relayURLs: ["https://relay.example", "https://RELAY.example:443/"] + )) { error in + XCTAssertEqual(error as? RelayConfigurationValidationError, .duplicateURL(index: 1)) + } + } + + func testCustomModeRejectsMoreThanEightRelays() { + let relayURLs = (0...RelayConfigurationValidator.maximumRelayCount).map { + "https://relay-\($0).example" + } + XCTAssertThrowsError(try RelayConfigurationValidator.validate(mode: .strictCustom, relayURLs: relayURLs)) { error in + XCTAssertEqual(error as? RelayConfigurationValidationError, .tooManyURLs) + } + } +} diff --git a/apple/Tests/SendModelTests.swift b/apple/Tests/SendModelTests.swift index 12b1801..641dbf2 100644 --- a/apple/Tests/SendModelTests.swift +++ b/apple/Tests/SendModelTests.swift @@ -58,4 +58,25 @@ final class SendModelTests: XCTestCase { let response = core.responses.first { $0.id == "req-1" } XCTAssertEqual(response?.accepted, false) } + + func testOnlyActiveShareExposesStoredInvitationTicket() { + XCTAssertEqual( + Fixtures.transfer(id: 1, direction: .send, status: .sharing).invitationPresentation, + .ready("ticket") + ) + XCTAssertEqual( + Fixtures.transfer(id: 2, direction: .send, status: .importing).invitationPresentation, + .preparing + ) + for status in [TransferStatus.stopped, .failed, .cancelled, .done] { + XCTAssertEqual( + Fixtures.transfer(id: 3, direction: .send, status: status).invitationPresentation, + .unavailable + ) + } + } + + func testOversizedInvitationReportsQRCodeUnavailable() { + XCTAssertNil(QRCode.generate(from: String(repeating: "x", count: 10_000))) + } } diff --git a/apple/Tests/SettingsModelTests.swift b/apple/Tests/SettingsModelTests.swift index a6623f1..e565762 100644 --- a/apple/Tests/SettingsModelTests.swift +++ b/apple/Tests/SettingsModelTests.swift @@ -42,4 +42,107 @@ final class SettingsModelTests: XCTestCase { await waitUntil { core.deletedTransfers.count == 2 } XCTAssertEqual(Set(core.deletedTransfers), [2, 3]) } + + func testNetworkSettingsExposeCurrentEndpointId() { + let core = FakeCoreGateway() + let model = makeModel(core, preferences: Fixtures.preferences()) + + core.setState(CoreState( + isInitialized: true, + status: CoreStatus(endpointId: "endpoint-for-allowlist", activeTransfers: 0, activeShares: 0) + )) + + XCTAssertEqual(model.state.endpointId, "endpoint-for-allowlist") + } + + func testApplyCustomRelayRestartsCoreThenPersistsConfiguration() async { + let core = FakeCoreGateway() + let preferences = Fixtures.preferences() + let model = makeModel(core, preferences: preferences) + model.setRelayMode(.strictCustom) + model.setRelayURL(" https://relay.example/ ", at: 0) + + model.applyRelayConfiguration() + + await waitUntil { preferences.preferences.relayConfiguration.mode == .strictCustom } + let expected = RelayConfiguration(mode: .strictCustom, relayURLs: ["https://relay.example"]) + XCTAssertEqual(preferences.preferences.relayConfiguration, expected) + XCTAssertEqual(core.initializedNetworkConfigurations, [expected]) + XCTAssertFalse(model.state.relayConfigurationIsDirty) + } + + func testApplyingAutomaticRetainsLastCustomRelayURLs() async { + let core = FakeCoreGateway() + let preferences = Fixtures.preferences() + let relayURLs = ["https://relay.example", "https://backup.example"] + preferences.setRelayConfiguration(RelayConfiguration(mode: .strictCustom, relayURLs: relayURLs)) + let model = makeModel(core, preferences: preferences) + + model.setRelayMode(.automatic) + model.applyRelayConfiguration() + + await waitUntil { preferences.preferences.relayConfiguration.mode == .automatic } + XCTAssertEqual(preferences.preferences.relayConfiguration.relayURLs, relayURLs) + XCTAssertEqual(core.initializedNetworkConfigurations, [ + RelayConfiguration(mode: .automatic, relayURLs: relayURLs), + ]) + model.setRelayMode(.strictCustom) + XCTAssertEqual(model.state.relayURLs, relayURLs) + } + + func testApplyRelayIsBlockedWhileShareIsActive() async { + let core = FakeCoreGateway() + let preferences = Fixtures.preferences() + let model = makeModel(core, preferences: preferences) + core.setState(CoreState( + isInitialized: true, + status: CoreStatus(endpointId: "endpoint", activeTransfers: 0, activeShares: 1) + )) + model.setRelayMode(.strictCustom) + model.setRelayURL("https://relay.example", at: 0) + + model.applyRelayConfiguration() + await Task.yield() + + XCTAssertTrue(core.initializedNetworkConfigurations.isEmpty) + XCTAssertEqual(preferences.preferences.relayConfiguration, .automatic) + XCTAssertEqual(model.state.relayApplyErrorKey, "relay_apply_active_transfers") + } + + func testRepositoryActiveWorkRejectionDoesNotAttemptRollback() async { + let core = FakeCoreGateway() + core.initializeResult = .failure(CoreNetworkLifecycleError.activeNetworkWork) + let preferences = Fixtures.preferences() + let model = makeModel(core, preferences: preferences) + let attempted = RelayConfiguration(mode: .strictCustom, relayURLs: ["https://relay.example"]) + model.setRelayMode(.strictCustom) + model.setRelayURL(attempted.relayURLs[0], at: 0) + + model.applyRelayConfiguration() + await waitUntil { + core.initializedNetworkConfigurations.count == 1 && !model.state.isApplyingRelayConfiguration + } + + XCTAssertEqual(core.initializedNetworkConfigurations, [attempted]) + XCTAssertEqual(preferences.preferences.relayConfiguration, .automatic) + XCTAssertTrue(model.state.hasActiveNetworkWork) + XCTAssertEqual(model.state.relayApplyErrorKey, "relay_apply_active_transfers") + } + + func testFailedRelayApplyRollsBackWithoutPersisting() async { + let core = FakeCoreGateway() + core.initializeResults = [.failure(TestError.unimplemented), .success(())] + let preferences = Fixtures.preferences() + let model = makeModel(core, preferences: preferences) + let attempted = RelayConfiguration(mode: .strictCustom, relayURLs: ["https://relay.example"]) + model.setRelayMode(.strictCustom) + model.setRelayURL(attempted.relayURLs[0], at: 0) + + model.applyRelayConfiguration() + await waitUntil { core.initializedNetworkConfigurations.count == 2 } + + XCTAssertEqual(core.initializedNetworkConfigurations, [attempted, .automatic]) + XCTAssertEqual(preferences.preferences.relayConfiguration, .automatic) + XCTAssertEqual(model.state.relayApplyErrorKey, "relay_apply_failed") + } } diff --git a/apple/VniDrop/Core/AppPreferences.swift b/apple/VniDrop/Core/AppPreferences.swift index 1508d4d..df56a2c 100644 --- a/apple/VniDrop/Core/AppPreferences.swift +++ b/apple/VniDrop/Core/AppPreferences.swift @@ -19,6 +19,101 @@ enum FolderAccessStatus { case unavailable } +enum RelayPreferenceMode: String, Codable, CaseIterable, Sendable { + case automatic + case strictCustom = "custom" + case customWithDirectFallback = "custom-with-direct-fallback" + case localOnly = "local-only" + + var usesCustomRelayURLs: Bool { + self == .strictCustom || self == .customWithDirectFallback + } +} + +struct RelayConfiguration: Equatable, Codable, Sendable { + var mode: RelayPreferenceMode + var relayURLs: [String] + + static let automatic = RelayConfiguration(mode: .automatic, relayURLs: []) +} + +enum RelayConfigurationValidationError: Error, Equatable, Sendable { + case missingURL + case tooManyURLs + case httpsRequired(index: Int) + case invalidURL(index: Int) + case duplicateURL(index: Int) + + var urlIndex: Int? { + switch self { + case .httpsRequired(let index), .invalidURL(let index), .duplicateURL(let index): return index + case .missingURL, .tooManyURLs: return nil + } + } +} + +enum RelayConfigurationValidator { + static let maximumRelayCount = 8 + static let maximumRelayURLBytes = 2_048 + + static func validate( + mode: RelayPreferenceMode, + relayURLs: [String], + retainedRelayURLs: [String] = [] + ) throws -> RelayConfiguration { + guard mode.usesCustomRelayURLs else { + return RelayConfiguration(mode: mode, relayURLs: retainedRelayURLs) + } + + let relayEntries = relayURLs.enumerated().compactMap { index, value -> (Int, String)? in + let trimmed = value.trimmingCharacters(in: .whitespacesAndNewlines) + return trimmed.isEmpty ? nil : (index, trimmed) + } + guard !relayEntries.isEmpty else { + throw RelayConfigurationValidationError.missingURL + } + guard relayEntries.count <= maximumRelayCount else { + throw RelayConfigurationValidationError.tooManyURLs + } + + var seen = Set() + var normalizedURLs: [String] = [] + for (index, relayURL) in relayEntries { + guard relayURL.lengthOfBytes(using: .utf8) <= maximumRelayURLBytes, + relayURL.rangeOfCharacter(from: .whitespacesAndNewlines.union(.controlCharacters)) == nil, + var components = URLComponents(string: relayURL) else { + throw RelayConfigurationValidationError.invalidURL(index: index) + } + guard components.scheme?.lowercased() == "https" else { + throw RelayConfigurationValidationError.httpsRequired(index: index) + } + guard + let host = components.host, + !host.isEmpty, + components.port.map({ (1...65_535).contains($0) }) ?? true, + components.user == nil, + components.password == nil, + components.query == nil, + components.fragment == nil, + components.path.isEmpty || components.path == "/" + else { + throw RelayConfigurationValidationError.invalidURL(index: index) + } + + components.scheme = "https" + components.host = host.lowercased() + if components.port == 443 { components.port = nil } + if components.path == "/" { components.path = "" } + guard let canonicalURL = components.string, seen.insert(canonicalURL).inserted else { + throw RelayConfigurationValidationError.duplicateURL(index: index) + } + normalizedURLs.append(canonicalURL) + } + + return RelayConfiguration(mode: mode, relayURLs: normalizedURLs) + } +} + /// Persisted app preferences, ported from `preferences/AppPreferencesRepository.kt`. /// Backed by `UserDefaults` instead of DataStore; keys and semantics match. struct AppPreferences: Equatable { @@ -27,6 +122,7 @@ struct AppPreferences: Equatable { var themeMode: ThemeMode var diagnosticsEnabled: Bool var diagnosticsInstallId: String + var relayConfiguration: RelayConfiguration } struct AppPreferencesDefaults { @@ -51,6 +147,7 @@ final class AppPreferencesRepository: ObservableObject { static let themeMode = "theme_mode" static let diagnosticsEnabled = "diagnostics_enabled" static let diagnosticsInstallId = "diagnostics_install_id" + static let relayConfiguration = "relay_configuration" } init(defaults: UserDefaults = .standard, fallback: AppPreferencesDefaults) { @@ -70,10 +167,24 @@ final class AppPreferencesRepository: ObservableObject { receiveFolder: folder, themeMode: themeMode, diagnosticsEnabled: diagnostics, - diagnosticsInstallId: installId + diagnosticsInstallId: installId, + relayConfiguration: resolveRelayConfiguration(defaults) ) } + private static func resolveRelayConfiguration(_ defaults: UserDefaults) -> RelayConfiguration { + guard defaults.object(forKey: Key.relayConfiguration) != nil else { return .automatic } + guard + let data = defaults.data(forKey: Key.relayConfiguration), + let configuration = try? JSONDecoder().decode(RelayConfiguration.self, from: data) + else { + // A stored profile must never silently fall back to public relays. Strict + // custom with no URLs makes startup fail closed until Settings repairs it. + return RelayConfiguration(mode: .strictCustom, relayURLs: []) + } + return configuration + } + private static func resolveReceiveFolder(_ defaults: UserDefaults, fallback: ReceiveFolder) -> ReceiveFolder { let kind = defaults.string(forKey: Key.receiveFolderKind) .flatMap(ReceiveFolderKind.init(rawValue:)) ?? fallback.kind @@ -113,6 +224,12 @@ final class AppPreferencesRepository: ObservableObject { reload() } + func setRelayConfiguration(_ configuration: RelayConfiguration) { + guard let encoded = try? JSONEncoder().encode(configuration) else { return } + defaults.set(encoded, forKey: Key.relayConfiguration) + reload() + } + @discardableResult func ensureDiagnosticsInstallId() -> String { let existing = preferences.diagnosticsInstallId diff --git a/apple/VniDrop/Core/CoreGateway.swift b/apple/VniDrop/Core/CoreGateway.swift index ee673f1..e7a5620 100644 --- a/apple/VniDrop/Core/CoreGateway.swift +++ b/apple/VniDrop/Core/CoreGateway.swift @@ -24,7 +24,7 @@ protocol CoreGateway: AnyObject { /// Coalesced change hints emitted by the event sink. var signals: AnyPublisher { get } - func initialize(appDataDir: String) async -> Result + func initialize(appDataDir: String, networkConfiguration: RelayConfiguration) async -> Result func shutdown() func shareSources( _ sources: [ShareSource], diff --git a/apple/VniDrop/Core/CoreModels.swift b/apple/VniDrop/Core/CoreModels.swift index df40304..ca594f2 100644 --- a/apple/VniDrop/Core/CoreModels.swift +++ b/apple/VniDrop/Core/CoreModels.swift @@ -134,6 +134,7 @@ enum ReceiverDeliveryStatus: Equatable, Sendable { case refused case expired case completed + case failed case unknown } diff --git a/apple/VniDrop/Core/CoreRepository.swift b/apple/VniDrop/Core/CoreRepository.swift index f7ea1a3..ed9c81a 100644 --- a/apple/VniDrop/Core/CoreRepository.swift +++ b/apple/VniDrop/Core/CoreRepository.swift @@ -2,6 +2,65 @@ import Foundation import Combine @preconcurrency import VnidropCore +enum CoreNetworkLifecycleError: Error, Equatable, LocalizedError, Sendable { + case transitionInProgress + case activeNetworkWork + + var errorDescription: String? { + switch self { + case .transitionInProgress: return "A network restart is already in progress." + case .activeNetworkWork: return "Stop active transfers and shares before restarting the network." + } + } +} + +enum CoreNetworkLifecycle { + nonisolated static func requireIdle(activeTransfers: UInt64, activeShares: UInt64) throws { + guard activeTransfers == 0, activeShares == 0 else { + throw CoreNetworkLifecycleError.activeNetworkWork + } + } +} + +protocol CoreBindingFactory: Sendable { + func initialize( + appDataDir: String, + eventSink: CoreEventSink, + networkConfiguration: RelayConfiguration + ) throws -> VnidropCore +} + +struct NativeCoreBindingFactory: CoreBindingFactory { + func initialize( + appDataDir: String, + eventSink: CoreEventSink, + networkConfiguration: RelayConfiguration + ) throws -> VnidropCore { + let nativeConfiguration: CoreNetworkConfig + switch networkConfiguration.mode { + case .automatic: + nativeConfiguration = defaultCoreNetworkConfig() + case .strictCustom: + nativeConfiguration = CoreNetworkConfig( + mode: .strictCustom, + relayUrls: networkConfiguration.relayURLs + ) + case .customWithDirectFallback: + nativeConfiguration = CoreNetworkConfig( + mode: .customWithDirectFallback, + relayUrls: networkConfiguration.relayURLs + ) + case .localOnly: + nativeConfiguration = CoreNetworkConfig(mode: .localOnly, relayUrls: []) + } + return try VnidropCore.initializeWithNetworkConfig( + appDataDir: appDataDir, + eventSink: eventSink, + networkConfig: nativeConfiguration + ) + } +} + /// Swift port of `core/CoreRepository.kt`. Owns the `VnidropCore` handle, maps the /// generated UniFFI records into app domain models, publishes an observable /// `CoreState`, and emits coalesced `CoreSignal`s from the event sink. @@ -17,28 +76,65 @@ final class CoreRepository: ObservableObject, CoreGateway { /// Coalesced change hints; subscribe to react to approval/history/transfer changes. var signals: AnyPublisher { signalsSubject.eraseToAnyPublisher() } - // Set on the main actor (initialize/shutdown) but read from `queue` inside - // `runCore`; the underlying core is internally synchronized, so this crossing - // is safe. `nonisolated(unsafe)` documents that contract for Swift 6. + // Initialization swaps happen on `queue`; shutdown and snapshot reads may also + // access the handle from the main actor. The underlying core is internally + // synchronized, and `nonisolated(unsafe)` documents that crossing for Swift 6. private nonisolated(unsafe) var core: VnidropCore? + // Core calls run through `dispatcher` (see runCore/runInterrupt); the factory + // and transition flag drive relay-aware (re)initialization. private let dispatcher = CoreDispatcher() + private let coreFactory: any CoreBindingFactory + private var isNetworkTransitionInProgress = false private lazy var sink = RepositoryEventSink { [weak self] event in Task { @MainActor in self?.handle(event: event) } } private nonisolated static let maxEvents = 200 + init(coreFactory: any CoreBindingFactory = NativeCoreBindingFactory()) { + self.coreFactory = coreFactory + } + // MARK: - Lifecycle - func initialize(appDataDir: String) async -> Result { - await runCore { [sink] in - self.core?.shutdown() - let created = try VnidropCore.initialize(appDataDir: appDataDir, eventSink: sink) - return created - }.map { created in + func initialize( + appDataDir: String, + networkConfiguration: RelayConfiguration + ) async -> Result { + guard !isNetworkTransitionInProgress else { + return .failure(CoreNetworkLifecycleError.transitionInProgress) + } + isNetworkTransitionInProgress = true + defer { isNetworkTransitionInProgress = false } + + let result = await runCore { [sink] in + if let existing = self.core { + let status = existing.status() + try CoreNetworkLifecycle.requireIdle( + activeTransfers: status.activeTransfers, + activeShares: status.activeShares + ) + existing.shutdown() + self.core = nil + } + let created = try self.coreFactory.initialize( + appDataDir: appDataDir, + eventSink: sink, + networkConfiguration: networkConfiguration + ) self.core = created + return created + } + switch result { + case .success: self.refreshSnapshot() self.state.isInitialized = true + return .success(()) + case .failure(let error): + if error as? CoreNetworkLifecycleError != .activeNetworkWork { + self.state = CoreState() + } + return .failure(error) } } @@ -56,6 +152,9 @@ final class CoreRepository: ObservableObject, CoreGateway { senderName: String, accessPolicy: ShareAccessPolicy ) async -> Result { + guard !isNetworkTransitionInProgress else { + return .failure(CoreNetworkLifecycleError.transitionInProgress) + } guard !sources.isEmpty else { return .failure(InvitationError.message("Select at least one file to share")) } @@ -89,7 +188,10 @@ final class CoreRepository: ObservableObject, CoreGateway { } func receive(ticket: String, outputDir: String, receiverName: String) async -> Result { - await runCore { + guard !isNetworkTransitionInProgress else { + return .failure(CoreNetworkLifecycleError.transitionInProgress) + } + return await runCore { try self.requireCore().receive( ticket: ticket, outputDir: outputDir, @@ -105,7 +207,10 @@ final class CoreRepository: ObservableObject, CoreGateway { outputDirectoryUrl: String, receiverName: String ) async -> Result { - await runCore { + guard !isNetworkTransitionInProgress else { + return .failure(CoreNetworkLifecycleError.transitionInProgress) + } + return await runCore { try withSecurityScopedAccess(pathOrUrl: outputDirectoryUrl) { try self.requireCore().receive( ticket: ticket, @@ -409,6 +514,7 @@ private extension ReceiverRequest { case "refused": return .refused case "expired": return .expired case "completed": return .completed + case "failed": return .failed default: return .unknown } } diff --git a/apple/VniDrop/Features/App/AppModel.swift b/apple/VniDrop/Features/App/AppModel.swift index f9df8b5..8357f26 100644 --- a/apple/VniDrop/Features/App/AppModel.swift +++ b/apple/VniDrop/Features/App/AppModel.swift @@ -26,7 +26,10 @@ final class AppModel: ObservableObject { AppLogger.info("lifecycle", "app started", ["platform": environment.name]) Task { - let result = await repository.initialize(appDataDir: environment.defaultCoreDataDir) + let result = await repository.initialize( + appDataDir: environment.defaultCoreDataDir, + networkConfiguration: preferences.preferences.relayConfiguration + ) if case .failure(let error) = result { messages.error(error) } } diff --git a/apple/VniDrop/Features/Send/TransferDetailsView.swift b/apple/VniDrop/Features/Send/TransferDetailsView.swift index da537d6..cc86990 100644 --- a/apple/VniDrop/Features/Send/TransferDetailsView.swift +++ b/apple/VniDrop/Features/Send/TransferDetailsView.swift @@ -236,6 +236,7 @@ private struct ReceiverRow: View { let name = receiver.receiverName ?? receiver.receiverDeviceName ?? String(localized: L10n.Transfer.nearbyDevice) let showLive = sendProgress != nil && receiver.status != .completed && receiver.status != .refused && receiver.status != .expired + && receiver.status != .failed HStack(alignment: .top, spacing: 12) { VStack(alignment: .leading, spacing: 6) { Text(name).font(VniType.bodyLarge).lineLimit(1) @@ -277,24 +278,39 @@ struct TransferSharePanel: View { var body: some View { PanelContainer(title: String(localized: L10n.Transfer.shareTitle)) { - if let ticket = transfer.ticket { - qrCard(ticket: ticket) - Text(String(localized: L10n.Transfer.scanQr)) - .font(VniType.bodySmall).foregroundStyle(colors.foregroundLighter) - .frame(maxWidth: .infinity) + switch transfer.invitationPresentation { + case .ready(let ticket): + let qrImage = QRCode.generate(from: ticket) + qrCard(image: qrImage) + if qrImage != nil { + Text(String(localized: L10n.Transfer.scanQr)) + .font(VniType.bodySmall).foregroundStyle(colors.foregroundLighter) + .frame(maxWidth: .infinity) + } ShareActionsView(model: model, transfer: transfer, ticket: ticket) - } else { + case .preparing: Text(String(localized: L10n.Transfer.eventPreparing)).foregroundStyle(colors.foregroundLighter) + case .unavailable: + Text(String(localized: transfer.status == .failed ? L10n.Transfer.eventFailed : L10n.Transfer.eventStopped)) + .foregroundStyle(colors.foregroundLighter) } } } - private func qrCard(ticket: String) -> some View { + private func qrCard(image: Image?) -> some View { ZStack { - if let qr = QRCode.generate(from: ticket) { - qr.interpolation(.none).resizable().scaledToFit().padding(14) + if let image { + image.interpolation(.none).resizable().scaledToFit().padding(14) } else { - ProgressView() + VStack(spacing: 10) { + Image(systemName: "qrcode") + .font(.system(size: 36, weight: .medium)) + Text(LocalizedStringKey("transfer_qr_unavailable")) + .font(VniType.bodySmall) + .multilineTextAlignment(.center) + } + .foregroundStyle(.black.opacity(0.72)) + .padding(22) } } .frame(width: 268, height: 268) @@ -303,6 +319,26 @@ struct TransferSharePanel: View { } } +enum TransferInvitationPresentation: Equatable { + case preparing + case ready(String) + case unavailable +} + +extension Transfer { + var invitationPresentation: TransferInvitationPresentation { + switch status { + case .importing: + return .preparing + case .sharing: + guard let ticket, !ticket.isEmpty else { return .preparing } + return .ready(ticket) + case .receiving, .done, .failed, .cancelled, .stopped: + return .unavailable + } + } +} + // MARK: - QR generation (CoreImage) enum QRCode { @@ -359,6 +395,7 @@ extension ReceiverDeliveryStatus { case .refused: return L10n.Transfer.receiverRefused case .expired: return L10n.Transfer.receiverExpired case .completed: return L10n.Transfer.receiverCompleted + case .failed: return L10n.Transfer.receiverFailed case .unknown: return L10n.Transfer.receiverUnknown } } @@ -366,7 +403,7 @@ extension ReceiverDeliveryStatus { func statusColor(_ colors: VniDropColors) -> Color { switch self { case .completed: return colors.brandDefault - case .refused, .expired: return colors.destructiveDefault + case .refused, .expired, .failed: return colors.destructiveDefault default: return colors.foregroundLighter } } diff --git a/apple/VniDrop/Features/Settings/SettingsModel.swift b/apple/VniDrop/Features/Settings/SettingsModel.swift index af29633..308a363 100644 --- a/apple/VniDrop/Features/Settings/SettingsModel.swift +++ b/apple/VniDrop/Features/Settings/SettingsModel.swift @@ -7,6 +7,7 @@ enum SettingsSection: Hashable { case preferences case appearance case notifications + case network case storage case about case bugReport @@ -17,6 +18,7 @@ enum SettingsSection: Hashable { case .preferences: return L10n.Preferences.title case .appearance: return L10n.Appearance.title case .notifications: return L10n.Notifications.title + case .network: return L10n.Settings.networkTitle case .storage: return L10n.Storage.title case .about: return L10n.About.title case .bugReport: return L10n.About.bugReport @@ -43,6 +45,14 @@ struct SettingsState: Equatable { var themeMode: ThemeMode = .system var notificationPermission: NotificationPermission = .notDetermined var diagnosticsEnabled = false + var relayMode: RelayPreferenceMode = .automatic + var relayURLs: [String] = [] + var relayValidationError: RelayConfigurationValidationError? + var relayConfigurationIsDirty = false + var isApplyingRelayConfiguration = false + var hasActiveNetworkWork = false + var endpointId: String? + var relayApplyErrorKey: String? var deviceInfo: DeviceInfo? var appVersion = "" var isLoadingDeviceInfo = false @@ -67,6 +77,13 @@ struct SettingsState: Equatable { && lhs.themeMode == rhs.themeMode && lhs.notificationPermission == rhs.notificationPermission && lhs.diagnosticsEnabled == rhs.diagnosticsEnabled && lhs.appVersion == rhs.appVersion + && lhs.relayMode == rhs.relayMode && lhs.relayURLs == rhs.relayURLs + && lhs.relayValidationError == rhs.relayValidationError + && lhs.relayConfigurationIsDirty == rhs.relayConfigurationIsDirty + && lhs.isApplyingRelayConfiguration == rhs.isApplyingRelayConfiguration + && lhs.hasActiveNetworkWork == rhs.hasActiveNetworkWork + && lhs.endpointId == rhs.endpointId + && lhs.relayApplyErrorKey == rhs.relayApplyErrorKey && lhs.isLoadingDeviceInfo == rhs.isLoadingDeviceInfo && lhs.bugWhatHappened == rhs.bugWhatHappened && lhs.bugExpected == rhs.bugExpected && lhs.bugSteps == rhs.bugSteps && lhs.bugContact == rhs.bugContact @@ -98,6 +115,7 @@ final class SettingsModel: ObservableObject { private var usernamePersistTask: Task? private var hasLocalUsernameDraft = false + private var hasRelayConfigurationDraft = false private var cancellables = Set() init( @@ -134,10 +152,29 @@ final class SettingsModel: ObservableObject { self.state.receiveFolder = folder self.state.themeMode = prefs.themeMode self.state.diagnosticsEnabled = prefs.diagnosticsEnabled + if !self.hasRelayConfigurationDraft { + self.state.relayMode = prefs.relayConfiguration.mode + self.state.relayURLs = prefs.relayConfiguration.relayURLs + self.state.relayConfigurationIsDirty = false + } if folder != previousFolder { Task { await self.validateFolder(folder) } } } .store(in: &cancellables) + repository.statePublisher + .sink { [weak self] coreState in + guard let self else { return } + let hasActiveWork = (coreState.status?.activeTransfers ?? 0) > 0 + || (coreState.status?.activeShares ?? 0) > 0 + || coreState.transfers.contains(where: { $0.status.isActiveTransfer }) + self.state.hasActiveNetworkWork = hasActiveWork + self.state.endpointId = coreState.status?.endpointId + if !hasActiveWork && self.state.relayApplyErrorKey == "relay_apply_active_transfers" { + self.state.relayApplyErrorKey = nil + } + } + .store(in: &cancellables) + refreshNotificationPermission() loadDeviceInfo() } @@ -204,6 +241,119 @@ final class SettingsModel: ObservableObject { } } + // MARK: - Network + + func setRelayMode(_ mode: RelayPreferenceMode) { + hasRelayConfigurationDraft = true + state.relayMode = mode + if mode.usesCustomRelayURLs && state.relayURLs.isEmpty { state.relayURLs = [""] } + updateRelayConfigurationDraft() + } + + func setRelayURL(_ value: String, at index: Int) { + guard state.relayURLs.indices.contains(index) else { return } + hasRelayConfigurationDraft = true + state.relayURLs[index] = value + updateRelayConfigurationDraft() + } + + func addRelayURL() { + guard state.relayURLs.count < RelayConfigurationValidator.maximumRelayCount else { return } + hasRelayConfigurationDraft = true + state.relayURLs.append("") + updateRelayConfigurationDraft() + } + + func removeRelayURL(at index: Int) { + guard state.relayURLs.indices.contains(index) else { return } + hasRelayConfigurationDraft = true + state.relayURLs.remove(at: index) + if state.relayURLs.isEmpty { state.relayURLs = [""] } + updateRelayConfigurationDraft() + } + + func applyRelayConfiguration() { + guard !state.isApplyingRelayConfiguration, state.relayConfigurationIsDirty else { return } + + let configuration: RelayConfiguration + do { + configuration = try RelayConfigurationValidator.validate( + mode: state.relayMode, + relayURLs: state.relayURLs, + retainedRelayURLs: preferences.preferences.relayConfiguration.relayURLs + ) + } catch let error as RelayConfigurationValidationError { + state.relayValidationError = error + state.relayApplyErrorKey = nil + return + } catch { + return + } + + let coreState = repository.state + let hasActiveWork = (coreState.status?.activeTransfers ?? 0) > 0 + || (coreState.status?.activeShares ?? 0) > 0 + || coreState.transfers.contains(where: { $0.status.isActiveTransfer }) + guard !hasActiveWork else { + state.hasActiveNetworkWork = true + state.relayApplyErrorKey = "relay_apply_active_transfers" + messages.show(UiMessage(text: .resource("relay_apply_active_transfers"), tone: .warning)) + return + } + + let previousConfiguration = preferences.preferences.relayConfiguration + state.relayValidationError = nil + state.relayApplyErrorKey = nil + state.isApplyingRelayConfiguration = true + Task { + let applyResult = await repository.initialize( + appDataDir: environment.defaultCoreDataDir, + networkConfiguration: configuration + ) + switch applyResult { + case .success: + hasRelayConfigurationDraft = false + preferences.setRelayConfiguration(configuration) + state.isApplyingRelayConfiguration = false + state.relayConfigurationIsDirty = false + messages.show(UiMessage(text: .resource("relay_settings_applied"), tone: .success)) + case .failure(let error): + if let lifecycleError = error as? CoreNetworkLifecycleError { + state.isApplyingRelayConfiguration = false + switch lifecycleError { + case .activeNetworkWork: + state.hasActiveNetworkWork = true + state.relayApplyErrorKey = "relay_apply_active_transfers" + case .transitionInProgress: + state.relayApplyErrorKey = "relay_apply_failed" + } + return + } + let rollbackResult = await repository.initialize( + appDataDir: environment.defaultCoreDataDir, + networkConfiguration: previousConfiguration + ) + state.isApplyingRelayConfiguration = false + if case .success = rollbackResult { + state.relayApplyErrorKey = "relay_apply_failed" + messages.show(UiMessage(text: .resource("relay_apply_failed"), tone: .error)) + } else { + state.relayApplyErrorKey = "relay_restore_failed" + messages.show(UiMessage(text: .resource("relay_restore_failed"), tone: .error)) + } + } + } + } + + private func updateRelayConfigurationDraft() { + state.relayValidationError = nil + state.relayApplyErrorKey = nil + let saved = preferences.preferences.relayConfiguration + let draftURLs = state.relayMode.usesCustomRelayURLs ? state.relayURLs : saved.relayURLs + state.relayConfigurationIsDirty = saved != RelayConfiguration(mode: state.relayMode, relayURLs: draftURLs) + hasRelayConfigurationDraft = state.relayConfigurationIsDirty + } + func setBugWhatHappened(_ value: String) { state.bugWhatHappened = value } func setBugExpected(_ value: String) { state.bugExpected = value } func setBugSteps(_ value: String) { state.bugSteps = value } diff --git a/apple/VniDrop/Features/Settings/SettingsScreen.swift b/apple/VniDrop/Features/Settings/SettingsScreen.swift index ae0723f..2fa7346 100644 --- a/apple/VniDrop/Features/Settings/SettingsScreen.swift +++ b/apple/VniDrop/Features/Settings/SettingsScreen.swift @@ -39,6 +39,17 @@ struct SettingsScreen: View { NavigationLink(value: SettingsSection.storage) { SettingsRow(icon: .internaldrive, title: String(localized: L10n.Storage.title), value: nil) } + } + Section(String(localized: L10n.Settings.advancedTitle)) { + NavigationLink(value: SettingsSection.network) { + SettingsRow( + icon: .network, + title: String(localized: L10n.Settings.networkTitle), + value: relayModeLabel(model.state.relayMode) + ) + } + } + Section { NavigationLink(value: SettingsSection.about) { SettingsRow(icon: .infoCircle, title: String(localized: L10n.About.title), value: nil) } @@ -100,6 +111,8 @@ private struct SettingsSectionContent: View { AppearanceSettings(model: model) case .notifications: NotificationSettings(model: model) + case .network: + NetworkSettings(model: model) case .storage: StorageSettings(model: model) case .about: @@ -110,6 +123,24 @@ private struct SettingsSectionContent: View { } } +func relayModeLabel(_ mode: RelayPreferenceMode) -> String { + switch mode { + case .automatic: return String(localized: "relay_mode_automatic") + case .strictCustom: return String(localized: "relay_mode_custom") + case .customWithDirectFallback: return String(localized: "relay_mode_custom_direct_fallback") + case .localOnly: return String(localized: "relay_mode_local_only") + } +} + +func relayModeDescriptionKey(_ mode: RelayPreferenceMode) -> String { + switch mode { + case .automatic: return "relay_mode_automatic_description" + case .strictCustom: return "relay_mode_custom_description" + case .customWithDirectFallback: return "relay_mode_custom_direct_fallback_description" + case .localOnly: return "relay_mode_local_only_description" + } +} + struct SettingsRow: View { let icon: SFSymbol let title: String diff --git a/apple/VniDrop/Features/Settings/SettingsSections.swift b/apple/VniDrop/Features/Settings/SettingsSections.swift index 603b632..5a9696d 100644 --- a/apple/VniDrop/Features/Settings/SettingsSections.swift +++ b/apple/VniDrop/Features/Settings/SettingsSections.swift @@ -74,6 +74,175 @@ struct NotificationSettings: View { } } +struct NetworkSettings: View { + @ObservedObject var model: SettingsModel + + var body: some View { + Section { + Picker( + String(localized: "settings_network_title"), + selection: Binding(get: { model.state.relayMode }, set: { model.setRelayMode($0) }) + ) { + ForEach(RelayPreferenceMode.allCases, id: \.self) { mode in + Text(relayModeLabel(mode)).tag(mode) + } + } + .pickerStyle(.inline) + .disabled(model.state.isApplyingRelayConfiguration) + } footer: { + Text(LocalizedStringKey(relayModeDescriptionKey(model.state.relayMode))) + } + + Section { + Label { + Text(LocalizedStringKey("relay_privacy_description")) + .fixedSize(horizontal: false, vertical: true) + } icon: { + Image(systemName: "lock.shield") + } + .foregroundStyle(.secondary) + } + + if let endpointId = model.state.endpointId, !endpointId.isEmpty { + Section { + Text(String(format: String(localized: "approval_endpoint_id"), endpointId)) + .font(.footnote.monospaced()) + .textSelection(.enabled) + } + } + + if model.state.relayMode.usesCustomRelayURLs { + Section { + if model.state.relayMode == .strictCustom { + Label { + Text(LocalizedStringKey("relay_strict_warning")) + .fixedSize(horizontal: false, vertical: true) + } icon: { + Image(systemName: "exclamationmark.shield.fill") + } + .foregroundStyle(.orange) + } + + ForEach(Array(model.state.relayURLs.indices), id: \.self) { index in + VStack(alignment: .leading, spacing: 6) { + HStack { + TextField( + "https://relay.example.com", + text: Binding( + get: { + model.state.relayURLs.indices.contains(index) + ? model.state.relayURLs[index] + : "" + }, + set: { model.setRelayURL($0, at: index) } + ) + ) + #if os(iOS) + .keyboardType(.URL) + .textInputAutocapitalization(.never) + #endif + .autocorrectionDisabled() + .disabled(model.state.isApplyingRelayConfiguration) + + Button(role: .destructive) { + model.removeRelayURL(at: index) + } label: { + Image(systemName: "minus.circle.fill") + } + .buttonStyle(.borderless) + .accessibilityLabel(Text(LocalizedStringKey("relay_remove_url"))) + .disabled(model.state.isApplyingRelayConfiguration) + } + + if let error = model.state.relayValidationError, error.urlIndex == index { + Text(relayValidationMessage(error)) + .font(.caption) + .foregroundStyle(.red) + } + } + } + + Button(action: model.addRelayURL) { + Label(String(localized: "relay_add_url"), systemImage: "plus.circle") + } + .disabled( + model.state.relayURLs.count >= RelayConfigurationValidator.maximumRelayCount + || model.state.isApplyingRelayConfiguration + ) + } header: { + Text(LocalizedStringKey("relay_custom_urls_label")) + } footer: { + Text(LocalizedStringKey("relay_custom_urls_help")) + } + } + + if let error = model.state.relayValidationError, error.urlIndex == nil { + Section { + Label { + Text(relayValidationMessage(error)) + } icon: { + Image(systemName: "exclamationmark.triangle.fill") + } + .foregroundStyle(.red) + } + } + + if model.state.hasActiveNetworkWork || model.state.relayApplyErrorKey != nil { + Section { + Label { + Text(LocalizedStringKey( + model.state.hasActiveNetworkWork + ? "relay_apply_active_transfers" + : model.state.relayApplyErrorKey ?? "relay_apply_failed" + )) + } icon: { + Image(systemName: "exclamationmark.triangle.fill") + } + .foregroundStyle(.red) + } + } + + Section { + Button(action: model.applyRelayConfiguration) { + HStack { + Text(LocalizedStringKey( + model.state.isApplyingRelayConfiguration ? "relay_applying" : "relay_apply" + )) + if model.state.isApplyingRelayConfiguration { + Spacer() + ProgressView() + } + } + } + .disabled( + !model.state.relayConfigurationIsDirty + || model.state.isApplyingRelayConfiguration + || model.state.hasActiveNetworkWork + ) + } footer: { + Text(LocalizedStringKey("relay_apply_restart_description")) + } + } +} + +private func relayValidationMessage(_ error: RelayConfigurationValidationError) -> String { + switch error { + case .missingURL: + return String(localized: "relay_validation_missing_url") + case .tooManyURLs: + return String( + format: String(localized: "relay_validation_too_many_urls"), + RelayConfigurationValidator.maximumRelayCount + ) + case .httpsRequired(let index): + return String(format: String(localized: "relay_validation_https_required"), index + 1) + case .invalidURL(let index): + return String(format: String(localized: "relay_validation_invalid_url"), index + 1) + case .duplicateURL(let index): + return String(format: String(localized: "relay_validation_duplicate_url"), index + 1) + } +} + struct StorageSettings: View { @ObservedObject var model: SettingsModel @State private var showDeleteConfirmation = false diff --git a/crates/vnidrop/CORE_FLOW.md b/crates/vnidrop/CORE_FLOW.md index 6fa08e9..f0d1fa4 100644 --- a/crates/vnidrop/CORE_FLOW.md +++ b/crates/vnidrop/CORE_FLOW.md @@ -91,6 +91,11 @@ or temporary tag. Receive downloads keep a temporary tag through export and beco reclaimable after publication. Restart reconciliation repairs active-share tags, removes orphan share tags, and never restores a stopped share. +The explicit transfer-cache action is available only when no transfer or share is +active. It shuts the core down cleanly, removes the app-owned blob store, and then +restarts the core with the same identity and network configuration. Deleting all +transfer records invokes the same cleanup after live shares have been stopped. + ## Resource Limits `CoreLimits` controls source count, collection files and bytes, path and ticket diff --git a/crates/vnidrop/Cargo.toml b/crates/vnidrop/Cargo.toml index 9df0499..cfa2f4d 100644 --- a/crates/vnidrop/Cargo.toml +++ b/crates/vnidrop/Cargo.toml @@ -16,7 +16,7 @@ blake3 = "1.8.3" data-encoding = "2.11.0" futures = "0.3" futures-lite = "2.6.1" -iroh = "1.0.0" +iroh = "1.0.3" iroh-blobs = "0.103.0" irpc = "0.17.0" irpc-iroh = "0.17.0" @@ -36,4 +36,5 @@ uuid = { version = "1.23.3", features = ["v4", "serde"] } walkdir = "2.5.0" [dev-dependencies] +iroh-relay = { version = "1.0.3", features = ["server"] } tempfile = "3.27.0" diff --git a/crates/vnidrop/src/api.rs b/crates/vnidrop/src/api.rs index e3b3c68..e387075 100644 --- a/crates/vnidrop/src/api.rs +++ b/crates/vnidrop/src/api.rs @@ -1,9 +1,175 @@ use anyhow::Context; +use iroh::RelayUrl; use iroh_blobs::Hash; use serde::{Deserialize, Serialize}; +use std::{collections::BTreeSet, net::IpAddr, path::PathBuf, str::FromStr}; +use crate::error::VnidropError; use crate::util::{non_empty, now_ms}; +pub(crate) const MAX_CUSTOM_RELAYS: usize = 8; +pub(crate) const MAX_RELAY_URL_BYTES: usize = 2_048; + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, uniffi::Enum)] +pub enum CoreRelayMode { + Automatic, + StrictCustom, + CustomWithDirectFallback, + LocalOnly, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, uniffi::Record)] +pub struct CoreNetworkConfig { + pub mode: CoreRelayMode, + pub relay_urls: Vec, +} + +impl Default for CoreNetworkConfig { + fn default() -> Self { + Self { + mode: CoreRelayMode::Automatic, + relay_urls: Vec::new(), + } + } +} + +impl CoreNetworkConfig { + pub(crate) fn validated_relay_urls(&self) -> anyhow::Result> { + match self.mode { + CoreRelayMode::Automatic | CoreRelayMode::LocalOnly => { + if !self.relay_urls.is_empty() { + anyhow::bail!( + "{} relay mode must not include custom relay URLs", + match self.mode { + CoreRelayMode::Automatic => "automatic", + CoreRelayMode::LocalOnly => "local-only", + CoreRelayMode::StrictCustom + | CoreRelayMode::CustomWithDirectFallback => unreachable!(), + } + ); + } + Ok(Vec::new()) + } + CoreRelayMode::StrictCustom | CoreRelayMode::CustomWithDirectFallback => { + if self.relay_urls.is_empty() { + anyhow::bail!("custom relay mode requires at least one relay URL"); + } + if self.relay_urls.len() > MAX_CUSTOM_RELAYS { + anyhow::bail!( + "custom relay mode supports at most {MAX_CUSTOM_RELAYS} relay URLs" + ); + } + + let mut seen = BTreeSet::new(); + let mut validated = Vec::with_capacity(self.relay_urls.len()); + for (index, value) in self.relay_urls.iter().enumerate() { + if value.is_empty() + || value + .chars() + .any(|character| character.is_whitespace() || character.is_control()) + { + anyhow::bail!( + "relay URL must be non-empty and contain no whitespace or control characters" + ); + } + if value.len() > MAX_RELAY_URL_BYTES { + anyhow::bail!( + "relay URL is {} bytes, limit is {MAX_RELAY_URL_BYTES}", + value.len() + ); + } + let url = RelayUrl::from_str(value) + .with_context(|| format!("invalid relay URL at position {}", index + 1))?; + let secure = url.scheme() == "https"; + let loopback_http = url.scheme() == "http" + && url.host_str().is_some_and(|host| { + host.eq_ignore_ascii_case("localhost") + || host + .trim_start_matches('[') + .trim_end_matches(']') + .parse::() + .is_ok_and(|address| address.is_loopback()) + }); + if !secure && !loopback_http { + anyhow::bail!( + "relay URL must use HTTPS; HTTP is allowed only for loopback development relays" + ); + } + if url.host_str().is_none() { + anyhow::bail!("relay URL must include a host"); + } + if url.port() == Some(0) { + anyhow::bail!("relay URL port must be between 1 and 65535"); + } + if value.contains('@') || !url.username().is_empty() || url.password().is_some() + { + anyhow::bail!("relay URL must not contain credentials"); + } + if url.query().is_some() || url.fragment().is_some() { + anyhow::bail!("relay URL must not contain a query or fragment"); + } + if url.path() != "/" { + anyhow::bail!("relay URL must not contain a path"); + } + if !seen.insert(url.clone()) { + anyhow::bail!("custom relay URLs must not contain duplicates"); + } + validated.push(url); + } + Ok(validated) + } + } + } +} + +#[uniffi::export] +pub fn default_core_network_config() -> CoreNetworkConfig { + CoreNetworkConfig::default() +} + +/// Removes the blob store after its owning core has shut down. +/// +/// Callers must verify that no transfer or share is active before shutdown. +#[uniffi::export] +pub fn clear_inactive_transfer_cache(app_data_dir: String) -> Result { + let result = (|| -> anyhow::Result { + let app_data_dir = PathBuf::from(app_data_dir); + anyhow::ensure!( + app_data_dir.is_absolute(), + "app data directory must be absolute" + ); + anyhow::ensure!( + app_data_dir.file_name().is_some(), + "app data directory must not be a filesystem root" + ); + let blobs = app_data_dir.join("blobs"); + let metadata = match std::fs::symlink_metadata(&blobs) { + Ok(metadata) => metadata, + Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(0), + Err(error) => return Err(error.into()), + }; + anyhow::ensure!( + metadata.is_dir() && !metadata.file_type().is_symlink(), + "blob store path is not a directory" + ); + let bytes = walkdir::WalkDir::new(&blobs) + .follow_links(false) + .into_iter() + .try_fold(0u64, |total, entry| { + let entry = entry?; + let metadata = entry.metadata()?; + Ok::<_, walkdir::Error>(if metadata.is_file() { + total.saturating_add(metadata.len()) + } else { + total + }) + })?; + std::fs::remove_dir_all(blobs)?; + Ok(bytes) + })(); + result.map_err(VnidropError::filesystem) +} + #[derive(Debug, Clone, Serialize, Deserialize, uniffi::Record)] pub struct CoreLimits { pub max_sources: u64, diff --git a/crates/vnidrop/src/approval.rs b/crates/vnidrop/src/approval.rs index 23075f9..c0f273d 100644 --- a/crates/vnidrop/src/approval.rs +++ b/crates/vnidrop/src/approval.rs @@ -8,7 +8,10 @@ use uuid::Uuid; use crate::{ access_policy::{AccessPolicy, APPROVAL_SESSION_TTL_MS}, event_hub::EventHub, - handshake::{DeliveryReceipt, DeliveryReceiptResponse, HandshakeResponse, RequestTransfer}, + handshake::{ + DeliveryFailureReceipt, DeliveryReceipt, DeliveryReceiptResponse, HandshakeResponse, + RequestTransfer, + }, repository::{ReceiverRequestInsert, Repository}, transfer_state::ReceiverRequestStatus, util::now_ms, @@ -70,6 +73,46 @@ impl ApprovalService { } } + pub(crate) async fn fail_delivery( + &self, + remote_endpoint_id: String, + receipt: DeliveryFailureReceipt, + ) -> DeliveryReceiptResponse { + let token_hash = receipt_token_hash(&receipt.token); + match self + .repository + .fail_receiver_delivery( + &receipt.request_id, + receipt.transfer_id, + &remote_endpoint_id, + &token_hash, + &receipt.reason, + ) + .await + { + Ok(()) => { + self.event_hub.emit_transfer( + receipt.transfer_id, + "send", + "delivery", + "receiver-failed", + json!({ + "request_id": receipt.request_id, + "remote_endpoint_id": remote_endpoint_id, + "reason": receipt.reason, + }), + ); + DeliveryReceiptResponse::Recorded + } + Err(error) => { + tracing::warn!(%error, "rejected receiver delivery failure"); + DeliveryReceiptResponse::Rejected { + reason: "invalid-receipt".to_string(), + } + } + } + } + pub(crate) fn new( repository: Repository, event_hub: Arc, diff --git a/crates/vnidrop/src/handshake.rs b/crates/vnidrop/src/handshake.rs index 385a220..3cc7638 100644 --- a/crates/vnidrop/src/handshake.rs +++ b/crates/vnidrop/src/handshake.rs @@ -72,6 +72,14 @@ impl ProtocolHandler for HandshakeService { .await; let _ = tx.send(response).await; } + HandshakeMessage::ReportDeliveryFailure(message) => { + let WithChannels { inner, tx, .. } = message; + let response = self + .approval + .fail_delivery(remote_endpoint_id.clone(), inner) + .await; + let _ = tx.send(response).await; + } } } @@ -109,6 +117,13 @@ impl HandshakeClient { ) -> Result { self.inner.rpc(receipt).await } + + pub(crate) async fn report_delivery_failure( + &self, + receipt: DeliveryFailureReceipt, + ) -> Result { + self.inner.rpc(receipt).await + } } #[derive(Debug, Clone, Serialize, Deserialize)] @@ -140,6 +155,14 @@ pub(crate) struct DeliveryReceipt { pub(crate) token: String, } +#[derive(Debug, Clone, Serialize, Deserialize)] +pub(crate) struct DeliveryFailureReceipt { + pub(crate) request_id: String, + pub(crate) transfer_id: u64, + pub(crate) token: String, + pub(crate) reason: String, +} + #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] pub(crate) enum DeliveryReceiptResponse { Recorded, @@ -153,4 +176,6 @@ enum HandshakeProtocol { RequestTransfer(RequestTransfer), #[rpc(tx=oneshot::Sender)] ReportDelivery(DeliveryReceipt), + #[rpc(tx=oneshot::Sender)] + ReportDeliveryFailure(DeliveryFailureReceipt), } diff --git a/crates/vnidrop/src/lib.rs b/crates/vnidrop/src/lib.rs index f958b5b..1ed14d8 100644 --- a/crates/vnidrop/src/lib.rs +++ b/crates/vnidrop/src/lib.rs @@ -14,7 +14,8 @@ mod transfer_state; mod util; pub use api::{ - default_core_limits, CoreEvent, CoreEventSink, CoreLimits, CoreStorageUsage, PublishedOutput, + clear_inactive_transfer_cache, default_core_limits, default_core_network_config, CoreEvent, + CoreEventSink, CoreLimits, CoreNetworkConfig, CoreRelayMode, CoreStorageUsage, PublishedOutput, ReceiveOutputSink, ReceiveOutputSinkV2, ReceivedArtifact, ReceivedLocatorKind, ReceiverRequest, RuntimeStatus, ShareMetadataInput, ShareResult, ShareSource, SourceKind, StoredTransfer, TicketInspection, TransferAccessMode, TransferMetadata, diff --git a/crates/vnidrop/src/repository.rs b/crates/vnidrop/src/repository.rs index 9715789..b913e8e 100644 --- a/crates/vnidrop/src/repository.rs +++ b/crates/vnidrop/src/repository.rs @@ -20,7 +20,7 @@ use crate::{ util::now_ms, }; -const SCHEMA_VERSION: i64 = 6; +const SCHEMA_VERSION: i64 = 7; #[derive(Debug, Clone)] pub(crate) struct Repository { @@ -49,6 +49,7 @@ pub(crate) struct PersistedShare { pub(crate) transfer_id: u64, pub(crate) local_id: String, pub(crate) content_hash: String, + pub(crate) ticket: Option, pub(crate) access_mode: String, } @@ -85,6 +86,7 @@ pub(crate) struct PendingDeliveryReceipt { pub(crate) request_id: String, pub(crate) sender_transfer_id: u64, pub(crate) token: String, + pub(crate) failure_reason: Option, } pub(crate) struct PendingDeliveryReceiptInsert<'a> { @@ -93,6 +95,7 @@ pub(crate) struct PendingDeliveryReceiptInsert<'a> { pub(crate) request_id: &'a str, pub(crate) sender_transfer_id: u64, pub(crate) token: &'a str, + pub(crate) failure_reason: Option<&'a str>, } impl Repository { @@ -293,12 +296,24 @@ impl Repository { sender_blob_ticket TEXT NOT NULL, sender_transfer_id INTEGER NOT NULL, token TEXT NOT NULL, + failure_reason TEXT, created_at INTEGER NOT NULL ); "#, ) .execute(&self.pool) .await?; + let receipt_columns = sqlx::query("PRAGMA table_info(pending_delivery_receipts)") + .fetch_all(&self.pool) + .await?; + if !receipt_columns + .iter() + .any(|row| row.get::(1) == "failure_reason") + { + sqlx::query("ALTER TABLE pending_delivery_receipts ADD COLUMN failure_reason TEXT") + .execute(&self.pool) + .await?; + } sqlx::query(&format!("PRAGMA user_version = {SCHEMA_VERSION}")) .execute(&self.pool) @@ -560,13 +575,14 @@ impl Repository { r#" INSERT INTO pending_delivery_receipts ( request_id, local_transfer_id, sender_blob_ticket, - sender_transfer_id, token, created_at - ) VALUES (?1, ?2, ?3, ?4, ?5, ?6) + sender_transfer_id, token, failure_reason, created_at + ) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7) ON CONFLICT(request_id) DO UPDATE SET local_transfer_id = excluded.local_transfer_id, sender_blob_ticket = excluded.sender_blob_ticket, sender_transfer_id = excluded.sender_transfer_id, - token = excluded.token + token = excluded.token, + failure_reason = excluded.failure_reason "#, ) .bind(receipt.request_id) @@ -574,6 +590,7 @@ impl Repository { .bind(receipt.sender_blob_ticket) .bind(to_db_id(receipt.sender_transfer_id)?) .bind(receipt.token) + .bind(receipt.failure_reason) .bind(now_ms()) .execute(&mut *transaction) .await?; @@ -581,13 +598,46 @@ impl Repository { Ok(()) } + pub(crate) async fn queue_failed_delivery_receipt( + &self, + receipt: PendingDeliveryReceiptInsert<'_>, + ) -> Result<()> { + let Some(reason) = receipt.failure_reason else { + anyhow::bail!("failed delivery receipt requires a reason"); + }; + sqlx::query( + r#" + INSERT INTO pending_delivery_receipts ( + request_id, local_transfer_id, sender_blob_ticket, + sender_transfer_id, token, failure_reason, created_at + ) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7) + ON CONFLICT(request_id) DO UPDATE SET + local_transfer_id = excluded.local_transfer_id, + sender_blob_ticket = excluded.sender_blob_ticket, + sender_transfer_id = excluded.sender_transfer_id, + token = excluded.token, + failure_reason = excluded.failure_reason + "#, + ) + .bind(receipt.request_id) + .bind(to_db_id(receipt.local_transfer_id)?) + .bind(receipt.sender_blob_ticket) + .bind(to_db_id(receipt.sender_transfer_id)?) + .bind(receipt.token) + .bind(reason) + .bind(now_ms()) + .execute(&self.pool) + .await?; + Ok(()) + } + pub(crate) async fn list_pending_delivery_receipts( &self, ) -> Result> { let rows = sqlx::query( r#" SELECT local_transfer_id, sender_blob_ticket, request_id, - sender_transfer_id, token + sender_transfer_id, token, failure_reason FROM pending_delivery_receipts ORDER BY created_at ASC "#, @@ -602,6 +652,7 @@ impl Repository { request_id: row.get("request_id"), sender_transfer_id: row.get::("sender_transfer_id") as u64, token: row.get("token"), + failure_reason: row.get("failure_reason"), }) .collect()) } @@ -709,7 +760,7 @@ impl Repository { pub(crate) async fn list_active_shares(&self) -> Result> { let rows = sqlx::query( r#" - SELECT transfer_id, local_id, content_hash, access_mode + SELECT transfer_id, local_id, content_hash, ticket, access_mode FROM transfers WHERE direction = 'send' AND status = 'sharing' @@ -724,7 +775,8 @@ impl Repository { transfer_id: row.get::(0) as u64, local_id: row.get::(1), content_hash: row.get::(2), - access_mode: row.get::(3), + ticket: row.get::, _>(3), + access_mode: row.get::(4), }) .collect()) } @@ -881,6 +933,56 @@ impl Repository { } } + pub(crate) async fn fail_receiver_delivery( + &self, + id: &str, + transfer_id: u64, + remote_endpoint_id: &str, + token_hash: &str, + reason: &str, + ) -> Result<()> { + let result = sqlx::query( + r#" + UPDATE receiver_requests + SET status = 'failed', reason = ?1 + WHERE id = ?2 AND transfer_id = ?3 AND remote_endpoint_id = ?4 AND receipt_token_hash = ?5 + AND status = 'accepted' + "#, + ) + .bind(reason) + .bind(id) + .bind(to_db_id(transfer_id)?) + .bind(remote_endpoint_id) + .bind(token_hash) + .execute(&self.pool) + .await?; + if result.rows_affected() == 1 { + return Ok(()); + } + let already_recorded = sqlx::query( + r#" + SELECT EXISTS( + SELECT 1 FROM receiver_requests + WHERE id = ?1 AND transfer_id = ?2 AND remote_endpoint_id = ?3 + AND receipt_token_hash = ?4 AND status = 'failed' + ) + "#, + ) + .bind(id) + .bind(to_db_id(transfer_id)?) + .bind(remote_endpoint_id) + .bind(token_hash) + .fetch_one(&self.pool) + .await? + .get::(0) + != 0; + if already_recorded { + Ok(()) + } else { + anyhow::bail!("delivery failure did not match an accepted receiver request") + } + } + pub(crate) async fn expire_pending_receiver_requests(&self, reason: &str) -> Result { let result = sqlx::query( r#" diff --git a/crates/vnidrop/src/runtime/delivery.rs b/crates/vnidrop/src/runtime/delivery.rs index 9a85c40..8938e2c 100644 --- a/crates/vnidrop/src/runtime/delivery.rs +++ b/crates/vnidrop/src/runtime/delivery.rs @@ -1,12 +1,14 @@ -use std::{str::FromStr, sync::Arc, time::Duration}; +use std::{sync::Arc, time::Duration}; -use iroh_blobs::ticket::BlobTicket; use serde_json::json; -use super::CoreInner; +use super::{filter_peer_addr_for_relay_mode, CoreInner}; use crate::{ - handshake::{DeliveryReceipt, DeliveryReceiptResponse, HandshakeService}, + handshake::{ + DeliveryFailureReceipt, DeliveryReceipt, DeliveryReceiptResponse, HandshakeService, + }, repository::PendingDeliveryReceipt, + ticket::parse_persisted_sender_address, }; const DELIVERY_RECEIPT_TIMEOUT: Duration = Duration::from_secs(5); @@ -60,8 +62,8 @@ impl CoreInner { } async fn deliver_pending_receipt(&self, pending: PendingDeliveryReceipt) { - let blob_ticket = match BlobTicket::from_str(&pending.sender_blob_ticket) { - Ok(ticket) => ticket, + let sender_addr = match parse_persisted_sender_address(&pending.sender_blob_ticket) { + Ok(addr) => addr, Err(error) => { tracing::warn!(%error, request_id = %pending.request_id, "discarded invalid pending delivery receipt"); let _ = self @@ -78,14 +80,47 @@ impl CoreInner { return; } }; - let client = HandshakeService::client(self.endpoint.clone(), blob_ticket.addr().clone()); - let receipt = DeliveryReceipt { - request_id: pending.request_id.clone(), - transfer_id: pending.sender_transfer_id, - token: pending.token, + let sender_addr = match filter_peer_addr_for_relay_mode( + &sender_addr, + self.relay_mode, + &self.custom_relay_urls, + ) { + Ok(addr) => addr, + Err(error) => { + self.emit_transfer( + pending.local_transfer_id, + "receive", + "delivery", + "receipt-failed", + json!({ "reason": error.to_string() }), + ); + return; + } }; - match tokio::time::timeout(DELIVERY_RECEIPT_TIMEOUT, client.report_delivery(receipt)).await - { + let client = HandshakeService::client(self.endpoint.clone(), sender_addr); + let request_id = pending.request_id.clone(); + let response = tokio::time::timeout(DELIVERY_RECEIPT_TIMEOUT, async { + if let Some(reason) = pending.failure_reason { + client + .report_delivery_failure(DeliveryFailureReceipt { + request_id, + transfer_id: pending.sender_transfer_id, + token: pending.token, + reason, + }) + .await + } else { + client + .report_delivery(DeliveryReceipt { + request_id, + transfer_id: pending.sender_transfer_id, + token: pending.token, + }) + .await + } + }) + .await; + match response { Ok(Ok(DeliveryReceiptResponse::Recorded)) => { if let Err(error) = self .repository diff --git a/crates/vnidrop/src/runtime/facade.rs b/crates/vnidrop/src/runtime/facade.rs index 26b1a1d..ea8f30a 100644 --- a/crates/vnidrop/src/runtime/facade.rs +++ b/crates/vnidrop/src/runtime/facade.rs @@ -6,9 +6,10 @@ use serde_json::json; use super::CoreInner; use crate::{ api::{ - CoreEvent, CoreEventSink, CoreLimits, CoreStorageUsage, ReceiveOutputSink, - ReceiveOutputSinkV2, ReceivedArtifact, ReceiverRequest, RuntimeStatus, ShareMetadataInput, - ShareResult, ShareSource, StoredTransfer, TicketInspection, TransferAccessMode, + CoreEvent, CoreEventSink, CoreLimits, CoreNetworkConfig, CoreStorageUsage, + ReceiveOutputSink, ReceiveOutputSinkV2, ReceivedArtifact, ReceiverRequest, RuntimeStatus, + ShareMetadataInput, ShareResult, ShareSource, StoredTransfer, TicketInspection, + TransferAccessMode, }, error::VnidropError, filesystem::platform_path, @@ -42,7 +43,26 @@ impl VnidropCore { app_data_dir: String, event_sink: Arc, ) -> Result, VnidropError> { - Self::initialize_with_limits(app_data_dir, event_sink, CoreLimits::default()) + Self::initialize_with_limits_and_network_config( + app_data_dir, + event_sink, + CoreLimits::default(), + CoreNetworkConfig::default(), + ) + } + + #[uniffi::constructor] + pub fn initialize_with_network_config( + app_data_dir: String, + event_sink: Arc, + network_config: CoreNetworkConfig, + ) -> Result, VnidropError> { + Self::initialize_with_limits_and_network_config( + app_data_dir, + event_sink, + CoreLimits::default(), + network_config, + ) } #[uniffi::constructor] @@ -50,15 +70,39 @@ impl VnidropCore { app_data_dir: String, event_sink: Arc, limits: CoreLimits, + ) -> Result, VnidropError> { + Self::initialize_with_limits_and_network_config( + app_data_dir, + event_sink, + limits, + CoreNetworkConfig::default(), + ) + } + + #[uniffi::constructor] + pub fn initialize_with_limits_and_network_config( + app_data_dir: String, + event_sink: Arc, + limits: CoreLimits, + network_config: CoreNetworkConfig, ) -> Result, VnidropError> { limits.validate().map_err(VnidropError::initialization)?; + let relay_urls = network_config + .validated_relay_urls() + .map_err(VnidropError::initialization)?; let runtime = tokio::runtime::Builder::new_multi_thread() .enable_all() .thread_name("vnidrop") .build()?; let app_data_dir = PathBuf::from(app_data_dir); let inner = runtime - .block_on(CoreInner::start(app_data_dir, event_sink, limits)) + .block_on(CoreInner::start( + app_data_dir, + event_sink, + limits, + network_config.mode, + relay_urls, + )) .map_err(VnidropError::initialization)?; Ok(Arc::new(Self { runtime, inner })) } diff --git a/crates/vnidrop/src/runtime/mod.rs b/crates/vnidrop/src/runtime/mod.rs index 55e3201..cb13930 100644 --- a/crates/vnidrop/src/runtime/mod.rs +++ b/crates/vnidrop/src/runtime/mod.rs @@ -16,6 +16,8 @@ mod share; mod storage; pub use facade::VnidropCore; +#[cfg(test)] +pub(crate) use provider::{consume_request_updates, RequestStreamOutcome}; use std::{ collections::{HashMap, HashSet}, @@ -27,7 +29,10 @@ use std::{ use anyhow::Result; use futures_lite::StreamExt as _; -use iroh::{endpoint::presets, protocol::Router, Endpoint}; +use iroh::{ + endpoint::presets, protocol::Router, tls::CaTlsConfig, Endpoint, EndpointAddr, RelayConfig, + RelayMap, RelayMode, RelayUrl, +}; use iroh_blobs::{ format::collection::Collection, provider::events::{EventMask, EventSender}, @@ -45,16 +50,36 @@ use tokio::{ use crate::{ access_policy::{mode_from_storage, AccessPolicy}, - api::{CoreEvent, CoreEventSink, CoreLimits}, + api::{CoreEvent, CoreEventSink, CoreLimits, CoreRelayMode}, approval::ApprovalService, event_hub::EventHub, handshake::HandshakeService, logging::init_logging, repository::Repository, secret::load_or_create_secret, + ticket::ticket_matches_relay_profile, transfer_state::{TransferDirection, TransferStatus}, }; +const RELAY_CONNECT_TIMEOUT: Duration = Duration::from_secs(10); + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum RelayStatus { + Disabled, + Connected, + Unreachable, +} + +impl RelayStatus { + fn as_str(self) -> &'static str { + match self { + Self::Disabled => "disabled", + Self::Connected => "connected", + Self::Unreachable => "unreachable", + } + } +} + /// Owns the Iroh endpoint, blob store, transfer history, and byte streaming. /// Kotlin owns app lifecycle and platform file picking. pub(super) struct CoreInner { @@ -66,6 +91,8 @@ pub(super) struct CoreInner { pub(super) event_hub: Arc, pub(super) approval: ApprovalService, pub(super) limits: CoreLimits, + pub(super) relay_mode: CoreRelayMode, + pub(super) custom_relay_urls: Vec, pub(super) transfer_slots: Semaphore, pub(super) access_policy: Arc, /// Sync mutex so cancel can remove + signal without awaiting (and without @@ -93,6 +120,8 @@ impl CoreInner { app_data_dir: PathBuf, event_sink: Arc, limits: CoreLimits, + relay_mode: CoreRelayMode, + relay_urls: Vec, ) -> Result> { tokio::fs::create_dir_all(&app_data_dir).await?; init_logging(&app_data_dir)?; @@ -105,11 +134,48 @@ impl CoreInner { add_protected: None, }); let store = FsStore::load_with_opts(store_root.join("blobs.db"), store_options).await?; - let endpoint = Endpoint::builder(presets::N0) - .secret_key(secret_key) - .bind() - .await?; - endpoint.online().await; + let endpoint = match relay_mode { + CoreRelayMode::Automatic => { + Endpoint::builder(presets::N0) + .secret_key(secret_key) + .bind() + .await? + } + CoreRelayMode::StrictCustom | CoreRelayMode::CustomWithDirectFallback => { + let relay_map = RelayMap::from_iter(relay_urls.iter().cloned().map(|url| { + // Loopback HTTP is a development escape hatch. Without TLS the + // relay cannot serve Iroh's QUIC address-discovery endpoint. + if url.scheme() == "http" { + RelayConfig::new(url, None) + } else { + RelayConfig::from(url) + } + })); + // Minimal leaves address lookup empty, so strict custom mode + // cannot silently publish or resolve addresses through N0. + Endpoint::builder(presets::Minimal) + .relay_mode(RelayMode::Custom(relay_map)) + .ca_tls_config(CaTlsConfig::embedded()) + .secret_key(secret_key) + .bind() + .await? + } + CoreRelayMode::LocalOnly => { + Endpoint::builder(presets::Minimal) + .relay_mode(RelayMode::Disabled) + .secret_key(secret_key) + .bind() + .await? + } + }; + let relay_status = + match wait_for_relay(&endpoint, relay_mode, &relay_urls, RELAY_CONNECT_TIMEOUT).await { + Ok(status) => status, + Err(error) => { + endpoint.close().await; + return Err(error); + } + }; // Provider events are where the sender sees remote readers. The core // uses them for send progress and for the current approval gate. @@ -122,6 +188,14 @@ impl CoreInner { limits.event_queue_capacity as usize, limits.max_events, )); + event_hub.emit_endpoint( + "network", + "relay-status", + json!({ + "mode": relay_mode_label(relay_mode), + "status": relay_status.as_str(), + }), + ); for recovered in recovered_transfers { event_hub.emit_transfer( recovered.transfer_id, @@ -189,6 +263,27 @@ impl CoreInner { ); continue; }; + let relay_profile_matches = share.ticket.as_deref().is_some_and(|ticket| { + ticket_matches_relay_profile(ticket, &limits, relay_mode, &relay_urls) + .unwrap_or(false) + }); + if !relay_profile_matches { + repository + .transition_transfer_status( + transfer_id, + TransferStatus::Sharing, + TransferStatus::Stopped, + ) + .await?; + event_hub.emit_transfer( + transfer_id, + TransferDirection::Send.as_str(), + "recovery", + "share-stopped-network-profile-changed", + json!({ "reason": "saved ticket does not match the active relay profile" }), + ); + continue; + } let tag_name = share_tag_name(&share.local_id); store .tags() @@ -239,6 +334,8 @@ impl CoreInner { repository, event_hub, approval, + relay_mode, + custom_relay_urls: relay_urls, transfer_slots: Semaphore::new(limits.max_concurrent_transfers as usize), limits, access_policy, @@ -309,6 +406,88 @@ impl CoreInner { } } +pub(crate) fn filter_peer_addr_for_relay_mode( + addr: &EndpointAddr, + relay_mode: CoreRelayMode, + custom_relay_urls: &[RelayUrl], +) -> Result { + match relay_mode { + CoreRelayMode::Automatic => Ok(addr.clone()), + CoreRelayMode::StrictCustom | CoreRelayMode::CustomWithDirectFallback => { + let mut filtered = EndpointAddr::new(addr.id); + for ip_addr in addr.ip_addrs().copied() { + filtered = filtered.with_ip_addr(ip_addr); + } + for relay_url in addr + .relay_urls() + .filter(|relay_url| custom_relay_urls.contains(relay_url)) + .cloned() + { + filtered = filtered.with_relay_url(relay_url); + } + if filtered.is_empty() { + anyhow::bail!( + "invitation has no direct address or relay allowed by strict custom relay mode" + ); + } + Ok(filtered) + } + CoreRelayMode::LocalOnly => { + let mut filtered = EndpointAddr::new(addr.id); + for ip_addr in addr.ip_addrs().copied() { + filtered = filtered.with_ip_addr(ip_addr); + } + if filtered.is_empty() { + anyhow::bail!("invitation has no direct address allowed by local-only mode"); + } + Ok(filtered) + } + } +} + +pub(crate) async fn wait_for_relay( + endpoint: &Endpoint, + relay_mode: CoreRelayMode, + relay_urls: &[RelayUrl], + timeout: Duration, +) -> Result { + if relay_mode == CoreRelayMode::LocalOnly { + return Ok(RelayStatus::Disabled); + } + if tokio::time::timeout(timeout, endpoint.online()) + .await + .is_err() + { + match relay_mode { + CoreRelayMode::StrictCustom => { + let configured_relays = relay_urls + .iter() + .map(ToString::to_string) + .collect::>() + .join(", "); + anyhow::bail!( + "timed out after {} seconds while connecting to custom relays [{configured_relays}]; verify the URLs, TLS certificates, network access, and relay availability", + timeout.as_secs_f32(), + ); + } + CoreRelayMode::Automatic | CoreRelayMode::CustomWithDirectFallback => { + return Ok(RelayStatus::Unreachable); + } + CoreRelayMode::LocalOnly => unreachable!(), + } + } + Ok(RelayStatus::Connected) +} + +fn relay_mode_label(relay_mode: CoreRelayMode) -> &'static str { + match relay_mode { + CoreRelayMode::Automatic => "automatic", + CoreRelayMode::StrictCustom => "strict-custom", + CoreRelayMode::CustomWithDirectFallback => "custom-with-direct-fallback", + CoreRelayMode::LocalOnly => "local-only", + } +} + pub(super) fn share_tag_name(local_id: &str) -> String { format!("vnidrop/share/{local_id}") } diff --git a/crates/vnidrop/src/runtime/provider.rs b/crates/vnidrop/src/runtime/provider.rs index d6263fa..9447626 100644 --- a/crates/vnidrop/src/runtime/provider.rs +++ b/crates/vnidrop/src/runtime/provider.rs @@ -10,6 +10,31 @@ use tokio::sync::mpsc; use super::CoreInner; use crate::access_policy::AccessDecision; +#[derive(Debug, PartialEq, Eq)] +pub(crate) enum RequestStreamOutcome { + TerminalUpdateReceived, + Aborted, +} + +pub(crate) async fn consume_request_updates( + mut rx: irpc::channel::mpsc::Receiver, + mut handle_update: impl FnMut(RequestUpdate), +) -> RequestStreamOutcome { + let mut terminal_update_received = false; + while let Ok(Some(update)) = rx.recv().await { + terminal_update_received |= matches!( + update, + RequestUpdate::Completed(_) | RequestUpdate::Aborted(_) + ); + handle_update(update); + } + if terminal_update_received { + RequestStreamOutcome::TerminalUpdateReceived + } else { + RequestStreamOutcome::Aborted + } +} + impl CoreInner { pub(super) async fn spawn_provider_event_task( self: &Arc, @@ -302,7 +327,7 @@ impl CoreInner { transfer_id: u64, connection_id: u64, request_id: u64, - mut rx: irpc::channel::mpsc::Receiver, + rx: irpc::channel::mpsc::Receiver, ) { // Request update tasks are tied to individual provider streams. Router // shutdown closes those streams; only the long-lived provider receiver @@ -318,35 +343,35 @@ impl CoreInner { .cloned(); let core = self.clone(); tokio::spawn(async move { - while let Ok(Some(update)) = rx.recv().await { - match update { - RequestUpdate::Started(started) => core.emit_transfer( - transfer_id, - "send", - "transfer", - "started", - json!({ - "connection_id": connection_id, - "request_id": request_id, - "endpoint_id": endpoint_id, - "hash": started.hash.to_string(), - "size": started.size, - "index": started.index, - }), - ), - RequestUpdate::Progress(progress) => core.emit_transfer( - transfer_id, - "send", - "transfer", - "progress", - json!({ - "connection_id": connection_id, - "request_id": request_id, - "endpoint_id": endpoint_id, - "end_offset": progress.end_offset, - }), - ), - RequestUpdate::Completed(_) => core.emit_transfer( + let outcome = consume_request_updates(rx, |update| match update { + RequestUpdate::Started(started) => core.emit_transfer( + transfer_id, + "send", + "transfer", + "started", + json!({ + "connection_id": connection_id, + "request_id": request_id, + "endpoint_id": endpoint_id, + "hash": started.hash.to_string(), + "size": started.size, + "index": started.index, + }), + ), + RequestUpdate::Progress(progress) => core.emit_transfer( + transfer_id, + "send", + "transfer", + "progress", + json!({ + "connection_id": connection_id, + "request_id": request_id, + "endpoint_id": endpoint_id, + "end_offset": progress.end_offset, + }), + ), + RequestUpdate::Completed(_) => { + core.emit_transfer( transfer_id, "send", "transfer", @@ -356,8 +381,10 @@ impl CoreInner { "request_id": request_id, "endpoint_id": endpoint_id, }), - ), - RequestUpdate::Aborted(_) => core.emit_transfer( + ); + } + RequestUpdate::Aborted(_) => { + core.emit_transfer( transfer_id, "send", "transfer", @@ -367,8 +394,22 @@ impl CoreInner { "request_id": request_id, "endpoint_id": endpoint_id, }), - ), + ); } + }) + .await; + if outcome == RequestStreamOutcome::Aborted { + core.emit_transfer( + transfer_id, + "send", + "transfer", + "aborted", + json!({ + "connection_id": connection_id, + "request_id": request_id, + "endpoint_id": endpoint_id, + }), + ); } }); } diff --git a/crates/vnidrop/src/runtime/receive.rs b/crates/vnidrop/src/runtime/receive.rs index b72223f..d4b5671 100644 --- a/crates/vnidrop/src/runtime/receive.rs +++ b/crates/vnidrop/src/runtime/receive.rs @@ -1,7 +1,7 @@ use std::{ io, path::{Path, PathBuf}, - sync::Arc, + sync::{Arc, Mutex}, }; use anyhow::{Context, Result}; @@ -9,12 +9,12 @@ use bytes::Bytes; use futures_lite::StreamExt as _; use iroh_blobs::{ api::proto::ExportRangesItem, api::remote::GetProgressItem, format::collection::Collection, - get::request::get_hash_seq_and_sizes, Hash, + get::request::get_hash_seq_and_sizes, ticket::BlobTicket, Hash, }; use serde_json::json; use tokio::sync::oneshot; -use super::{ActiveTransfer, CoreInner}; +use super::{filter_peer_addr_for_relay_mode, ActiveTransfer, CoreInner}; use crate::{ access_policy::mode_to_storage, api::{ @@ -28,7 +28,9 @@ use crate::{ }, handshake::{DeliveryReceipt, HandshakeResponse, HandshakeService}, repository::{PendingDeliveryReceiptInsert, ReceivedArtifactInsert, TransferUpsert}, - ticket::{parse_transfer_ticket_with_limits, ParsedTransferTicket}, + ticket::{ + encode_persisted_sender_address, parse_transfer_ticket_with_limits, ParsedTransferTicket, + }, transfer_state::{TransferDirection, TransferStatus}, }; @@ -192,7 +194,7 @@ impl CoreInner { .await .context("transfer limiter is closed") .map_err(VnidropError::internal)?; - let parsed = match parse_transfer_ticket_with_limits(&ticket, &self.limits) + let mut parsed = match parse_transfer_ticket_with_limits(&ticket, &self.limits) .context("failed to parse transfer ticket") { Ok(parsed) => parsed, @@ -205,10 +207,25 @@ impl CoreInner { return Err(error); } }; + let sender_addr = filter_peer_addr_for_relay_mode( + parsed.blob_ticket.addr(), + self.relay_mode, + &self.custom_relay_urls, + ) + .map_err(VnidropError::network)?; + parsed.blob_ticket = BlobTicket::new( + sender_addr, + parsed.blob_ticket.hash(), + parsed.blob_ticket.format(), + ); let transfer_id = parsed.metadata.transfer_id; self.persist_receive_start(transfer_id, &parsed, receiver_name.as_deref()) .await .map_err(VnidropError::repository)?; + let persisted_sender_address = + encode_persisted_sender_address(parsed.blob_ticket.addr()) + .context("failed to encode sender address for delivery receipt")?; + let delivery_receipt = Arc::new(Mutex::new(None)); // Cancellation is cooperative: it stops our receive future and marks // local state while lower-level Iroh work unwinds naturally. let (shutdown_tx, mut shutdown_rx) = oneshot::channel(); @@ -224,7 +241,14 @@ impl CoreInner { ); let (result, cancelled) = tokio::select! { - result = self.receive_inner(transfer_id, parsed, target, receiver_name) => { + result = self.receive_inner( + transfer_id, + parsed, + target, + receiver_name, + persisted_sender_address.clone(), + delivery_receipt.clone(), + ) => { (result.map_err(VnidropError::transfer), false) }, _ = &mut shutdown_rx => (Err(VnidropError::cancelled("transfer cancelled")), true), @@ -254,6 +278,34 @@ impl CoreInner { ) .await; } + let receipt = delivery_receipt.lock().expect("delivery_receipt").take(); + if let Some(receipt) = receipt { + let reason = if cancelled { "cancelled" } else { error.code() }; + match self + .repository + .queue_failed_delivery_receipt(PendingDeliveryReceiptInsert { + local_transfer_id: transfer_id, + sender_blob_ticket: &persisted_sender_address, + request_id: &receipt.request_id, + sender_transfer_id: receipt.transfer_id, + token: &receipt.token, + failure_reason: Some(reason), + }) + .await + { + Ok(()) => self.delivery_receipt_notify.notify_one(), + Err(queue_error) => { + tracing::warn!(%queue_error, "failed to queue delivery failure receipt"); + self.emit_transfer( + transfer_id, + "receive", + "delivery", + "receipt-failed", + json!({ "reason": queue_error.to_string() }), + ); + } + } + } } result.map_err(anyhow::Error::new) } @@ -264,6 +316,8 @@ impl CoreInner { parsed: ParsedTransferTicket, target: ReceiveTarget, receiver_name: Option, + persisted_sender_address: String, + pending_delivery_receipt: Arc>>, ) -> Result<()> { if let ReceiveTarget::Directory(output_dir) = &target { tokio::fs::create_dir_all(output_dir) @@ -271,7 +325,6 @@ impl CoreInner { .map_err(VnidropError::filesystem)?; } let sender_addr = parsed.blob_ticket.addr().clone(); - let sender_blob_ticket = parsed.blob_ticket.to_string(); self.emit_transfer(transfer_id, "receive", "network", "connecting", json!({})); // Every VniDrop ticket carries metadata and must complete the handshake. @@ -283,6 +336,9 @@ impl CoreInner { receiver_name.as_deref(), ) .await?; + *pending_delivery_receipt + .lock() + .expect("pending_delivery_receipt") = Some(delivery_receipt.clone()); let connection = self .endpoint .connect(sender_addr.clone(), iroh_blobs::ALPN) @@ -355,13 +411,18 @@ impl CoreInner { self.repository .complete_receive_with_pending_receipt(PendingDeliveryReceiptInsert { local_transfer_id: transfer_id, - sender_blob_ticket: &sender_blob_ticket, + sender_blob_ticket: &persisted_sender_address, request_id: &delivery_receipt.request_id, sender_transfer_id: delivery_receipt.transfer_id, token: &delivery_receipt.token, + failure_reason: None, }) .await .map_err(VnidropError::repository)?; + pending_delivery_receipt + .lock() + .expect("pending_delivery_receipt") + .take(); drop(download_tag); self.emit_transfer(transfer_id, "receive", "lifecycle", "done", json!({})); self.delivery_receipt_notify.notify_one(); diff --git a/crates/vnidrop/src/runtime/share.rs b/crates/vnidrop/src/runtime/share.rs index 1b2c211..849bba3 100644 --- a/crates/vnidrop/src/runtime/share.rs +++ b/crates/vnidrop/src/runtime/share.rs @@ -149,9 +149,13 @@ impl CoreInner { import.file_count, import.total_size, ); - let ticket = VnidropTicket::new(blob_ticket, ticket_metadata) - .encode() - .context("failed to encode VniDrop transfer ticket")?; + let ticket = VnidropTicket::new_with_relay_urls( + blob_ticket, + ticket_metadata, + &self.custom_relay_urls, + ) + .encode() + .context("failed to encode VniDrop transfer ticket")?; let content_hash = import.root_hash.to_string(); let local_id = self .repository diff --git a/crates/vnidrop/src/tests.rs b/crates/vnidrop/src/tests.rs index 859a73d..75e095a 100644 --- a/crates/vnidrop/src/tests.rs +++ b/crates/vnidrop/src/tests.rs @@ -8,6 +8,8 @@ mod filesystem_tests; mod handshake_tests; #[path = "tests/limits.rs"] mod limits_tests; +#[path = "tests/network_config.rs"] +mod network_config_tests; #[path = "tests/repository.rs"] mod repository_tests; #[path = "tests/runtime.rs"] diff --git a/crates/vnidrop/src/tests/network_config.rs b/crates/vnidrop/src/tests/network_config.rs new file mode 100644 index 0000000..363ccf2 --- /dev/null +++ b/crates/vnidrop/src/tests/network_config.rs @@ -0,0 +1,232 @@ +use std::time::{Duration, Instant}; + +use iroh::{endpoint::presets, Endpoint, EndpointAddr, RelayMode, RelayUrl, SecretKey}; + +use crate::{ + api::{ + default_core_network_config, CoreNetworkConfig, CoreRelayMode, MAX_CUSTOM_RELAYS, + MAX_RELAY_URL_BYTES, + }, + runtime::{filter_peer_addr_for_relay_mode, wait_for_relay, RelayStatus}, +}; + +#[test] +fn default_network_config_uses_automatic_relays() { + assert_eq!( + default_core_network_config(), + CoreNetworkConfig { + mode: CoreRelayMode::Automatic, + relay_urls: Vec::new(), + } + ); + default_core_network_config() + .validated_relay_urls() + .unwrap(); +} + +#[test] +fn relay_mode_and_url_list_must_be_consistent() { + let automatic_with_url = CoreNetworkConfig { + mode: CoreRelayMode::Automatic, + relay_urls: vec!["https://relay.example.com".to_string()], + }; + assert!(automatic_with_url.validated_relay_urls().is_err()); + + for mode in [ + CoreRelayMode::StrictCustom, + CoreRelayMode::CustomWithDirectFallback, + ] { + let custom_without_url = CoreNetworkConfig { + mode, + relay_urls: Vec::new(), + }; + assert!(custom_without_url.validated_relay_urls().is_err()); + } + + let local_only_with_url = CoreNetworkConfig { + mode: CoreRelayMode::LocalOnly, + relay_urls: vec!["https://relay.example.com".to_string()], + }; + assert!(local_only_with_url.validated_relay_urls().is_err()); +} + +#[test] +fn custom_relay_urls_allow_https_and_loopback_http() { + let config = CoreNetworkConfig { + mode: CoreRelayMode::StrictCustom, + relay_urls: vec![ + "https://relay.example.com".to_string(), + "http://localhost:3340".to_string(), + "http://127.0.0.1:3341".to_string(), + "http://[::1]:3342".to_string(), + ], + }; + + assert_eq!(config.validated_relay_urls().unwrap().len(), 4); +} + +#[test] +fn custom_relay_urls_reject_unsafe_or_ambiguous_values() { + for value in [ + "http://relay.example.com", + "https://user:password@relay.example.com", + "https://relay.example.com/path", + "https://relay.example.com?token=secret", + "https://relay.example.com#fragment", + "https://relay.example.com:0", + "https://relay.exa\tmple.com", + "https://@relay.example.com", + " https://relay.example.com", + ] { + let config = CoreNetworkConfig { + mode: CoreRelayMode::StrictCustom, + relay_urls: vec![value.to_string()], + }; + assert!( + config.validated_relay_urls().is_err(), + "{value} should be rejected" + ); + } +} + +#[test] +fn custom_relay_urls_are_bounded_and_unique_after_normalization() { + let duplicates = CoreNetworkConfig { + mode: CoreRelayMode::StrictCustom, + relay_urls: vec![ + "https://relay.example.com".to_string(), + "https://relay.example.com/".to_string(), + ], + }; + assert!(duplicates.validated_relay_urls().is_err()); + + let too_many = CoreNetworkConfig { + mode: CoreRelayMode::StrictCustom, + relay_urls: (0..=MAX_CUSTOM_RELAYS) + .map(|index| format!("https://relay-{index}.example.com")) + .collect(), + }; + assert!(too_many.validated_relay_urls().is_err()); + + let too_long = CoreNetworkConfig { + mode: CoreRelayMode::StrictCustom, + relay_urls: vec![format!( + "https://{}.example.com", + "a".repeat(MAX_RELAY_URL_BYTES) + )], + }; + assert!(too_long.validated_relay_urls().is_err()); +} + +#[test] +fn strict_custom_mode_filters_peer_relays_but_retains_direct_addresses() { + let allowed: RelayUrl = "https://allowed.relay.example.com".parse().unwrap(); + let disallowed: RelayUrl = "https://disallowed.relay.example.com".parse().unwrap(); + let direct = "192.0.2.1:4433".parse().unwrap(); + let addr = EndpointAddr::new(SecretKey::generate().public()) + .with_relay_url(allowed.clone()) + .with_relay_url(disallowed.clone()) + .with_ip_addr(direct); + + let filtered = filter_peer_addr_for_relay_mode( + &addr, + CoreRelayMode::StrictCustom, + std::slice::from_ref(&allowed), + ) + .unwrap(); + assert_eq!( + filtered.relay_urls().cloned().collect::>(), + vec![allowed.clone()] + ); + assert_eq!( + filtered.ip_addrs().copied().collect::>(), + vec![direct] + ); + assert_eq!( + filter_peer_addr_for_relay_mode(&addr, CoreRelayMode::Automatic, &[]).unwrap(), + addr + ); + + let disallowed_only = + EndpointAddr::new(SecretKey::generate().public()).with_relay_url(disallowed); + assert!(filter_peer_addr_for_relay_mode( + &disallowed_only, + CoreRelayMode::StrictCustom, + std::slice::from_ref(&allowed), + ) + .is_err()); + + let fallback_filtered = filter_peer_addr_for_relay_mode( + &addr, + CoreRelayMode::CustomWithDirectFallback, + std::slice::from_ref(&allowed), + ) + .unwrap(); + assert_eq!(fallback_filtered, filtered); + + let local_only = filter_peer_addr_for_relay_mode(&addr, CoreRelayMode::LocalOnly, &[]).unwrap(); + assert_eq!(local_only.relay_urls().count(), 0); + assert_eq!( + local_only.ip_addrs().copied().collect::>(), + vec![direct] + ); + assert!( + filter_peer_addr_for_relay_mode(&disallowed_only, CoreRelayMode::LocalOnly, &[]).is_err() + ); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn relay_wait_enforces_only_strict_custom_mode() { + let relay_url: RelayUrl = "http://127.0.0.1:9".parse().unwrap(); + let endpoint = Endpoint::builder(presets::Minimal) + .relay_mode(RelayMode::custom([relay_url.clone()])) + .bind() + .await + .unwrap(); + let started = Instant::now(); + + let error = wait_for_relay( + &endpoint, + CoreRelayMode::StrictCustom, + std::slice::from_ref(&relay_url), + Duration::from_millis(50), + ) + .await + .unwrap_err(); + + assert!(started.elapsed() < Duration::from_secs(1)); + assert!(error.to_string().contains(relay_url.as_str())); + assert!(error.to_string().contains("verify the URLs")); + + let automatic_status = wait_for_relay( + &endpoint, + CoreRelayMode::Automatic, + &[], + Duration::from_millis(50), + ) + .await + .unwrap(); + assert!(started.elapsed() < Duration::from_secs(1)); + assert_eq!(automatic_status, RelayStatus::Unreachable); + + let fallback_status = wait_for_relay( + &endpoint, + CoreRelayMode::CustomWithDirectFallback, + std::slice::from_ref(&relay_url), + Duration::from_millis(50), + ) + .await + .unwrap(); + assert_eq!(fallback_status, RelayStatus::Unreachable); + + let local_only_status = wait_for_relay( + &endpoint, + CoreRelayMode::LocalOnly, + &[], + Duration::from_millis(50), + ) + .await + .unwrap(); + assert_eq!(local_only_status, RelayStatus::Disabled); + endpoint.close().await; +} diff --git a/crates/vnidrop/src/tests/repository.rs b/crates/vnidrop/src/tests/repository.rs index 8bade55..dfe9222 100644 --- a/crates/vnidrop/src/tests/repository.rs +++ b/crates/vnidrop/src/tests/repository.rs @@ -66,7 +66,7 @@ async fn received_artifacts_survive_history_deletion() { async fn persists_transfers_and_events_across_reopen() { let temp = tempfile::tempdir().unwrap(); let repository = Repository::open(temp.path()).await.unwrap(); - assert_eq!(repository.schema_version().await.unwrap(), 6); + assert_eq!(repository.schema_version().await.unwrap(), 7); repository .insert_transfer(transfer( 7, @@ -80,6 +80,7 @@ async fn persists_transfers_and_events_across_reopen() { assert_eq!(shares.len(), 1); assert_eq!(shares[0].transfer_id, 7); assert_eq!(shares[0].content_hash, "hash"); + assert_eq!(shares[0].ticket.as_deref(), Some("ticket")); assert_eq!(shares[0].access_mode, "approval_required"); repository @@ -134,6 +135,7 @@ async fn receive_completion_persists_delivery_receipt_until_recorded() { request_id: "request-93", sender_transfer_id: 39, token: "receipt-token", + failure_reason: None, }) .await .unwrap(); @@ -220,6 +222,68 @@ async fn receiver_request_can_only_be_resolved_once() { assert!(requests[0].completed_at.is_some()); } +#[tokio::test] +async fn authenticated_delivery_failure_marks_accepted_receiver_failed() { + let temp = tempfile::tempdir().unwrap(); + let repository = Repository::open(temp.path()).await.unwrap(); + repository + .insert_receiver_request(ReceiverRequestInsert { + id: "request-failed", + transfer_id: 78, + remote_endpoint_id: "node-a", + transfer_name: "demo", + receiver_name: Some("receiver"), + receiver_device_name: None, + app_version: "0.1.0", + }) + .await + .unwrap(); + repository + .update_receiver_request_status("request-failed", ReceiverRequestStatus::Accepted, None) + .await + .unwrap(); + repository + .set_receiver_receipt_token("request-failed", "token-hash") + .await + .unwrap(); + + repository + .fail_receiver_delivery( + "request-failed", + 78, + "node-a", + "token-hash", + "destination_exists", + ) + .await + .unwrap(); + repository + .fail_receiver_delivery( + "request-failed", + 78, + "node-a", + "token-hash", + "destination_exists", + ) + .await + .unwrap(); + assert!(repository + .fail_receiver_delivery( + "request-failed", + 78, + "node-b", + "token-hash", + "destination_exists", + ) + .await + .is_err()); + + let requests = repository.list_receiver_requests(78).await.unwrap(); + assert_eq!(requests.len(), 1); + assert_eq!(requests[0].status, "failed"); + assert_eq!(requests[0].reason.as_deref(), Some("destination_exists")); +} + #[tokio::test] async fn startup_expiration_is_idempotent_for_pending_requests() { let temp = tempfile::tempdir().unwrap(); @@ -581,7 +645,7 @@ async fn migrates_schema_v2_identity_without_losing_transfer() { pool.close().await; let repository = Repository::open(temp.path()).await.unwrap(); - assert_eq!(repository.schema_version().await.unwrap(), 6); + assert_eq!(repository.schema_version().await.unwrap(), 7); let stored = repository.list_transfers().await.unwrap().remove(0); assert_eq!(stored.transfer_id, 7); assert_eq!(stored.local_id, "legacy-7-send"); diff --git a/crates/vnidrop/src/tests/runtime.rs b/crates/vnidrop/src/tests/runtime.rs index 8b3ca76..895a448 100644 --- a/crates/vnidrop/src/tests/runtime.rs +++ b/crates/vnidrop/src/tests/runtime.rs @@ -1,9 +1,16 @@ -use std::sync::Arc; +use std::{sync::Arc, time::Duration}; -use iroh_blobs::Hash; +use iroh_blobs::{ + provider::{ + events::{RequestUpdate, TransferCompleted}, + TransferStats, + }, + Hash, +}; use crate::{ repository::{PendingDeliveryReceiptInsert, Repository, TransferUpsert}, + runtime::{consume_request_updates, RequestStreamOutcome}, transfer_state::{TransferDirection, TransferStatus}, CoreEvent, CoreEventSink, VnidropCore, VnidropError, }; @@ -14,6 +21,37 @@ impl CoreEventSink for TestSink { fn on_event(&self, _event: CoreEvent) {} } +#[test] +fn provider_request_stream_distinguishes_success_from_silent_abort() { + let runtime = tokio::runtime::Runtime::new().unwrap(); + runtime.block_on(async { + let (completed_tx, completed_rx) = irpc::channel::mpsc::channel(1); + completed_tx + .send(RequestUpdate::Completed(TransferCompleted { + stats: Box::new(TransferStats { + payload_bytes_sent: 5, + other_bytes_sent: 0, + other_bytes_read: 0, + duration: Duration::ZERO, + }), + })) + .await + .unwrap(); + drop(completed_tx); + assert_eq!( + consume_request_updates(completed_rx, |_| {}).await, + RequestStreamOutcome::TerminalUpdateReceived + ); + + let (aborted_tx, aborted_rx) = irpc::channel::mpsc::channel::(1); + drop(aborted_tx); + assert_eq!( + consume_request_updates(aborted_rx, |_| {}).await, + RequestStreamOutcome::Aborted + ); + }); +} + #[test] fn initializes_and_reports_endpoint() { let temp = tempfile::tempdir().unwrap(); @@ -126,6 +164,7 @@ fn startup_processes_persisted_delivery_receipts() { request_id: "request-94", sender_transfer_id: 49, token: "receipt-token", + failure_reason: None, }) .await .unwrap(); diff --git a/crates/vnidrop/src/tests/ticket.rs b/crates/vnidrop/src/tests/ticket.rs index 47fec19..67d5e90 100644 --- a/crates/vnidrop/src/tests/ticket.rs +++ b/crates/vnidrop/src/tests/ticket.rs @@ -1,11 +1,16 @@ +use std::net::{Ipv4Addr, SocketAddr}; + use data_encoding::BASE64URL_NOPAD; -use iroh::SecretKey; +use iroh::{RelayUrl, SecretKey}; use iroh_blobs::{ticket::BlobTicket, BlobFormat, Hash}; use serde_json::json; use crate::{ - api::{CoreLimits, TransferMetadata}, - ticket::{parse_transfer_ticket, parse_transfer_ticket_with_limits, VnidropTicket}, + api::{CoreLimits, CoreRelayMode, TransferMetadata}, + ticket::{ + encode_persisted_sender_address, parse_persisted_sender_address, parse_transfer_ticket, + parse_transfer_ticket_with_limits, ticket_matches_relay_profile, VnidropTicket, + }, }; fn blob_ticket(hash_byte: u8) -> BlobTicket { @@ -25,7 +30,7 @@ fn metadata_ticket_round_trips() { 3, 2048, ); - let encoded = VnidropTicket::new(blob_ticket.clone(), metadata.clone()) + let encoded = VnidropTicket::new_with_relay_urls(blob_ticket.clone(), metadata.clone(), &[]) .encode() .unwrap(); let parsed = parse_transfer_ticket(&encoded).unwrap(); @@ -38,7 +43,7 @@ fn metadata_ticket_round_trips() { fn metadata_ticket_tolerates_wrapped_whitespace() { let blob_ticket = blob_ticket(9); let metadata = TransferMetadata::new(7, "Wrapped", None, blob_ticket.hash(), 1, 10); - let encoded = VnidropTicket::new(blob_ticket.clone(), metadata) + let encoded = VnidropTicket::new_with_relay_urls(blob_ticket.clone(), metadata, &[]) .encode() .unwrap(); let wrapped = encoded @@ -52,6 +57,147 @@ fn metadata_ticket_tolerates_wrapped_whitespace() { assert_eq!(parsed.blob_ticket.hash(), blob_ticket.hash()); } +#[test] +fn metadata_ticket_restores_backup_relays_without_losing_direct_addresses() { + let secret = SecretKey::generate(); + let primary: RelayUrl = "https://a.relay.example.com".parse().unwrap(); + let backup: RelayUrl = "https://b.relay.example.com".parse().unwrap(); + let direct = SocketAddr::from((Ipv4Addr::LOCALHOST, 49152)); + let addr = iroh::EndpointAddr::new(secret.public()) + .with_relay_url(primary.clone()) + .with_ip_addr(direct); + let blob_ticket = BlobTicket::new(addr, Hash::new([11; 32]), BlobFormat::HashSeq); + let metadata = TransferMetadata::new(11, "Backed up", None, blob_ticket.hash(), 1, 10); + + let encoded = VnidropTicket::new_with_relay_urls( + blob_ticket, + metadata, + &[primary.clone(), backup.clone()], + ) + .encode() + .unwrap(); + let parsed = parse_transfer_ticket(&encoded).unwrap(); + + assert_eq!( + parsed + .blob_ticket + .addr() + .relay_urls() + .cloned() + .collect::>(), + vec![primary, backup] + ); + assert_eq!( + parsed + .blob_ticket + .addr() + .ip_addrs() + .copied() + .collect::>(), + vec![direct] + ); +} + +#[test] +fn saved_ticket_relay_profile_matching_is_mode_aware_and_order_insensitive() { + let relay_a: RelayUrl = "https://a.relay.example.com".parse().unwrap(); + let relay_b: RelayUrl = "https://b.relay.example.com".parse().unwrap(); + let relay_c: RelayUrl = "https://c.relay.example.com".parse().unwrap(); + let blob_ticket = blob_ticket(13); + let metadata = TransferMetadata::new(13, "Relay profile", None, blob_ticket.hash(), 1, 10); + let custom_ticket = VnidropTicket::new_with_relay_urls( + blob_ticket.clone(), + metadata.clone(), + &[relay_a.clone(), relay_b.clone()], + ) + .encode() + .unwrap(); + let automatic_ticket = VnidropTicket::new_with_relay_urls(blob_ticket, metadata, &[]) + .encode() + .unwrap(); + let limits = CoreLimits::default(); + + assert!(ticket_matches_relay_profile( + &custom_ticket, + &limits, + CoreRelayMode::StrictCustom, + &[relay_b.clone(), relay_a.clone()], + ) + .unwrap()); + assert!(ticket_matches_relay_profile( + &custom_ticket, + &limits, + CoreRelayMode::CustomWithDirectFallback, + &[relay_b.clone(), relay_a.clone()], + ) + .unwrap()); + assert!(!ticket_matches_relay_profile( + &custom_ticket, + &limits, + CoreRelayMode::StrictCustom, + &[relay_a.clone(), relay_c], + ) + .unwrap()); + assert!( + !ticket_matches_relay_profile(&custom_ticket, &limits, CoreRelayMode::Automatic, &[],) + .unwrap() + ); + assert!(ticket_matches_relay_profile( + &automatic_ticket, + &limits, + CoreRelayMode::Automatic, + &[], + ) + .unwrap()); + assert!(!ticket_matches_relay_profile( + &automatic_ticket, + &limits, + CoreRelayMode::StrictCustom, + &[relay_a], + ) + .unwrap()); + assert!(ticket_matches_relay_profile( + &automatic_ticket, + &limits, + CoreRelayMode::LocalOnly, + &[], + ) + .unwrap()); + assert!( + !ticket_matches_relay_profile(&custom_ticket, &limits, CoreRelayMode::LocalOnly, &[],) + .unwrap() + ); +} + +#[test] +fn persisted_sender_address_preserves_relays_and_accepts_legacy_blob_ticket() { + let secret = SecretKey::generate(); + let primary: RelayUrl = "https://a.relay.example.com".parse().unwrap(); + let backup: RelayUrl = "https://b.relay.example.com".parse().unwrap(); + let direct = SocketAddr::from((Ipv4Addr::LOCALHOST, 49153)); + let addr = iroh::EndpointAddr::new(secret.public()) + .with_relay_url(primary.clone()) + .with_relay_url(backup) + .with_ip_addr(direct); + + let encoded = encode_persisted_sender_address(&addr).unwrap(); + assert_eq!(parse_persisted_sender_address(&encoded).unwrap(), addr); + + let legacy_addr = iroh::EndpointAddr::new(secret.public()) + .with_relay_url(primary) + .with_ip_addr(direct); + let legacy = BlobTicket::new( + legacy_addr.clone(), + Hash::new([12; 32]), + BlobFormat::HashSeq, + ) + .to_string(); + assert_eq!( + parse_persisted_sender_address(&legacy).unwrap(), + legacy_addr + ); +} + #[test] fn invalid_ticket_is_rejected() { assert!(parse_transfer_ticket("not-a-ticket").is_err()); diff --git a/crates/vnidrop/src/ticket.rs b/crates/vnidrop/src/ticket.rs index 87f4b63..d2f108e 100644 --- a/crates/vnidrop/src/ticket.rs +++ b/crates/vnidrop/src/ticket.rs @@ -1,27 +1,38 @@ -use std::str::FromStr; +use std::{collections::BTreeSet, str::FromStr}; use anyhow::{Context, Result}; use data_encoding::BASE64URL_NOPAD; +use iroh::{EndpointAddr, RelayUrl}; use iroh_blobs::ticket::BlobTicket; use serde::{Deserialize, Serialize}; -use crate::api::{CoreLimits, TransferMetadata}; +use crate::api::{CoreLimits, CoreNetworkConfig, CoreRelayMode, TransferMetadata}; const VNIDROP_TICKET_PREFIX: &str = "vnd1:"; const VNIDROP_TICKET_VERSION: u8 = 1; +const PERSISTED_SENDER_ADDRESS_PREFIX: &str = "vndaddr1:"; #[derive(Debug, Clone, Serialize, Deserialize)] pub(crate) struct VnidropTicket { version: u8, blob_ticket: String, + // BlobTicket's current wire format retains only one relay URL. The outer + // envelope carries backups so new receivers can rebuild the full address. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + relay_urls: Vec, metadata: TransferMetadata, } impl VnidropTicket { - pub(crate) fn new(blob_ticket: BlobTicket, metadata: TransferMetadata) -> Self { + pub(crate) fn new_with_relay_urls( + blob_ticket: BlobTicket, + metadata: TransferMetadata, + relay_urls: &[RelayUrl], + ) -> Self { Self { version: VNIDROP_TICKET_VERSION, blob_ticket: blob_ticket.to_string(), + relay_urls: relay_urls.iter().map(ToString::to_string).collect(), metadata, } } @@ -50,6 +61,35 @@ impl VnidropTicket { pub(crate) struct ParsedTransferTicket { pub(crate) blob_ticket: BlobTicket, pub(crate) metadata: TransferMetadata, + pub(crate) advertised_custom_relay_urls: Vec, +} + +#[derive(Debug, Serialize, Deserialize)] +struct PersistedSenderAddress { + addr: EndpointAddr, +} + +pub(crate) fn encode_persisted_sender_address(addr: &EndpointAddr) -> Result { + let bytes = serde_json::to_vec(&PersistedSenderAddress { addr: addr.clone() })?; + Ok(format!( + "{PERSISTED_SENDER_ADDRESS_PREFIX}{}", + BASE64URL_NOPAD.encode(&bytes) + )) +} + +pub(crate) fn parse_persisted_sender_address(value: &str) -> Result { + if let Some(encoded) = value.strip_prefix(PERSISTED_SENDER_ADDRESS_PREFIX) { + let bytes = BASE64URL_NOPAD + .decode(encoded.as_bytes()) + .context("invalid persisted sender address encoding")?; + let persisted: PersistedSenderAddress = + serde_json::from_slice(&bytes).context("invalid persisted sender address payload")?; + return Ok(persisted.addr); + } + + // Rows created before multi-relay invitations stored a raw BlobTicket. + let legacy = BlobTicket::from_str(value).context("invalid legacy sender BlobTicket")?; + Ok(legacy.addr().clone()) } #[cfg(test)] @@ -93,17 +133,57 @@ pub(crate) fn parse_transfer_ticket_with_limits( Some(ticket.metadata.transfer_name.as_str()), )?; limits.validate_metadata_text("sender name", ticket.metadata.sender_name.as_deref())?; - let blob_ticket = BlobTicket::from_str(&ticket.blob_ticket) + let mut blob_ticket = BlobTicket::from_str(&ticket.blob_ticket) .context("invalid BlobTicket inside VniDrop ticket")?; if ticket.metadata.content_hash != blob_ticket.hash().to_string() { anyhow::bail!("VniDrop ticket metadata hash does not match BlobTicket hash"); } + let advertised_custom_relay_urls = if ticket.relay_urls.is_empty() { + Vec::new() + } else { + CoreNetworkConfig { + mode: CoreRelayMode::StrictCustom, + relay_urls: ticket.relay_urls, + } + .validated_relay_urls() + .context("invalid relay URLs inside VniDrop ticket")? + }; + if !advertised_custom_relay_urls.is_empty() { + let (mut addr, hash, format) = blob_ticket.into_parts(); + for relay_url in advertised_custom_relay_urls.iter().cloned() { + addr = addr.with_relay_url(relay_url); + } + blob_ticket = BlobTicket::new(addr, hash, format); + } Ok(ParsedTransferTicket { blob_ticket, metadata: ticket.metadata, + advertised_custom_relay_urls, }) } +pub(crate) fn ticket_matches_relay_profile( + value: &str, + limits: &CoreLimits, + relay_mode: CoreRelayMode, + custom_relay_urls: &[RelayUrl], +) -> Result { + let parsed = parse_transfer_ticket_with_limits(value, limits)?; + match relay_mode { + CoreRelayMode::Automatic => Ok(parsed.advertised_custom_relay_urls.is_empty()), + CoreRelayMode::StrictCustom | CoreRelayMode::CustomWithDirectFallback => { + let advertised = parsed + .advertised_custom_relay_urls + .into_iter() + .collect::>(); + let configured = custom_relay_urls.iter().cloned().collect::>(); + Ok(advertised == configured) + } + CoreRelayMode::LocalOnly => Ok(parsed.advertised_custom_relay_urls.is_empty() + && parsed.blob_ticket.addr().relay_urls().next().is_none()), + } +} + fn normalize_ticket_input(value: &str) -> String { // Tickets are commonly copied from text views or chat apps that insert line // breaks. Strip whitespace only; other corrupt characters should still be diff --git a/crates/vnidrop/src/transfer_state.rs b/crates/vnidrop/src/transfer_state.rs index 7952671..b13f619 100644 --- a/crates/vnidrop/src/transfer_state.rs +++ b/crates/vnidrop/src/transfer_state.rs @@ -87,6 +87,7 @@ pub(crate) enum ReceiverRequestStatus { Refused, Expired, Completed, + Failed, } impl ReceiverRequestStatus { @@ -97,6 +98,7 @@ impl ReceiverRequestStatus { Self::Refused => "refused", Self::Expired => "expired", Self::Completed => "completed", + Self::Failed => "failed", } } } @@ -111,6 +113,7 @@ impl TryFrom<&str> for ReceiverRequestStatus { "refused" => Ok(Self::Refused), "expired" => Ok(Self::Expired), "completed" => Ok(Self::Completed), + "failed" => Ok(Self::Failed), _ => bail!("unknown receiver request status: {value}"), } } diff --git a/crates/vnidrop/tests/custom_relay.rs b/crates/vnidrop/tests/custom_relay.rs new file mode 100644 index 0000000..b2dae70 --- /dev/null +++ b/crates/vnidrop/tests/custom_relay.rs @@ -0,0 +1,146 @@ +mod support; + +use std::str::FromStr; + +use data_encoding::BASE64URL_NOPAD; +use iroh::{EndpointAddr, RelayUrl}; +use iroh_blobs::ticket::BlobTicket; +use serde_json::Value; +use support::{receive_with_response, share_path, TestNode, TestRelay}; +use vnidrop::{CoreNetworkConfig, CoreRelayMode}; + +fn custom_config(relay_urls: &[&str]) -> CoreNetworkConfig { + CoreNetworkConfig { + mode: CoreRelayMode::StrictCustom, + relay_urls: relay_urls.iter().map(ToString::to_string).collect(), + } +} + +fn local_only_config() -> CoreNetworkConfig { + CoreNetworkConfig { + mode: CoreRelayMode::LocalOnly, + relay_urls: Vec::new(), + } +} + +fn read_blob_ticket(ticket: &str) -> (Value, BlobTicket) { + let encoded = ticket.strip_prefix("vnd1:").unwrap(); + let payload = BASE64URL_NOPAD.decode(encoded.as_bytes()).unwrap(); + let value: Value = serde_json::from_slice(&payload).unwrap(); + let blob_ticket = BlobTicket::from_str(value["blob_ticket"].as_str().unwrap()).unwrap(); + let (mut addr, hash, format) = blob_ticket.into_parts(); + if let Some(relay_urls) = value["relay_urls"].as_array() { + for relay_url in relay_urls { + addr = addr.with_relay_url(relay_url.as_str().unwrap().parse().unwrap()); + } + } + let blob_ticket = BlobTicket::new(addr, hash, format); + (value, blob_ticket) +} + +#[test] +fn local_only_mode_advertises_direct_addresses_and_transfers_on_lan() { + let sender = TestNode::with_network_config(local_only_config()); + let receiver = TestNode::with_network_config(local_only_config()); + let source_dir = tempfile::tempdir().unwrap(); + let output_dir = tempfile::tempdir().unwrap(); + let source_path = source_dir.path().join("local-only.txt"); + std::fs::write(&source_path, b"direct on the local network").unwrap(); + + let share = share_path(&sender.core, &source_path, 402, "local-only.txt", false); + let (ticket_value, blob_ticket) = read_blob_ticket(&share.ticket); + assert!(ticket_value.get("relay_urls").is_none()); + assert_eq!(blob_ticket.addr().relay_urls().count(), 0); + assert!(!sender.core.status().addr.contains("iroh.link")); + + receive_with_response( + &sender.core, + share.transfer_id, + receiver.core.arc(), + share.ticket, + output_dir.path(), + true, + ) + .unwrap(); + + assert_eq!( + std::fs::read(output_dir.path().join("local-only.txt")).unwrap(), + b"direct on the local network" + ); +} + +fn with_relay_only_address(ticket: &str, relay_url: &str) -> String { + let (mut value, blob_ticket) = read_blob_ticket(ticket); + let relay_url: RelayUrl = relay_url.parse().unwrap(); + let relay_only_addr = EndpointAddr::new(blob_ticket.addr().id).with_relay_url(relay_url); + let relay_only_ticket = + BlobTicket::new(relay_only_addr, blob_ticket.hash(), blob_ticket.format()); + value["blob_ticket"] = Value::String(relay_only_ticket.to_string()); + let payload = serde_json::to_vec(&value).unwrap(); + format!("vnd1:{}", BASE64URL_NOPAD.encode(&payload)) +} + +#[test] +fn strict_custom_relay_is_advertised_and_transfers_without_direct_ticket_addresses() { + let relay = TestRelay::start(); + let backup_relay = "http://127.0.0.1:9"; + let relay_urls = [relay.url.as_str(), backup_relay]; + let sender = TestNode::with_network_config(custom_config(&relay_urls)); + let receiver = TestNode::with_network_config(custom_config(&[relay.url.as_str()])); + let source_dir = tempfile::tempdir().unwrap(); + let output_dir = tempfile::tempdir().unwrap(); + let source_path = source_dir.path().join("custom-relay.txt"); + std::fs::write(&source_path, b"through the custom relay").unwrap(); + + let share = share_path(&sender.core, &source_path, 401, "custom-relay.txt", false); + let (ticket_value, blob_ticket) = read_blob_ticket(&share.ticket); + let advertised_relays: Vec<_> = blob_ticket + .addr() + .relay_urls() + .map(ToString::to_string) + .collect(); + let configured_relay = RelayUrl::from_str(&relay.url).unwrap().to_string(); + let configured_backup = RelayUrl::from_str(backup_relay).unwrap().to_string(); + let envelope_relays = ticket_value["relay_urls"] + .as_array() + .unwrap() + .iter() + .map(|value| value.as_str().unwrap().to_string()) + .collect::>(); + assert_eq!( + envelope_relays, + vec![configured_relay.clone(), configured_backup.clone()] + ); + let mut configured_relays = vec![configured_relay.clone(), configured_backup]; + configured_relays.sort(); + assert_eq!(advertised_relays, configured_relays.clone()); + assert!(!advertised_relays.iter().any(|url| url.contains("n0"))); + assert!(!sender.core.status().addr.contains("iroh.link")); + + let relay_only_ticket = with_relay_only_address(&share.ticket, &relay.url); + let (_, relay_only_blob_ticket) = read_blob_ticket(&relay_only_ticket); + assert_eq!(relay_only_blob_ticket.addr().ip_addrs().count(), 0); + assert_eq!( + relay_only_blob_ticket + .addr() + .relay_urls() + .map(ToString::to_string) + .collect::>(), + configured_relays + ); + + receive_with_response( + &sender.core, + share.transfer_id, + receiver.core.arc(), + relay_only_ticket, + output_dir.path(), + true, + ) + .unwrap(); + + assert_eq!( + std::fs::read(output_dir.path().join("custom-relay.txt")).unwrap(), + b"through the custom relay" + ); +} diff --git a/crates/vnidrop/tests/lifecycle.rs b/crates/vnidrop/tests/lifecycle.rs index 4637e7d..06bc25c 100644 --- a/crates/vnidrop/tests/lifecycle.rs +++ b/crates/vnidrop/tests/lifecycle.rs @@ -5,10 +5,10 @@ use std::time::Duration; use futures_lite::StreamExt as _; use iroh_blobs::store::fs::FsStore; -use support::{share_path, CoreGuard, RecordingSink, TestNode}; +use support::{share_path, CoreGuard, RecordingSink, TestNode, TestRelay}; use vnidrop::{ - CoreEvent, CoreEventSink, CoreLimits, ShareMetadataInput, ShareSource, SourceKind, - TransferAccessMode, + CoreEvent, CoreEventSink, CoreLimits, CoreNetworkConfig, CoreRelayMode, ShareMetadataInput, + ShareSource, SourceKind, TransferAccessMode, }; #[test] @@ -137,6 +137,56 @@ fn persisted_share_is_recovered_and_can_be_stopped_after_restart() { assert_eq!(restarted.status().active_shares, 0); } +#[test] +fn persisted_share_is_revoked_when_restarted_with_a_different_relay_profile() { + let relay_a = TestRelay::start(); + let relay_b = TestRelay::start(); + assert_ne!(relay_a.url, relay_b.url); + + let source_dir = tempfile::tempdir().unwrap(); + let core_dir = tempfile::tempdir().unwrap(); + let source_path = source_dir.path().join("stale-relay.txt"); + std::fs::write(&source_path, b"must not survive a relay profile change").unwrap(); + let sender = CoreGuard::start_with_network_config( + core_dir.path(), + Arc::new(RecordingSink::default()), + CoreNetworkConfig { + mode: CoreRelayMode::StrictCustom, + relay_urls: vec![relay_a.url.clone()], + }, + ); + let share = share_path(&sender, &source_path, 120, "stale-relay.txt", false); + drop(sender); + drop(relay_a); + + let restarted = CoreGuard::start_with_network_config( + core_dir.path(), + Arc::new(RecordingSink::default()), + CoreNetworkConfig { + mode: CoreRelayMode::StrictCustom, + relay_urls: vec![relay_b.url.clone()], + }, + ); + + assert_eq!(restarted.status().active_shares, 0); + let transfer = restarted + .list_transfers() + .unwrap() + .into_iter() + .find(|transfer| transfer.transfer_id == share.transfer_id) + .unwrap(); + assert_eq!(transfer.status, "stopped"); + assert!(restarted + .list_events(Some(share.transfer_id)) + .unwrap() + .iter() + .any(|event| { + event.phase == "recovery" && event.kind == "share-stopped-network-profile-changed" + })); + drop(restarted); + assert_eq!(share_tag_count(core_dir.path()), 0); +} + #[test] fn stopped_share_rejects_receive() { let source_dir = tempfile::tempdir().unwrap(); diff --git a/crates/vnidrop/tests/storage.rs b/crates/vnidrop/tests/storage.rs new file mode 100644 index 0000000..248151b --- /dev/null +++ b/crates/vnidrop/tests/storage.rs @@ -0,0 +1,26 @@ +use vnidrop::clear_inactive_transfer_cache; + +#[test] +fn inactive_transfer_cache_is_removed_and_reports_reclaimed_bytes() { + let app_data = tempfile::tempdir().unwrap(); + let blobs = app_data.path().join("blobs"); + std::fs::create_dir_all(blobs.join("data")).unwrap(); + std::fs::write(blobs.join("data").join("payload"), vec![9u8; 4096]).unwrap(); + std::fs::write(blobs.join("blobs.db"), vec![3u8; 512]).unwrap(); + + let reclaimed = + clear_inactive_transfer_cache(app_data.path().to_string_lossy().into_owned()).unwrap(); + + assert_eq!(reclaimed, 4608); + assert!(!blobs.exists()); +} + +#[test] +fn inactive_transfer_cache_rejects_relative_app_data_paths() { + assert!(clear_inactive_transfer_cache("relative/path".to_string()).is_err()); +} + +#[test] +fn inactive_transfer_cache_rejects_filesystem_roots() { + assert!(clear_inactive_transfer_cache(std::path::MAIN_SEPARATOR_STR.to_string()).is_err()); +} diff --git a/crates/vnidrop/tests/support/mod.rs b/crates/vnidrop/tests/support/mod.rs index d5cc1e2..f1acfa3 100644 --- a/crates/vnidrop/tests/support/mod.rs +++ b/crates/vnidrop/tests/support/mod.rs @@ -8,15 +8,16 @@ use std::{ path::Path, sync::{ atomic::{AtomicBool, Ordering}, - Arc, Condvar, Mutex, + mpsc, Arc, Condvar, Mutex, }, + thread::JoinHandle, time::{Duration, Instant}, }; use vnidrop::{ - CoreEvent, CoreEventSink, CoreLimits, PublishedOutput, ReceiveOutputSink, ReceiveOutputSinkV2, - ReceivedLocatorKind, ReceiverRequest, ShareMetadataInput, ShareResult, ShareSource, SourceKind, - TransferAccessMode, VnidropCore, VnidropError, + CoreEvent, CoreEventSink, CoreLimits, CoreNetworkConfig, PublishedOutput, ReceiveOutputSink, + ReceiveOutputSinkV2, ReceivedLocatorKind, ReceiverRequest, ShareMetadataInput, ShareResult, + ShareSource, SourceKind, TransferAccessMode, VnidropCore, VnidropError, }; #[derive(Default)] @@ -57,6 +58,21 @@ impl CoreGuard { ) } + pub fn start_with_network_config( + path: &Path, + sink: Arc, + network_config: CoreNetworkConfig, + ) -> Self { + Self( + VnidropCore::initialize_with_network_config( + path.to_string_lossy().to_string(), + sink, + network_config, + ) + .expect("test core should initialize with network config"), + ) + } + pub fn arc(&self) -> Arc { self.0.clone() } @@ -93,6 +109,80 @@ impl TestNode { sink, } } + + pub fn with_network_config(network_config: CoreNetworkConfig) -> Self { + let data_dir = tempfile::tempdir().unwrap(); + let sink = Arc::new(RecordingSink::default()); + let core = + CoreGuard::start_with_network_config(data_dir.path(), sink.clone(), network_config); + Self { + _data_dir: data_dir, + core, + sink, + } + } +} + +pub struct TestRelay { + pub url: String, + shutdown: Option>, + thread: Option>, +} + +impl TestRelay { + pub fn start() -> Self { + let (ready_tx, ready_rx) = mpsc::sync_channel(1); + let (shutdown_tx, shutdown_rx) = tokio::sync::oneshot::channel(); + let thread = std::thread::spawn(move || { + let runtime = tokio::runtime::Builder::new_multi_thread() + .enable_all() + .thread_name("vnidrop-test-relay") + .build() + .unwrap(); + runtime.block_on(async move { + let relay = + iroh_relay::server::RelayConfig::new((std::net::Ipv4Addr::LOCALHOST, 0)); + let mut config = iroh_relay::server::ServerConfig::default(); + config.relay = Some(relay); + let server = match iroh_relay::server::Server::spawn(config).await { + Ok(server) => server, + Err(error) => { + ready_tx.send(Err(error.to_string())).ok(); + return; + } + }; + let url = format!( + "http://{}", + server.http_addr().expect("HTTP relay should be bound") + ); + if ready_tx.send(Ok(url)).is_err() { + return; + } + shutdown_rx.await.ok(); + drop(server); + }); + }); + let url = ready_rx + .recv_timeout(Duration::from_secs(5)) + .expect("test relay should start") + .expect("test relay should bind"); + Self { + url, + shutdown: Some(shutdown_tx), + thread: Some(thread), + } + } +} + +impl Drop for TestRelay { + fn drop(&mut self) { + if let Some(shutdown) = self.shutdown.take() { + shutdown.send(()).ok(); + } + if let Some(thread) = self.thread.take() { + thread.join().unwrap(); + } + } } #[derive(Default)] diff --git a/crates/vnidrop/tests/transfer.rs b/crates/vnidrop/tests/transfer.rs index 6544150..64d909a 100644 --- a/crates/vnidrop/tests/transfer.rs +++ b/crates/vnidrop/tests/transfer.rs @@ -1,7 +1,52 @@ mod support; +use std::time::{Duration, Instant}; + use support::{receive_with_response, share_path, TestNode}; -use vnidrop::VnidropError; +use vnidrop::{CoreEvent, VnidropError}; + +fn wait_for_sender_transfer_event(sender: &TestNode, transfer_id: u64, kind: &str) -> CoreEvent { + let started = Instant::now(); + loop { + if let Some(event) = sender.sink.events().into_iter().find(|event| { + event.transfer_id == Some(transfer_id) + && event.direction.as_deref() == Some("send") + && event.phase == "transfer" + && event.kind == kind + }) { + return event; + } + assert!( + started.elapsed() < Duration::from_secs(5), + "timed out waiting for sender transfer event {kind}" + ); + std::thread::sleep(Duration::from_millis(10)); + } +} + +fn wait_for_receiver_status( + sender: &TestNode, + transfer_id: u64, + status: &str, +) -> vnidrop::ReceiverRequest { + let started = Instant::now(); + loop { + if let Some(request) = sender + .core + .list_receiver_requests(transfer_id) + .unwrap() + .into_iter() + .find(|request| request.status == status) + { + return request; + } + assert!( + started.elapsed() < Duration::from_secs(5), + "timed out waiting for receiver status {status}" + ); + std::thread::sleep(Duration::from_millis(10)); + } +} #[test] fn transfers_file_between_two_cores() { @@ -50,6 +95,12 @@ fn transfers_file_between_two_cores() { artifacts[0].locator, output_dir.path().join("hello.txt").to_string_lossy() ); + let completed = wait_for_sender_transfer_event(&sender, share.transfer_id, "completed"); + assert!(completed.data_json.contains("\"connection_id\":")); + assert!(completed.data_json.contains("\"request_id\":")); + assert!(completed + .data_json + .contains(receiver.core.status().endpoint_id.as_str())); receiver.core.delete_receive_history().unwrap(); assert_eq!(receiver.core.list_received_artifacts().unwrap(), artifacts); @@ -135,4 +186,11 @@ fn receive_refuses_to_overwrite_existing_destination() { && event.kind == "failed" && event.data_json.contains("\"code\":\"destination_exists\"") })); + let failed = wait_for_receiver_status(&sender, share.transfer_id, "failed"); + assert_eq!(failed.reason.as_deref(), Some("destination_exists")); + assert!(sender.sink.events().iter().any(|event| { + event.transfer_id == Some(share.transfer_id) + && event.phase == "delivery" + && event.kind == "receiver-failed" + })); } diff --git a/localization/strings.json b/localization/strings.json index 4a59818..be75e03 100644 --- a/localization/strings.json +++ b/localization/strings.json @@ -2672,6 +2672,394 @@ "ru": "Передача VniDrop" } }, + "relay_add_url": { + "context": "Apple Network settings button that appends another custom relay URL field.", + "translations": { + "en": "Add relay server", + "fr": "Ajouter un serveur relais", + "es": "Añadir servidor de retransmisión", + "it": "Aggiungi server relay", + "de": "Relay-Server hinzufügen", + "pt": "Adicionar servidor de retransmissão", + "pl": "Dodaj serwer przekaźnikowy", + "nl": "Relayserver toevoegen", + "ru": "Добавить сервер-ретранслятор" + } + }, + "relay_apply": { + "context": "Network settings button that activates the selected relay configuration.", + "translations": { + "en": "Apply network settings", + "fr": "Appliquer les réglages réseau", + "es": "Aplicar ajustes de red", + "it": "Applica impostazioni di rete", + "de": "Netzwerkeinstellungen anwenden", + "pt": "Aplicar definições de rede", + "pl": "Zastosuj ustawienia sieci", + "nl": "Netwerkinstellingen toepassen", + "ru": "Применить настройки сети" + } + }, + "relay_applying": { + "context": "Network settings button label while a relay configuration is being activated.", + "translations": { + "en": "Applying…", + "fr": "Application…", + "es": "Aplicando…", + "it": "Applicazione…", + "de": "Wird angewendet…", + "pt": "A aplicar…", + "pl": "Stosowanie…", + "nl": "Toepassen…", + "ru": "Применение…" + } + }, + "relay_apply_active_transfers": { + "context": "Network settings warning when relay configuration cannot change during active work.", + "translations": { + "en": "Stop all active transfers and shares before applying network settings.", + "fr": "Arrêtez tous les transferts et partages actifs avant d’appliquer les réglages réseau.", + "es": "Detenga todas las transferencias y elementos compartidos activos antes de aplicar los ajustes de red.", + "it": "Interrompa tutti i trasferimenti e le condivisioni attivi prima di applicare le impostazioni di rete.", + "de": "Beenden Sie alle aktiven Übertragungen und Freigaben, bevor Sie die Netzwerkeinstellungen anwenden.", + "pt": "Pare todas as transferências e partilhas ativas antes de aplicar as definições de rede.", + "pl": "Zatrzymaj wszystkie aktywne transfery i udostępnienia przed zastosowaniem ustawień sieci.", + "nl": "Stop alle actieve overdrachten en gedeelde items voordat u de netwerkinstellingen toepast.", + "ru": "Остановите все активные передачи и раздачи перед применением настроек сети." + } + }, + "relay_apply_failed": { + "context": "Network settings error after a relay configuration fails and the previous one is restored.", + "translations": { + "en": "Could not apply these settings. The previous network settings were restored.", + "fr": "Impossible d’appliquer ces réglages. Les réglages réseau précédents ont été restaurés.", + "es": "No se han podido aplicar estos ajustes. Se han restaurado los ajustes de red anteriores.", + "it": "Impossibile applicare queste impostazioni. Sono state ripristinate le impostazioni di rete precedenti.", + "de": "Diese Einstellungen konnten nicht angewendet werden. Die vorherigen Netzwerkeinstellungen wurden wiederhergestellt.", + "pt": "Não foi possível aplicar estas definições. As definições de rede anteriores foram restauradas.", + "pl": "Nie udało się zastosować tych ustawień. Przywrócono poprzednie ustawienia sieci.", + "nl": "Deze instellingen konden niet worden toegepast. De vorige netwerkinstellingen zijn hersteld.", + "ru": "Не удалось применить эти настройки. Предыдущие настройки сети восстановлены." + } + }, + "relay_apply_restart_description": { + "context": "Network settings explanation of restart and invitation effects when applying relay changes.", + "translations": { + "en": "Applying restarts VniDrop’s network connection. Stop active transfers and shares first. Existing invitations may need to be shared again.", + "fr": "L’application de ces réglages redémarre la connexion réseau de VniDrop. Arrêtez d’abord les transferts et partages actifs. Il peut être nécessaire de partager à nouveau les invitations existantes.", + "es": "Al aplicar los ajustes, se reinicia la conexión de red de VniDrop. Detenga primero las transferencias y los elementos compartidos activos. Es posible que tenga que volver a compartir las invitaciones existentes.", + "it": "L’applicazione riavvia la connessione di rete di VniDrop. Interrompa prima i trasferimenti e le condivisioni attivi. Potrebbe essere necessario condividere di nuovo gli inviti esistenti.", + "de": "Beim Anwenden wird die Netzwerkverbindung von VniDrop neu gestartet. Beenden Sie zuerst aktive Übertragungen und Freigaben. Vorhandene Einladungen müssen eventuell erneut geteilt werden.", + "pt": "A aplicação reinicia a ligação de rede do VniDrop. Pare primeiro as transferências e partilhas ativas. Poderá ser necessário voltar a partilhar os convites existentes.", + "pl": "Zastosowanie ustawień ponownie uruchamia połączenie sieciowe VniDrop. Najpierw zatrzymaj aktywne transfery i udostępnienia. Istniejące zaproszenia mogą wymagać ponownego udostępnienia.", + "nl": "Bij het toepassen wordt de netwerkverbinding van VniDrop opnieuw gestart. Stop eerst actieve overdrachten en gedeelde items. Bestaande uitnodigingen moeten mogelijk opnieuw worden gedeeld.", + "ru": "При применении сетевое соединение VniDrop перезапускается. Сначала остановите активные передачи и раздачи. Возможно, существующие приглашения потребуется отправить повторно." + } + }, + "relay_custom_urls_help": { + "context": "Network settings help for entering custom relay server URLs.", + "translations": { + "en": "Enter one HTTPS relay URL per line. URL credentials are not supported. The TLS certificate must be issued by a publicly trusted certificate authority.", + "fr": "Saisissez une URL de relais HTTPS par ligne. Les identifiants dans les URL ne sont pas pris en charge. Le certificat TLS doit être émis par une autorité de certification reconnue publiquement.", + "es": "Introduzca una URL HTTPS de relé por línea. No se admiten credenciales en las URL. El certificado TLS debe ser emitido por una autoridad de certificación de confianza pública.", + "it": "Inserisca un URL relay HTTPS per riga. Le credenziali negli URL non sono supportate. Il certificato TLS deve essere emesso da un’autorità di certificazione pubblicamente attendibile.", + "de": "Geben Sie pro Zeile eine HTTPS-Relay-URL ein. Anmeldedaten in URLs werden nicht unterstützt. Das TLS-Zertifikat muss von einer öffentlich vertrauenswürdigen Zertifizierungsstelle ausgestellt sein.", + "pt": "Introduza um URL HTTPS de retransmissor por linha. Não são suportadas credenciais nos URLs. O certificado TLS tem de ser emitido por uma autoridade de certificação publicamente reconhecida.", + "pl": "Wprowadź po jednym adresie URL HTTPS przekaźnika w każdym wierszu. Dane logowania w adresach URL nie są obsługiwane. Certyfikat TLS musi być wystawiony przez publicznie zaufany urząd certyfikacji.", + "nl": "Voer per regel één HTTPS-relay-URL in. Aanmeldgegevens in URL's worden niet ondersteund. Het TLS-certificaat moet zijn uitgegeven door een openbaar vertrouwde certificeringsinstantie.", + "ru": "Введите по одному HTTPS-адресу ретранслятора в строке. Учётные данные в URL-адресах не поддерживаются. Сертификат TLS должен быть выдан общедоступным доверенным центром сертификации." + } + }, + "relay_custom_urls_label": { + "context": "Network settings label for the custom relay URL input.", + "translations": { + "en": "Relay URLs", + "fr": "URL des relais", + "es": "URL de relés", + "it": "URL relay", + "de": "Relay-URLs", + "pt": "URLs dos retransmissores", + "pl": "Adresy URL przekaźników", + "nl": "Relay-URL's", + "ru": "URL-адреса ретрансляторов" + } + }, + "relay_mode_automatic": { + "context": "Network settings label for VniDrop's automatic public relay mode.", + "translations": { + "en": "Automatic (recommended)", + "fr": "Automatique (recommandé)", + "es": "Automático (recomendado)", + "it": "Automatica (consigliata)", + "de": "Automatisch (empfohlen)", + "pt": "Automático (recomendado)", + "pl": "Automatyczny (zalecany)", + "nl": "Automatisch (aanbevolen)", + "ru": "Автоматически (рекомендуется)" + } + }, + "relay_mode_automatic_description": { + "context": "Network settings description of automatic public relay behavior.", + "translations": { + "en": "Use VniDrop’s default public relay infrastructure when a direct connection is unavailable.", + "fr": "Utiliser l’infrastructure de relais publique par défaut de VniDrop lorsqu’une connexion directe est indisponible.", + "es": "Usa la infraestructura pública de relés predeterminada de VniDrop cuando no haya una conexión directa disponible.", + "it": "Usa l’infrastruttura relay pubblica predefinita di VniDrop quando non è disponibile una connessione diretta.", + "de": "Verwendet die öffentliche Standard-Relay-Infrastruktur von VniDrop, wenn keine direkte Verbindung möglich ist.", + "pt": "Utiliza a infraestrutura pública de retransmissores predefinida do VniDrop quando não está disponível uma ligação direta.", + "pl": "Używa domyślnej publicznej infrastruktury przekaźników VniDrop, gdy połączenie bezpośrednie jest niedostępne.", + "nl": "Gebruikt de standaard openbare relay-infrastructuur van VniDrop wanneer geen directe verbinding beschikbaar is.", + "ru": "Использовать стандартную публичную инфраструктуру ретрансляторов VniDrop, если прямое соединение недоступно." + } + }, + "relay_mode_custom": { + "context": "Network settings label for strict custom relay mode.", + "translations": { + "en": "Strict custom", + "fr": "Personnalisé strict", + "es": "Personalizado estricto", + "it": "Personalizzata rigorosa", + "de": "Strikt benutzerdefiniert", + "pt": "Personalizado estrito", + "pl": "Ścisły niestandardowy", + "nl": "Strikt aangepast", + "ru": "Строго пользовательский" + } + }, + "relay_mode_custom_description": { + "context": "Network settings description of strict custom relay behavior.", + "translations": { + "en": "Use only the configured custom relays or direct connections. Report an error if no custom relay can be established.", + "fr": "Utilise uniquement les relais personnalisés configurés ou les connexions directes. Signale une erreur si aucun relais personnalisé ne peut être établi.", + "es": "Usa solo los relés personalizados configurados o conexiones directas. Informa de un error si no se puede establecer ningún relé personalizado.", + "it": "Usa solo i relay personalizzati configurati o connessioni dirette. Segnala un errore se non è possibile stabilire alcun relay personalizzato.", + "de": "Verwendet nur die konfigurierten eigenen Relays oder Direktverbindungen. Meldet einen Fehler, wenn kein eigenes Relay erreichbar ist.", + "pt": "Utiliza apenas os retransmissores personalizados configurados ou ligações diretas. Apresenta um erro se não for possível estabelecer nenhum retransmissor personalizado.", + "pl": "Używa tylko skonfigurowanych własnych przekaźników lub połączeń bezpośrednich. Zgłasza błąd, jeśli nie można połączyć się z żadnym własnym przekaźnikiem.", + "nl": "Gebruikt alleen de ingestelde aangepaste relays of rechtstreekse verbindingen. Meldt een fout als geen aangepaste relay bereikbaar is.", + "ru": "Использует только настроенные пользовательские ретрансляторы или прямые соединения. Сообщает об ошибке, если ни один пользовательский ретранслятор недоступен." + } + }, + "relay_mode_custom_direct_fallback": { + "context": "Network settings label for custom relays that allow direct-only startup fallback.", + "translations": { + "en": "Custom with direct fallback", + "fr": "Personnalisé avec repli direct", + "es": "Personalizado con conexión directa de reserva", + "it": "Personalizzata con ripiego diretto", + "de": "Benutzerdefiniert mit direktem Rückfall", + "pt": "Personalizado com alternativa direta", + "pl": "Niestandardowy z trybem bezpośrednim", + "nl": "Aangepast met directe terugval", + "ru": "Пользовательский с прямым резервом" + } + }, + "relay_mode_custom_direct_fallback_description": { + "context": "Network settings description of custom relays with direct-only startup fallback.", + "translations": { + "en": "Prefer the configured custom relays. If unavailable, continue with direct connections only. Never use public relays.", + "fr": "Préfère les relais personnalisés configurés. S’ils sont indisponibles, continue uniquement avec des connexions directes. N’utilise jamais les relais publics.", + "es": "Prefiere los relés personalizados configurados. Si no están disponibles, continúa solo con conexiones directas. Nunca usa relés públicos.", + "it": "Preferisce i relay personalizzati configurati. Se non sono disponibili, continua solo con connessioni dirette. Non usa mai relay pubblici.", + "de": "Bevorzugt die konfigurierten eigenen Relays. Sind sie nicht verfügbar, werden nur Direktverbindungen verwendet. Öffentliche Relays werden nie genutzt.", + "pt": "Prefere os retransmissores personalizados configurados. Se não estiverem disponíveis, continua apenas com ligações diretas. Nunca utiliza retransmissores públicos.", + "pl": "Preferuje skonfigurowane własne przekaźniki. Jeśli są niedostępne, kontynuuje tylko przez połączenia bezpośrednie. Nigdy nie używa publicznych przekaźników.", + "nl": "Geeft de voorkeur aan de ingestelde aangepaste relays. Als die niet beschikbaar zijn, worden alleen rechtstreekse verbindingen gebruikt. Openbare relays worden nooit gebruikt.", + "ru": "Предпочитает настроенные пользовательские ретрансляторы. Если они недоступны, продолжает работу только через прямые соединения. Публичные ретрансляторы не используются." + } + }, + "relay_mode_local_only": { + "context": "Network settings label for direct connections without any relay.", + "translations": { + "en": "Local only", + "fr": "Réseau local uniquement", + "es": "Solo red local", + "it": "Solo rete locale", + "de": "Nur lokales Netzwerk", + "pt": "Apenas rede local", + "pl": "Tylko sieć lokalna", + "nl": "Alleen lokaal netwerk", + "ru": "Только локальная сеть" + } + }, + "relay_mode_local_only_description": { + "context": "Network settings description of direct-only local-network mode.", + "translations": { + "en": "Disable all relays and allow only direct connections, primarily for devices on the same network.", + "fr": "Désactive tous les relais et autorise uniquement les connexions directes, principalement pour les appareils sur le même réseau.", + "es": "Desactiva todos los relés y permite solo conexiones directas, principalmente para dispositivos de la misma red.", + "it": "Disattiva tutti i relay e consente solo connessioni dirette, soprattutto per dispositivi sulla stessa rete.", + "de": "Deaktiviert alle Relays und erlaubt nur Direktverbindungen, hauptsächlich für Geräte im selben Netzwerk.", + "pt": "Desativa todos os retransmissores e permite apenas ligações diretas, principalmente para dispositivos na mesma rede.", + "pl": "Wyłącza wszystkie przekaźniki i zezwala tylko na połączenia bezpośrednie, głównie dla urządzeń w tej samej sieci.", + "nl": "Schakelt alle relays uit en staat alleen rechtstreekse verbindingen toe, vooral voor apparaten in hetzelfde netwerk.", + "ru": "Отключает все ретрансляторы и разрешает только прямые соединения, прежде всего для устройств в одной сети." + } + }, + "relay_privacy_description": { + "context": "Network settings privacy note about what relay operators can observe.", + "translations": { + "en": "Relays forward encrypted traffic and cannot read your files, but their operator can observe connection metadata.", + "fr": "Les relais transmettent du trafic chiffré et ne peuvent pas lire vos fichiers, mais leur opérateur peut observer les métadonnées de connexion.", + "es": "Los relés reenvían tráfico cifrado y no pueden leer sus archivos, pero su operador puede observar los metadatos de conexión.", + "it": "I relay inoltrano traffico cifrato e non possono leggere i suoi file, ma il loro operatore può osservare i metadati di connessione.", + "de": "Relays leiten verschlüsselten Datenverkehr weiter und können Ihre Dateien nicht lesen, ihr Betreiber kann jedoch Verbindungsmetadaten sehen.", + "pt": "Os retransmissores encaminham tráfego cifrado e não conseguem ler os seus ficheiros, mas o operador pode observar metadados da ligação.", + "pl": "Przekaźniki przesyłają zaszyfrowany ruch i nie mogą odczytać plików, ale ich operator może obserwować metadane połączenia.", + "nl": "Relays sturen versleuteld verkeer door en kunnen uw bestanden niet lezen, maar de beheerder kan verbindingsmetadata bekijken.", + "ru": "Ретрансляторы передают зашифрованный трафик и не могут читать ваши файлы, но их оператор может видеть метаданные соединения." + } + }, + "relay_remove_url": { + "context": "Apple Network settings accessibility label for removing one custom relay URL field.", + "translations": { + "en": "Remove relay server", + "fr": "Supprimer le serveur relais", + "es": "Eliminar servidor de retransmisión", + "it": "Rimuovi server relay", + "de": "Relay-Server entfernen", + "pt": "Remover servidor de retransmissão", + "pl": "Usuń serwer przekaźnikowy", + "nl": "Relayserver verwijderen", + "ru": "Удалить сервер-ретранслятор" + } + }, + "relay_restore_failed": { + "context": "Network settings severe error when neither new nor previous relay settings can initialize.", + "translations": { + "en": "Could not restore the previous network settings. Restart VniDrop and review your relay configuration.", + "fr": "Impossible de restaurer les réglages réseau précédents. Redémarrez VniDrop et vérifiez votre configuration de relais.", + "es": "No se han podido restaurar los ajustes de red anteriores. Reinicie VniDrop y revise la configuración de relés.", + "it": "Impossibile ripristinare le impostazioni di rete precedenti. Riavvii VniDrop e verifichi la configurazione dei relay.", + "de": "Die vorherigen Netzwerkeinstellungen konnten nicht wiederhergestellt werden. Starten Sie VniDrop neu und prüfen Sie Ihre Relay-Konfiguration.", + "pt": "Não foi possível restaurar as definições de rede anteriores. Reinicie o VniDrop e reveja a configuração dos retransmissores.", + "pl": "Nie udało się przywrócić poprzednich ustawień sieci. Uruchom ponownie VniDrop i sprawdź konfigurację przekaźników.", + "nl": "De vorige netwerkinstellingen konden niet worden hersteld. Start VniDrop opnieuw en controleer uw relayconfiguratie.", + "ru": "Не удалось восстановить предыдущие настройки сети. Перезапустите VniDrop и проверьте конфигурацию ретрансляторов." + } + }, + "relay_settings_applied": { + "context": "Network settings confirmation after a relay configuration is activated.", + "translations": { + "en": "Network settings applied.", + "fr": "Réglages réseau appliqués.", + "es": "Ajustes de red aplicados.", + "it": "Impostazioni di rete applicate.", + "de": "Netzwerkeinstellungen angewendet.", + "pt": "Definições de rede aplicadas.", + "pl": "Zastosowano ustawienia sieci.", + "nl": "Netwerkinstellingen toegepast.", + "ru": "Настройки сети применены." + } + }, + "relay_strict_warning": { + "context": "Network settings warning that custom relay mode has no public fallback or discovery.", + "translations": { + "en": "Strict custom mode will not start unless at least one configured relay is reachable. VniDrop never uses public relays or public discovery in this mode.", + "fr": "Le mode personnalisé strict ne démarre que si au moins un relais configuré est accessible. VniDrop n’utilise jamais de relais ni de découverte publics dans ce mode.", + "es": "El modo personalizado estricto no se inicia a menos que se pueda acceder al menos a un relé configurado. VniDrop nunca usa relés ni descubrimiento públicos en este modo.", + "it": "La modalità personalizzata rigorosa si avvia solo se almeno un relay configurato è raggiungibile. In questa modalità VniDrop non usa mai relay o rilevamento pubblici.", + "de": "Der strikt benutzerdefinierte Modus startet nur, wenn mindestens ein konfiguriertes Relay erreichbar ist. VniDrop verwendet in diesem Modus nie öffentliche Relays oder öffentliche Erkennung.", + "pt": "O modo personalizado estrito só inicia se pelo menos um retransmissor configurado estiver acessível. Neste modo, o VniDrop nunca utiliza retransmissores nem descoberta públicos.", + "pl": "Ścisły tryb niestandardowy uruchamia się tylko wtedy, gdy co najmniej jeden skonfigurowany przekaźnik jest dostępny. VniDrop nigdy nie używa w tym trybie publicznych przekaźników ani publicznego wykrywania.", + "nl": "De strikt aangepaste modus start alleen als minstens één ingestelde relay bereikbaar is. VniDrop gebruikt in deze modus nooit openbare relays of openbare detectie.", + "ru": "Строго пользовательский режим запускается, только если доступен хотя бы один настроенный ретранслятор. В этом режиме VniDrop никогда не использует публичные ретрансляторы или публичное обнаружение." + } + }, + "relay_validation_duplicate_url": { + "context": "Network settings validation error for a repeated custom relay URL.", + "args": [ + { + "name": "line", + "type": "int" + } + ], + "translations": { + "en": "Relay URL on line {line} duplicates an earlier entry.", + "fr": "L’URL de relais à la ligne {line} est identique à une entrée précédente.", + "es": "La URL de relé de la línea {line} duplica una entrada anterior.", + "it": "L’URL relay alla riga {line} duplica una voce precedente.", + "de": "Die Relay-URL in Zeile {line} ist bereits zuvor eingetragen.", + "pt": "O URL do retransmissor na linha {line} duplica uma entrada anterior.", + "pl": "Adres URL przekaźnika w wierszu {line} powtarza wcześniejszy wpis.", + "nl": "De relay-URL op regel {line} is gelijk aan een eerdere invoer.", + "ru": "URL-адрес ретранслятора в строке {line} повторяет предыдущую запись." + } + }, + "relay_validation_https_required": { + "context": "Network settings validation error when a custom relay URL is not HTTPS.", + "args": [ + { + "name": "line", + "type": "int" + } + ], + "translations": { + "en": "Relay URL on line {line} must start with https://.", + "fr": "L’URL de relais à la ligne {line} doit commencer par https://.", + "es": "La URL de relé de la línea {line} debe empezar por https://.", + "it": "L’URL relay alla riga {line} deve iniziare con https://.", + "de": "Die Relay-URL in Zeile {line} muss mit https:// beginnen.", + "pt": "O URL do retransmissor na linha {line} tem de começar por https://.", + "pl": "Adres URL przekaźnika w wierszu {line} musi zaczynać się od https://.", + "nl": "De relay-URL op regel {line} moet beginnen met https://.", + "ru": "URL-адрес ретранслятора в строке {line} должен начинаться с https://." + } + }, + "relay_validation_invalid_url": { + "context": "Network settings validation error for a malformed custom relay URL.", + "args": [ + { + "name": "line", + "type": "int" + } + ], + "translations": { + "en": "Relay URL on line {line} is not valid.", + "fr": "L’URL de relais à la ligne {line} n’est pas valide.", + "es": "La URL de relé de la línea {line} no es válida.", + "it": "L’URL relay alla riga {line} non è valido.", + "de": "Die Relay-URL in Zeile {line} ist ungültig.", + "pt": "O URL do retransmissor na linha {line} não é válido.", + "pl": "Adres URL przekaźnika w wierszu {line} jest nieprawidłowy.", + "nl": "De relay-URL op regel {line} is ongeldig.", + "ru": "URL-адрес ретранслятора в строке {line} недействителен." + } + }, + "relay_validation_missing_url": { + "context": "Network settings validation error when custom mode has no relay URL.", + "translations": { + "en": "Add at least one relay URL.", + "fr": "Ajoutez au moins une URL de relais.", + "es": "Añada al menos una URL de relé.", + "it": "Aggiunga almeno un URL relay.", + "de": "Fügen Sie mindestens eine Relay-URL hinzu.", + "pt": "Adicione pelo menos um URL de retransmissor.", + "pl": "Dodaj co najmniej jeden adres URL przekaźnika.", + "nl": "Voeg ten minste één relay-URL toe.", + "ru": "Добавьте хотя бы один URL-адрес ретранслятора." + } + }, + "relay_validation_too_many_urls": { + "context": "Network settings validation error when too many custom relay URLs are entered.", + "args": [ + { + "name": "maximum", + "type": "int" + } + ], + "translations": { + "en": "You can configure up to {maximum} relay servers.", + "fr": "Vous pouvez configurer jusqu’à {maximum} serveurs relais.", + "es": "Puede configurar hasta {maximum} servidores de retransmisión.", + "it": "Può configurare fino a {maximum} server relay.", + "de": "Sie können bis zu {maximum} Relay-Server konfigurieren.", + "pt": "Pode configurar até {maximum} servidores de retransmissão.", + "pl": "Możesz skonfigurować maksymalnie {maximum} serwerów przekaźnikowych.", + "nl": "U kunt maximaal {maximum} relayservers instellen.", + "ru": "Можно настроить до {maximum} серверов-ретрансляторов." + } + }, "send_access_anyone": { "context": "Send access option: anyone with the invitation can receive.", "translations": { @@ -3000,6 +3388,34 @@ "ru": "Ваши передачи" } }, + "settings_advanced_title": { + "context": "Settings overview section header for expert configuration.", + "translations": { + "en": "Advanced", + "fr": "Avancé", + "es": "Avanzado", + "it": "Avanzate", + "de": "Erweitert", + "pt": "Avançado", + "pl": "Zaawansowane", + "nl": "Geavanceerd", + "ru": "Дополнительно" + } + }, + "settings_network_title": { + "context": "Settings overview row and Network settings screen title.", + "translations": { + "en": "Network", + "fr": "Réseau", + "es": "Red", + "it": "Rete", + "de": "Netzwerk", + "pt": "Rede", + "pl": "Sieć", + "nl": "Netwerk", + "ru": "Сеть" + } + }, "settings_subtitle": { "context": "Settings screen: subtitle summarizing what's configurable.", "translations": { @@ -3903,6 +4319,20 @@ "ru": "Запрос истёк" } }, + "transfer_receiver_failed": { + "context": "Receiver status: the delivery to this receiver failed.", + "translations": { + "en": "Delivery failed", + "fr": "Échec de l'envoi", + "es": "Error en la entrega", + "it": "Consegna non riuscita", + "de": "Übertragung fehlgeschlagen", + "pt": "Falha na entrega", + "pl": "Dostarczenie nie powiodło się", + "nl": "Levering mislukt", + "ru": "Ошибка доставки" + } + }, "transfer_receiver_refused": { "context": "Receiver status: the request was refused.", "translations": { @@ -4013,6 +4443,20 @@ "ru": "Получатели" } }, + "transfer_qr_unavailable": { + "context": "Transfer share: shown when an invitation is too large to encode as a QR code.", + "translations": { + "en": "QR unavailable for this invitation. Use Share or Download instead.", + "fr": "Le code QR n’est pas disponible pour cette invitation. Utilisez plutôt Partager ou Télécharger.", + "es": "El QR no está disponible para esta invitación. Use Compartir o Descargar.", + "it": "Il codice QR non è disponibile per questo invito. Utilizzi invece Condividi o Scarica.", + "de": "Für diese Einladung ist kein QR-Code verfügbar. Verwenden Sie stattdessen Teilen oder Herunterladen.", + "pt": "O código QR não está disponível para este convite. Utilize Partilhar ou Transferir.", + "pl": "Kod QR jest niedostępny dla tego zaproszenia. Zamiast tego użyj opcji Udostępnij lub Pobierz.", + "nl": "QR is niet beschikbaar voor deze uitnodiging. Gebruik in plaats daarvan Delen of Downloaden.", + "ru": "QR-код недоступен для этого приглашения. Используйте «Поделиться» или «Скачать»." + } + }, "transfer_scan_qr": { "context": "Transfer share: caption under the QR code.", "translations": { diff --git a/shared/src/androidMain/kotlin/com/vnidrop/app/core/FileSystemService.android.kt b/shared/src/androidMain/kotlin/com/vnidrop/app/core/FileSystemService.android.kt index fb8bc5b..9bb4d11 100644 --- a/shared/src/androidMain/kotlin/com/vnidrop/app/core/FileSystemService.android.kt +++ b/shared/src/androidMain/kotlin/com/vnidrop/app/core/FileSystemService.android.kt @@ -103,7 +103,7 @@ private class AndroidFileSystemService( return ReceivedStorageInspection(bytes, existing, missing, inaccessible) } - override suspend fun temporaryUsage(): ULong = directorySize(context.cacheDir) + override suspend fun temporaryUsage(receiveFolder: ReceiveFolder): ULong = directorySize(context.cacheDir) override fun createReceiveOutputSink(folder: ReceiveFolder): ReceiveOutputSinkV2? = when (folder.kind) { diff --git a/shared/src/commonMain/composeResources/values-de/strings.xml b/shared/src/commonMain/composeResources/values-de/strings.xml index 315627c..4a85909 100644 --- a/shared/src/commonMain/composeResources/values-de/strings.xml +++ b/shared/src/commonMain/composeResources/values-de/strings.xml @@ -170,6 +170,32 @@ Übertragung prüfen Empfangen VniDrop-Übertragung + Relay-Server hinzufügen + Netzwerkeinstellungen anwenden + Wird angewendet… + Beenden Sie alle aktiven Übertragungen und Freigaben, bevor Sie die Netzwerkeinstellungen anwenden. + Diese Einstellungen konnten nicht angewendet werden. Die vorherigen Netzwerkeinstellungen wurden wiederhergestellt. + Beim Anwenden wird die Netzwerkverbindung von VniDrop neu gestartet. Beenden Sie zuerst aktive Übertragungen und Freigaben. Vorhandene Einladungen müssen eventuell erneut geteilt werden. + Geben Sie pro Zeile eine HTTPS-Relay-URL ein. Anmeldedaten in URLs werden nicht unterstützt. Das TLS-Zertifikat muss von einer öffentlich vertrauenswürdigen Zertifizierungsstelle ausgestellt sein. + Relay-URLs + Automatisch (empfohlen) + Verwendet die öffentliche Standard-Relay-Infrastruktur von VniDrop, wenn keine direkte Verbindung möglich ist. + Strikt benutzerdefiniert + Verwendet nur die konfigurierten eigenen Relays oder Direktverbindungen. Meldet einen Fehler, wenn kein eigenes Relay erreichbar ist. + Benutzerdefiniert mit direktem Rückfall + Bevorzugt die konfigurierten eigenen Relays. Sind sie nicht verfügbar, werden nur Direktverbindungen verwendet. Öffentliche Relays werden nie genutzt. + Nur lokales Netzwerk + Deaktiviert alle Relays und erlaubt nur Direktverbindungen, hauptsächlich für Geräte im selben Netzwerk. + Relays leiten verschlüsselten Datenverkehr weiter und können Ihre Dateien nicht lesen, ihr Betreiber kann jedoch Verbindungsmetadaten sehen. + Relay-Server entfernen + Die vorherigen Netzwerkeinstellungen konnten nicht wiederhergestellt werden. Starten Sie VniDrop neu und prüfen Sie Ihre Relay-Konfiguration. + Netzwerkeinstellungen angewendet. + Der strikt benutzerdefinierte Modus startet nur, wenn mindestens ein konfiguriertes Relay erreichbar ist. VniDrop verwendet in diesem Modus nie öffentliche Relays oder öffentliche Erkennung. + Die Relay-URL in Zeile %1$d ist bereits zuvor eingetragen. + Die Relay-URL in Zeile %1$d muss mit https:// beginnen. + Die Relay-URL in Zeile %1$d ist ungültig. + Fügen Sie mindestens eine Relay-URL hinzu. + Sie können bis zu %1$d Relay-Server konfigurieren. Jeder mit dieser Übertragung Keine Genehmigung erforderlich. Verwenden Sie dies nur für Objekte, die Sie unbedenklich teilen können. Jeder mit der Einladung kann herunterladen, bis Sie die Freigabe beenden. Verwenden Sie dies nicht für private oder sensible Objekte. @@ -193,6 +219,8 @@ Übertragung erstellt. Übertragungsdetails Ihre Übertragungen + Erweitert + Netzwerk Ihr Name, wo Übertragungen gesichert werden, Darstellung und Mitteilungen. Einstellungen Ausblenden @@ -253,6 +281,7 @@ Genehmigt – wartet auf Abschluss Erfolgreich empfangen Anfrage abgelaufen + Übertragung fehlgeschlagen Anfrage abgelehnt Wartet auf Ihre Genehmigung Status nicht verfügbar @@ -260,6 +289,7 @@ Anfragen, Genehmigungen und abgeschlossene Zustellungen %1$d warten Empfänger + Für diese Einladung ist kein QR-Code verfügbar. Verwenden Sie stattdessen Teilen oder Herunterladen. Mit VniDrop scannen, um diese Übertragung zu empfangen QR-Code, Einladungsdatei und Optionen in der Nähe Teilen diff --git a/shared/src/commonMain/composeResources/values-es/strings.xml b/shared/src/commonMain/composeResources/values-es/strings.xml index 130422a..7d1c285 100644 --- a/shared/src/commonMain/composeResources/values-es/strings.xml +++ b/shared/src/commonMain/composeResources/values-es/strings.xml @@ -170,6 +170,32 @@ Revisar transferencia Recibir Transferencia de VniDrop + Añadir servidor de retransmisión + Aplicar ajustes de red + Aplicando… + Detenga todas las transferencias y elementos compartidos activos antes de aplicar los ajustes de red. + No se han podido aplicar estos ajustes. Se han restaurado los ajustes de red anteriores. + Al aplicar los ajustes, se reinicia la conexión de red de VniDrop. Detenga primero las transferencias y los elementos compartidos activos. Es posible que tenga que volver a compartir las invitaciones existentes. + Introduzca una URL HTTPS de relé por línea. No se admiten credenciales en las URL. El certificado TLS debe ser emitido por una autoridad de certificación de confianza pública. + URL de relés + Automático (recomendado) + Usa la infraestructura pública de relés predeterminada de VniDrop cuando no haya una conexión directa disponible. + Personalizado estricto + Usa solo los relés personalizados configurados o conexiones directas. Informa de un error si no se puede establecer ningún relé personalizado. + Personalizado con conexión directa de reserva + Prefiere los relés personalizados configurados. Si no están disponibles, continúa solo con conexiones directas. Nunca usa relés públicos. + Solo red local + Desactiva todos los relés y permite solo conexiones directas, principalmente para dispositivos de la misma red. + Los relés reenvían tráfico cifrado y no pueden leer sus archivos, pero su operador puede observar los metadatos de conexión. + Eliminar servidor de retransmisión + No se han podido restaurar los ajustes de red anteriores. Reinicie VniDrop y revise la configuración de relés. + Ajustes de red aplicados. + El modo personalizado estricto no se inicia a menos que se pueda acceder al menos a un relé configurado. VniDrop nunca usa relés ni descubrimiento públicos en este modo. + La URL de relé de la línea %1$d duplica una entrada anterior. + La URL de relé de la línea %1$d debe empezar por https://. + La URL de relé de la línea %1$d no es válida. + Añada al menos una URL de relé. + Puede configurar hasta %1$d servidores de retransmisión. Cualquiera que tenga esta transferencia No se requiere aprobación. Úselo solo para elementos que no le importe compartir. Cualquiera que tenga la invitación puede descargar hasta que deje de compartir. No lo use para elementos privados o sensibles. @@ -193,6 +219,8 @@ Transferencia creada. Detalles de la transferencia Sus transferencias + Avanzado + Red Su nombre, dónde se guardan las transferencias, la apariencia y las notificaciones. Ajustes Descartar @@ -253,6 +281,7 @@ Aprobado: esperando a que se complete Recibido correctamente Solicitud caducada + Error en la entrega Solicitud rechazada Esperando su aprobación Estado no disponible @@ -260,6 +289,7 @@ Solicitudes, aprobaciones y entregas completadas %1$d en espera Destinatarios + El QR no está disponible para esta invitación. Use Compartir o Descargar. Escanee con VniDrop para recibir esta transferencia Código QR, archivo de invitación y opciones cercanas Compartir diff --git a/shared/src/commonMain/composeResources/values-fr/strings.xml b/shared/src/commonMain/composeResources/values-fr/strings.xml index ce9eb80..41de788 100644 --- a/shared/src/commonMain/composeResources/values-fr/strings.xml +++ b/shared/src/commonMain/composeResources/values-fr/strings.xml @@ -170,6 +170,32 @@ Vérifier le transfert Recevoir Transfert VniDrop + Ajouter un serveur relais + Appliquer les réglages réseau + Application… + Arrêtez tous les transferts et partages actifs avant d’appliquer les réglages réseau. + Impossible d’appliquer ces réglages. Les réglages réseau précédents ont été restaurés. + L’application de ces réglages redémarre la connexion réseau de VniDrop. Arrêtez d’abord les transferts et partages actifs. Il peut être nécessaire de partager à nouveau les invitations existantes. + Saisissez une URL de relais HTTPS par ligne. Les identifiants dans les URL ne sont pas pris en charge. Le certificat TLS doit être émis par une autorité de certification reconnue publiquement. + URL des relais + Automatique (recommandé) + Utiliser l’infrastructure de relais publique par défaut de VniDrop lorsqu’une connexion directe est indisponible. + Personnalisé strict + Utilise uniquement les relais personnalisés configurés ou les connexions directes. Signale une erreur si aucun relais personnalisé ne peut être établi. + Personnalisé avec repli direct + Préfère les relais personnalisés configurés. S’ils sont indisponibles, continue uniquement avec des connexions directes. N’utilise jamais les relais publics. + Réseau local uniquement + Désactive tous les relais et autorise uniquement les connexions directes, principalement pour les appareils sur le même réseau. + Les relais transmettent du trafic chiffré et ne peuvent pas lire vos fichiers, mais leur opérateur peut observer les métadonnées de connexion. + Supprimer le serveur relais + Impossible de restaurer les réglages réseau précédents. Redémarrez VniDrop et vérifiez votre configuration de relais. + Réglages réseau appliqués. + Le mode personnalisé strict ne démarre que si au moins un relais configuré est accessible. VniDrop n’utilise jamais de relais ni de découverte publics dans ce mode. + L’URL de relais à la ligne %1$d est identique à une entrée précédente. + L’URL de relais à la ligne %1$d doit commencer par https://. + L’URL de relais à la ligne %1$d n’est pas valide. + Ajoutez au moins une URL de relais. + Vous pouvez configurer jusqu’à %1$d serveurs relais. Toute personne disposant de ce transfert Aucune approbation requise. À n’utiliser que pour des éléments que vous êtes à l’aise de partager. Toute personne disposant de l’invitation peut télécharger jusqu’à ce que vous arrêtiez le partage. Ne l’utilisez pas pour des éléments privés ou sensibles. @@ -193,6 +219,8 @@ Transfert créé. Détails du transfert Vos transferts + Avancé + Réseau Votre nom, l’emplacement d’enregistrement des transferts, l’apparence et les notifications. Réglages Ignorer @@ -253,6 +281,7 @@ Approuvé — en attente de la fin Reçu avec succès Demande expirée + Échec de l\'envoi Demande refusée En attente de votre approbation Statut indisponible @@ -260,6 +289,7 @@ Demandes, approbations et livraisons terminées %1$d en attente Destinataires + Le code QR n’est pas disponible pour cette invitation. Utilisez plutôt Partager ou Télécharger. Scannez avec VniDrop pour recevoir ce transfert QR code, fichier d’invitation et options à proximité Partager diff --git a/shared/src/commonMain/composeResources/values-it/strings.xml b/shared/src/commonMain/composeResources/values-it/strings.xml index 03645d8..463dc47 100644 --- a/shared/src/commonMain/composeResources/values-it/strings.xml +++ b/shared/src/commonMain/composeResources/values-it/strings.xml @@ -170,6 +170,32 @@ Rivedi trasferimento Ricevi Trasferimento VniDrop + Aggiungi server relay + Applica impostazioni di rete + Applicazione… + Interrompa tutti i trasferimenti e le condivisioni attivi prima di applicare le impostazioni di rete. + Impossibile applicare queste impostazioni. Sono state ripristinate le impostazioni di rete precedenti. + L’applicazione riavvia la connessione di rete di VniDrop. Interrompa prima i trasferimenti e le condivisioni attivi. Potrebbe essere necessario condividere di nuovo gli inviti esistenti. + Inserisca un URL relay HTTPS per riga. Le credenziali negli URL non sono supportate. Il certificato TLS deve essere emesso da un’autorità di certificazione pubblicamente attendibile. + URL relay + Automatica (consigliata) + Usa l’infrastruttura relay pubblica predefinita di VniDrop quando non è disponibile una connessione diretta. + Personalizzata rigorosa + Usa solo i relay personalizzati configurati o connessioni dirette. Segnala un errore se non è possibile stabilire alcun relay personalizzato. + Personalizzata con ripiego diretto + Preferisce i relay personalizzati configurati. Se non sono disponibili, continua solo con connessioni dirette. Non usa mai relay pubblici. + Solo rete locale + Disattiva tutti i relay e consente solo connessioni dirette, soprattutto per dispositivi sulla stessa rete. + I relay inoltrano traffico cifrato e non possono leggere i suoi file, ma il loro operatore può osservare i metadati di connessione. + Rimuovi server relay + Impossibile ripristinare le impostazioni di rete precedenti. Riavvii VniDrop e verifichi la configurazione dei relay. + Impostazioni di rete applicate. + La modalità personalizzata rigorosa si avvia solo se almeno un relay configurato è raggiungibile. In questa modalità VniDrop non usa mai relay o rilevamento pubblici. + L’URL relay alla riga %1$d duplica una voce precedente. + L’URL relay alla riga %1$d deve iniziare con https://. + L’URL relay alla riga %1$d non è valido. + Aggiunga almeno un URL relay. + Può configurare fino a %1$d server relay. Chiunque abbia questo trasferimento Nessuna approvazione richiesta. Da usare solo per elementi che non ha problemi a condividere. Chiunque abbia l’invito può scaricare finché non interrompe la condivisione. Non lo usi per elementi privati o sensibili. @@ -193,6 +219,8 @@ Trasferimento creato. Dettagli del trasferimento I suoi trasferimenti + Avanzate + Rete Il suo nome, dove vengono salvati i trasferimenti, l’aspetto e le notifiche. Impostazioni Ignora @@ -253,6 +281,7 @@ Approvato: in attesa del completamento Ricevuto correttamente Richiesta scaduta + Consegna non riuscita Richiesta rifiutata In attesa della sua approvazione Stato non disponibile @@ -260,6 +289,7 @@ Richieste, approvazioni e consegne completate %1$d in attesa Destinatari + Il codice QR non è disponibile per questo invito. Utilizzi invece Condividi o Scarica. Scansioni con VniDrop per ricevere questo trasferimento Codice QR, file di invito e opzioni nelle vicinanze Condividi diff --git a/shared/src/commonMain/composeResources/values-nl/strings.xml b/shared/src/commonMain/composeResources/values-nl/strings.xml index 4674cec..e5728ab 100644 --- a/shared/src/commonMain/composeResources/values-nl/strings.xml +++ b/shared/src/commonMain/composeResources/values-nl/strings.xml @@ -170,6 +170,32 @@ Overdracht controleren Ontvangen VniDrop-overdracht + Relayserver toevoegen + Netwerkinstellingen toepassen + Toepassen… + Stop alle actieve overdrachten en gedeelde items voordat u de netwerkinstellingen toepast. + Deze instellingen konden niet worden toegepast. De vorige netwerkinstellingen zijn hersteld. + Bij het toepassen wordt de netwerkverbinding van VniDrop opnieuw gestart. Stop eerst actieve overdrachten en gedeelde items. Bestaande uitnodigingen moeten mogelijk opnieuw worden gedeeld. + Voer per regel één HTTPS-relay-URL in. Aanmeldgegevens in URL\'s worden niet ondersteund. Het TLS-certificaat moet zijn uitgegeven door een openbaar vertrouwde certificeringsinstantie. + Relay-URL\'s + Automatisch (aanbevolen) + Gebruikt de standaard openbare relay-infrastructuur van VniDrop wanneer geen directe verbinding beschikbaar is. + Strikt aangepast + Gebruikt alleen de ingestelde aangepaste relays of rechtstreekse verbindingen. Meldt een fout als geen aangepaste relay bereikbaar is. + Aangepast met directe terugval + Geeft de voorkeur aan de ingestelde aangepaste relays. Als die niet beschikbaar zijn, worden alleen rechtstreekse verbindingen gebruikt. Openbare relays worden nooit gebruikt. + Alleen lokaal netwerk + Schakelt alle relays uit en staat alleen rechtstreekse verbindingen toe, vooral voor apparaten in hetzelfde netwerk. + Relays sturen versleuteld verkeer door en kunnen uw bestanden niet lezen, maar de beheerder kan verbindingsmetadata bekijken. + Relayserver verwijderen + De vorige netwerkinstellingen konden niet worden hersteld. Start VniDrop opnieuw en controleer uw relayconfiguratie. + Netwerkinstellingen toegepast. + De strikt aangepaste modus start alleen als minstens één ingestelde relay bereikbaar is. VniDrop gebruikt in deze modus nooit openbare relays of openbare detectie. + De relay-URL op regel %1$d is gelijk aan een eerdere invoer. + De relay-URL op regel %1$d moet beginnen met https://. + De relay-URL op regel %1$d is ongeldig. + Voeg ten minste één relay-URL toe. + U kunt maximaal %1$d relayservers instellen. Iedereen met deze overdracht Geen goedkeuring vereist. Gebruik dit alleen voor items die u gerust kunt delen. Iedereen met de uitnodiging kan downloaden totdat u stopt met delen. Gebruik dit niet voor privé- of gevoelige items. @@ -193,6 +219,8 @@ Overdracht aangemaakt. Overdrachtsdetails Uw overdrachten + Geavanceerd + Netwerk Uw naam, waar overdrachten worden bewaard, weergave en meldingen. Instellingen Sluiten @@ -253,6 +281,7 @@ Goedgekeurd — wachten op voltooiing Succesvol ontvangen Verzoek verlopen + Levering mislukt Verzoek geweigerd Wachten op uw goedkeuring Status niet beschikbaar @@ -260,6 +289,7 @@ Verzoeken, goedkeuringen en voltooide leveringen %1$d in behandeling Ontvangers + QR is niet beschikbaar voor deze uitnodiging. Gebruik in plaats daarvan Delen of Downloaden. Scan met VniDrop om deze overdracht te ontvangen QR-code, uitnodigingsbestand en opties in de buurt Delen diff --git a/shared/src/commonMain/composeResources/values-pl/strings.xml b/shared/src/commonMain/composeResources/values-pl/strings.xml index 237dabe..60d814c 100644 --- a/shared/src/commonMain/composeResources/values-pl/strings.xml +++ b/shared/src/commonMain/composeResources/values-pl/strings.xml @@ -170,6 +170,32 @@ Przejrzyj transfer Odbierz Transfer VniDrop + Dodaj serwer przekaźnikowy + Zastosuj ustawienia sieci + Stosowanie… + Zatrzymaj wszystkie aktywne transfery i udostępnienia przed zastosowaniem ustawień sieci. + Nie udało się zastosować tych ustawień. Przywrócono poprzednie ustawienia sieci. + Zastosowanie ustawień ponownie uruchamia połączenie sieciowe VniDrop. Najpierw zatrzymaj aktywne transfery i udostępnienia. Istniejące zaproszenia mogą wymagać ponownego udostępnienia. + Wprowadź po jednym adresie URL HTTPS przekaźnika w każdym wierszu. Dane logowania w adresach URL nie są obsługiwane. Certyfikat TLS musi być wystawiony przez publicznie zaufany urząd certyfikacji. + Adresy URL przekaźników + Automatyczny (zalecany) + Używa domyślnej publicznej infrastruktury przekaźników VniDrop, gdy połączenie bezpośrednie jest niedostępne. + Ścisły niestandardowy + Używa tylko skonfigurowanych własnych przekaźników lub połączeń bezpośrednich. Zgłasza błąd, jeśli nie można połączyć się z żadnym własnym przekaźnikiem. + Niestandardowy z trybem bezpośrednim + Preferuje skonfigurowane własne przekaźniki. Jeśli są niedostępne, kontynuuje tylko przez połączenia bezpośrednie. Nigdy nie używa publicznych przekaźników. + Tylko sieć lokalna + Wyłącza wszystkie przekaźniki i zezwala tylko na połączenia bezpośrednie, głównie dla urządzeń w tej samej sieci. + Przekaźniki przesyłają zaszyfrowany ruch i nie mogą odczytać plików, ale ich operator może obserwować metadane połączenia. + Usuń serwer przekaźnikowy + Nie udało się przywrócić poprzednich ustawień sieci. Uruchom ponownie VniDrop i sprawdź konfigurację przekaźników. + Zastosowano ustawienia sieci. + Ścisły tryb niestandardowy uruchamia się tylko wtedy, gdy co najmniej jeden skonfigurowany przekaźnik jest dostępny. VniDrop nigdy nie używa w tym trybie publicznych przekaźników ani publicznego wykrywania. + Adres URL przekaźnika w wierszu %1$d powtarza wcześniejszy wpis. + Adres URL przekaźnika w wierszu %1$d musi zaczynać się od https://. + Adres URL przekaźnika w wierszu %1$d jest nieprawidłowy. + Dodaj co najmniej jeden adres URL przekaźnika. + Możesz skonfigurować maksymalnie %1$d serwerów przekaźnikowych. Każdy, kto ma ten transfer Nie jest wymagane zatwierdzenie. Używaj tylko dla elementów, które możesz swobodnie udostępniać. Każdy, kto ma zaproszenie, może pobierać, dopóki nie zatrzymasz udostępniania. Nie używaj tego dla prywatnych ani wrażliwych elementów. @@ -193,6 +219,8 @@ Transfer utworzony. Szczegóły transferu Twoje transfery + Zaawansowane + Sieć Twoja nazwa, miejsce zapisu transferów, wygląd i powiadomienia. Ustawienia Zamknij @@ -253,6 +281,7 @@ Zatwierdzono — oczekiwanie na ukończenie Odebrano pomyślnie Prośba wygasła + Dostarczenie nie powiodło się Prośba odrzucona Oczekiwanie na Twoje zatwierdzenie Status niedostępny @@ -260,6 +289,7 @@ Prośby, zatwierdzenia i ukończone dostawy Oczekujące: %1$d Odbiorcy + Kod QR jest niedostępny dla tego zaproszenia. Zamiast tego użyj opcji Udostępnij lub Pobierz. Zeskanuj za pomocą VniDrop, aby odebrać ten transfer Kod QR, plik zaproszenia i opcje w pobliżu Udostępnij diff --git a/shared/src/commonMain/composeResources/values-pt/strings.xml b/shared/src/commonMain/composeResources/values-pt/strings.xml index b95839c..3ffe0b0 100644 --- a/shared/src/commonMain/composeResources/values-pt/strings.xml +++ b/shared/src/commonMain/composeResources/values-pt/strings.xml @@ -170,6 +170,32 @@ Rever transferência Receber Transferência VniDrop + Adicionar servidor de retransmissão + Aplicar definições de rede + A aplicar… + Pare todas as transferências e partilhas ativas antes de aplicar as definições de rede. + Não foi possível aplicar estas definições. As definições de rede anteriores foram restauradas. + A aplicação reinicia a ligação de rede do VniDrop. Pare primeiro as transferências e partilhas ativas. Poderá ser necessário voltar a partilhar os convites existentes. + Introduza um URL HTTPS de retransmissor por linha. Não são suportadas credenciais nos URLs. O certificado TLS tem de ser emitido por uma autoridade de certificação publicamente reconhecida. + URLs dos retransmissores + Automático (recomendado) + Utiliza a infraestrutura pública de retransmissores predefinida do VniDrop quando não está disponível uma ligação direta. + Personalizado estrito + Utiliza apenas os retransmissores personalizados configurados ou ligações diretas. Apresenta um erro se não for possível estabelecer nenhum retransmissor personalizado. + Personalizado com alternativa direta + Prefere os retransmissores personalizados configurados. Se não estiverem disponíveis, continua apenas com ligações diretas. Nunca utiliza retransmissores públicos. + Apenas rede local + Desativa todos os retransmissores e permite apenas ligações diretas, principalmente para dispositivos na mesma rede. + Os retransmissores encaminham tráfego cifrado e não conseguem ler os seus ficheiros, mas o operador pode observar metadados da ligação. + Remover servidor de retransmissão + Não foi possível restaurar as definições de rede anteriores. Reinicie o VniDrop e reveja a configuração dos retransmissores. + Definições de rede aplicadas. + O modo personalizado estrito só inicia se pelo menos um retransmissor configurado estiver acessível. Neste modo, o VniDrop nunca utiliza retransmissores nem descoberta públicos. + O URL do retransmissor na linha %1$d duplica uma entrada anterior. + O URL do retransmissor na linha %1$d tem de começar por https://. + O URL do retransmissor na linha %1$d não é válido. + Adicione pelo menos um URL de retransmissor. + Pode configurar até %1$d servidores de retransmissão. Qualquer pessoa com esta transferência Não é necessária aprovação. Utilize apenas para itens que não se importe de partilhar. Qualquer pessoa com o convite pode descarregar até parar de partilhar. Não utilize para itens privados ou sensíveis. @@ -193,6 +219,8 @@ Transferência criada. Detalhes da transferência As suas transferências + Avançado + Rede O seu nome, onde as transferências são guardadas, o aspeto e as notificações. Definições Ignorar @@ -253,6 +281,7 @@ Aprovado — a aguardar conclusão Recebido com sucesso Pedido expirado + Falha na entrega Pedido recusado A aguardar a sua aprovação Estado indisponível @@ -260,6 +289,7 @@ Pedidos, aprovações e entregas concluídas %1$d em espera Destinatários + O código QR não está disponível para este convite. Utilize Partilhar ou Transferir. Leia com o VniDrop para receber esta transferência Código QR, ficheiro de convite e opções por perto Partilhar diff --git a/shared/src/commonMain/composeResources/values-ru/strings.xml b/shared/src/commonMain/composeResources/values-ru/strings.xml index 8eb0899..b1f2727 100644 --- a/shared/src/commonMain/composeResources/values-ru/strings.xml +++ b/shared/src/commonMain/composeResources/values-ru/strings.xml @@ -170,6 +170,32 @@ Проверить передачу Получить Передача VniDrop + Добавить сервер-ретранслятор + Применить настройки сети + Применение… + Остановите все активные передачи и раздачи перед применением настроек сети. + Не удалось применить эти настройки. Предыдущие настройки сети восстановлены. + При применении сетевое соединение VniDrop перезапускается. Сначала остановите активные передачи и раздачи. Возможно, существующие приглашения потребуется отправить повторно. + Введите по одному HTTPS-адресу ретранслятора в строке. Учётные данные в URL-адресах не поддерживаются. Сертификат TLS должен быть выдан общедоступным доверенным центром сертификации. + URL-адреса ретрансляторов + Автоматически (рекомендуется) + Использовать стандартную публичную инфраструктуру ретрансляторов VniDrop, если прямое соединение недоступно. + Строго пользовательский + Использует только настроенные пользовательские ретрансляторы или прямые соединения. Сообщает об ошибке, если ни один пользовательский ретранслятор недоступен. + Пользовательский с прямым резервом + Предпочитает настроенные пользовательские ретрансляторы. Если они недоступны, продолжает работу только через прямые соединения. Публичные ретрансляторы не используются. + Только локальная сеть + Отключает все ретрансляторы и разрешает только прямые соединения, прежде всего для устройств в одной сети. + Ретрансляторы передают зашифрованный трафик и не могут читать ваши файлы, но их оператор может видеть метаданные соединения. + Удалить сервер-ретранслятор + Не удалось восстановить предыдущие настройки сети. Перезапустите VniDrop и проверьте конфигурацию ретрансляторов. + Настройки сети применены. + Строго пользовательский режим запускается, только если доступен хотя бы один настроенный ретранслятор. В этом режиме VniDrop никогда не использует публичные ретрансляторы или публичное обнаружение. + URL-адрес ретранслятора в строке %1$d повторяет предыдущую запись. + URL-адрес ретранслятора в строке %1$d должен начинаться с https://. + URL-адрес ретранслятора в строке %1$d недействителен. + Добавьте хотя бы один URL-адрес ретранслятора. + Можно настроить до %1$d серверов-ретрансляторов. Любой, у кого есть эта передача Одобрение не требуется. Используйте только для объектов, которыми вы готовы поделиться. Любой, у кого есть приглашение, может загружать, пока вы не остановите общий доступ. Не используйте это для личных или конфиденциальных объектов. @@ -193,6 +219,8 @@ Передача создана. Сведения о передаче Ваши передачи + Дополнительно + Сеть Ваше имя, место сохранения передач, оформление и уведомления. Настройки Закрыть @@ -253,6 +281,7 @@ Одобрено — ожидание завершения Успешно получено Запрос истёк + Ошибка доставки Запрос отклонён Ожидание вашего одобрения Статус недоступен @@ -260,6 +289,7 @@ Запросы, одобрения и завершённые доставки Ожидают: %1$d Получатели + QR-код недоступен для этого приглашения. Используйте «Поделиться» или «Скачать». Отсканируйте с помощью VniDrop, чтобы получить эту передачу QR-код, файл приглашения и варианты поблизости Поделиться diff --git a/shared/src/commonMain/composeResources/values/strings.xml b/shared/src/commonMain/composeResources/values/strings.xml index f8c1232..bd6f807 100644 --- a/shared/src/commonMain/composeResources/values/strings.xml +++ b/shared/src/commonMain/composeResources/values/strings.xml @@ -170,6 +170,32 @@ Review transfer Receive VniDrop transfer + Add relay server + Apply network settings + Applying… + Stop all active transfers and shares before applying network settings. + Could not apply these settings. The previous network settings were restored. + Applying restarts VniDrop’s network connection. Stop active transfers and shares first. Existing invitations may need to be shared again. + Enter one HTTPS relay URL per line. URL credentials are not supported. The TLS certificate must be issued by a publicly trusted certificate authority. + Relay URLs + Automatic (recommended) + Use VniDrop’s default public relay infrastructure when a direct connection is unavailable. + Strict custom + Use only the configured custom relays or direct connections. Report an error if no custom relay can be established. + Custom with direct fallback + Prefer the configured custom relays. If unavailable, continue with direct connections only. Never use public relays. + Local only + Disable all relays and allow only direct connections, primarily for devices on the same network. + Relays forward encrypted traffic and cannot read your files, but their operator can observe connection metadata. + Remove relay server + Could not restore the previous network settings. Restart VniDrop and review your relay configuration. + Network settings applied. + Strict custom mode will not start unless at least one configured relay is reachable. VniDrop never uses public relays or public discovery in this mode. + Relay URL on line %1$d duplicates an earlier entry. + Relay URL on line %1$d must start with https://. + Relay URL on line %1$d is not valid. + Add at least one relay URL. + You can configure up to %1$d relay servers. Anyone with this transfer No approval is required. Only use this for items you are comfortable sharing. Anyone with the invitation can download until you stop sharing. Do not use this for private or sensitive items. @@ -193,6 +219,8 @@ Transfer created. Transfer details Your transfers + Advanced + Network Your name, where transfers are saved, appearance, and notifications. Settings Dismiss @@ -253,6 +281,7 @@ Approved — waiting for completion Received successfully Request expired + Delivery failed Request refused Waiting for your approval Status unavailable @@ -260,6 +289,7 @@ Requests, approvals, and completed deliveries %1$d waiting Receivers + QR unavailable for this invitation. Use Share or Download instead. Scan with VniDrop to receive this transfer QR code, invitation file, and nearby options Share diff --git a/shared/src/commonMain/kotlin/com/vnidrop/app/core/CoreLifecycleGate.kt b/shared/src/commonMain/kotlin/com/vnidrop/app/core/CoreLifecycleGate.kt new file mode 100644 index 0000000..416c441 --- /dev/null +++ b/shared/src/commonMain/kotlin/com/vnidrop/app/core/CoreLifecycleGate.kt @@ -0,0 +1,51 @@ +package com.vnidrop.app.core + +import kotlinx.coroutines.NonCancellable +import kotlinx.coroutines.sync.Mutex +import kotlinx.coroutines.sync.withLock +import kotlinx.coroutines.withContext + +internal class CoreLifecycleBusyException(message: String) : IllegalStateException(message) + +internal class CoreLifecycleGate { + private val mutex = Mutex() + private var reconfiguring = false + private var inFlightCalls = 0 + + suspend fun withCall( + capture: () -> C, + block: suspend (C) -> T, + ): T { + val captured = mutex.withLock { + if (reconfiguring) throw CoreLifecycleBusyException("Core network configuration is changing") + val value = capture() + inFlightCalls += 1 + value + } + return try { + block(captured) + } finally { + withContext(NonCancellable) { + mutex.withLock { + check(inFlightCalls > 0) + inFlightCalls -= 1 + } + } + } + } + + suspend fun withReconfiguration(block: suspend () -> T): T { + mutex.withLock { + if (reconfiguring) throw CoreLifecycleBusyException("Core network configuration is already changing") + if (inFlightCalls > 0) throw CoreLifecycleBusyException("Core calls are still active") + reconfiguring = true + } + return try { + block() + } finally { + withContext(NonCancellable) { + mutex.withLock { reconfiguring = false } + } + } + } +} diff --git a/shared/src/commonMain/kotlin/com/vnidrop/app/core/CoreModels.kt b/shared/src/commonMain/kotlin/com/vnidrop/app/core/CoreModels.kt index 72d0876..de11ba9 100644 --- a/shared/src/commonMain/kotlin/com/vnidrop/app/core/CoreModels.kt +++ b/shared/src/commonMain/kotlin/com/vnidrop/app/core/CoreModels.kt @@ -27,6 +27,21 @@ enum class ShareAccessPolicy { AnyoneWithTransfer, } +enum class RelayMode { + Automatic, + StrictCustom, + CustomWithDirectFallback, + LocalOnly, +} + +data class RelaySettings( + val mode: RelayMode = RelayMode.Automatic, + val relayUrls: List = emptyList(), +) + +val RelayMode.usesCustomRelayUrls: Boolean + get() = this == RelayMode.StrictCustom || this == RelayMode.CustomWithDirectFallback + enum class TransferDirection { Send, Receive, @@ -102,6 +117,7 @@ enum class ReceiverDeliveryStatus { Refused, Expired, Completed, + Failed, Unknown, } @@ -142,7 +158,10 @@ interface CoreGateway { val state: StateFlow val signals: SharedFlow - suspend fun initialize(appDataDir: String): Result + suspend fun initialize( + appDataDir: String, + relaySettings: RelaySettings = RelaySettings(), + ): Result fun shutdown() suspend fun sharePath(path: String, transferName: String, senderName: String, accessPolicy: ShareAccessPolicy): Result suspend fun shareFileDescriptor( @@ -164,6 +183,7 @@ interface CoreGateway { suspend fun receiveWithOutputSink(ticket: String, outputSink: ReceiveOutputSink, receiverName: String): Result suspend fun receiveWithOutputSinkV2(ticket: String, outputSink: ReceiveOutputSinkV2, receiverName: String): Result suspend fun storageUsage(): Result + suspend fun clearTransferCache(): Result suspend fun receivedArtifacts(): Result> suspend fun cancel(transferId: ULong): Result suspend fun delete(transferId: ULong): Result diff --git a/shared/src/commonMain/kotlin/com/vnidrop/app/core/CoreRepository.kt b/shared/src/commonMain/kotlin/com/vnidrop/app/core/CoreRepository.kt index e1cc450..46689e7 100644 --- a/shared/src/commonMain/kotlin/com/vnidrop/app/core/CoreRepository.kt +++ b/shared/src/commonMain/kotlin/com/vnidrop/app/core/CoreRepository.kt @@ -16,6 +16,8 @@ import kotlinx.coroutines.withContext import kotlin.random.Random import uniffi.vnidrop.CoreEvent import uniffi.vnidrop.CoreEventSink +import uniffi.vnidrop.CoreNetworkConfig +import uniffi.vnidrop.CoreRelayMode import uniffi.vnidrop.ReceiveOutputSink import uniffi.vnidrop.ReceiveOutputSinkV2 import uniffi.vnidrop.ReceiverRequest @@ -28,6 +30,8 @@ import uniffi.vnidrop.TicketInspection import uniffi.vnidrop.TransferMetadata import uniffi.vnidrop.TransferAccessMode import uniffi.vnidrop.VnidropCore +import uniffi.vnidrop.clearInactiveTransferCache +import uniffi.vnidrop.defaultCoreNetworkConfig class CoreRepository( private val dispatcher: CoroutineDispatcher = Dispatchers.IO, @@ -42,6 +46,9 @@ class CoreRepository( override val signals: SharedFlow = _signals.asSharedFlow() private var core: VnidropCore? = null + private var currentAppDataDir: String? = null + private var currentRelaySettings = RelaySettings() + private val lifecycleGate = CoreLifecycleGate() private val sink = object : CoreEventSink { override fun onEvent(event: CoreEvent) { @@ -60,16 +67,30 @@ class CoreRepository( } } - override suspend fun initialize(appDataDir: String): Result = runCore { - core?.shutdown() - core = VnidropCore.initialize(appDataDir, sink) - refreshSnapshot() - _state.update { it.copy(isInitialized = true) } - } + override suspend fun initialize(appDataDir: String, relaySettings: RelaySettings): Result = + runReconfiguration { + val previousCore = core + if (previousCore != null) { + val status = previousCore.status() + require(status.activeTransfers == 0UL && status.activeShares == 0UL) { + "Stop active transfers and shares before changing relay settings" + } + } + _state.update { it.copy(isInitialized = false, status = null) } + core = null + disposeCore(previousCore) + core = VnidropCore.initializeWithNetworkConfig(appDataDir, sink, relaySettings.toNative()) + currentAppDataDir = appDataDir + currentRelaySettings = relaySettings + refreshSnapshot(requireCore()) + _state.update { it.copy(isInitialized = true) } + } override fun shutdown() { - core?.shutdown() + val activeCore = core core = null + disposeCore(activeCore) + currentAppDataDir = null _state.value = CoreState() } @@ -84,7 +105,7 @@ class CoreRepository( ShareSource( kind = SourceKind.PATH, value = path, - displayName = path.substringAfterLast('/').ifBlank { null }, + displayName = null, isDirectory = false, ), ), @@ -114,37 +135,37 @@ class CoreRepository( accessPolicy = accessPolicy, ) - override suspend fun inspectTicket(ticket: String): Result = runCore { - requireCore().inspectTicket(ticket).toModel().also { inspection -> + override suspend fun inspectTicket(ticket: String): Result = runCore { activeCore -> + activeCore.inspectTicket(ticket).toModel().also { inspection -> _state.update { it.copy(lastInspection = inspection) } } } - override suspend fun receive(ticket: String, outputDir: String, receiverName: String): Result = runCore { - requireCore().receive(ticket, outputDir, receiverName.ifBlank { null }) - refreshSnapshot() + override suspend fun receive(ticket: String, outputDir: String, receiverName: String): Result = runCore { activeCore -> + activeCore.receive(ticket, outputDir, receiverName.ifBlank { null }) + refreshSnapshot(activeCore) } override suspend fun receiveWithOutputSink( ticket: String, outputSink: ReceiveOutputSink, receiverName: String, - ): Result = runCore { - requireCore().receiveWithOutputSink(ticket, outputSink, receiverName.ifBlank { null }) - refreshSnapshot() + ): Result = runCore { activeCore -> + activeCore.receiveWithOutputSink(ticket, outputSink, receiverName.ifBlank { null }) + refreshSnapshot(activeCore) } override suspend fun receiveWithOutputSinkV2( ticket: String, outputSink: ReceiveOutputSinkV2, receiverName: String, - ): Result = runCore { - requireCore().receiveWithOutputSinkV2(ticket, outputSink, receiverName.ifBlank { null }) - refreshSnapshot() + ): Result = runCore { activeCore -> + activeCore.receiveWithOutputSinkV2(ticket, outputSink, receiverName.ifBlank { null }) + refreshSnapshot(activeCore) } - override suspend fun storageUsage(): Result = runCore { - val usage = requireCore().storageUsage() + override suspend fun storageUsage(): Result = runCore { activeCore -> + val usage = activeCore.storageUsage() CoreStorageUsageModel( blobStoreBytes = usage.blobStoreBytes, databaseBytes = usage.databaseBytes, @@ -154,8 +175,40 @@ class CoreRepository( ) } - override suspend fun receivedArtifacts(): Result> = runCore { - requireCore().listReceivedArtifacts().map { artifact -> + override suspend fun clearTransferCache(): Result = runReconfiguration { + val activeCore = requireCore() + val status = activeCore.status() + require(status.activeTransfers == 0UL && status.activeShares == 0UL) { + "Wait for active transfers and shares to finish before clearing the transfer cache" + } + val appDataDir = requireNotNull(currentAppDataDir) { "Core data directory is unavailable" } + val relaySettings = currentRelaySettings + _state.update { it.copy(isInitialized = false, status = null) } + core = null + disposeCore(activeCore) + var reclaimed = 0UL + try { + reclaimed = clearInactiveTransferCache(appDataDir) + } finally { + core = VnidropCore.initializeWithNetworkConfig(appDataDir, sink, relaySettings.toNative()) + refreshSnapshot(requireCore()) + _state.update { it.copy(isInitialized = true) } + } + reclaimed + } + + private fun disposeCore(activeCore: VnidropCore?) { + if (activeCore == null) return + try { + activeCore.shutdown() + } finally { + // UniFFI owns the Rust Arc; explicit disposal releases Windows file handles before cache deletion. + activeCore.close() + } + } + + override suspend fun receivedArtifacts(): Result> = runCore { activeCore -> + activeCore.listReceivedArtifacts().map { artifact -> ReceivedArtifactModel( id = artifact.id, locator = artifact.locator, @@ -165,47 +218,47 @@ class CoreRepository( } } - override suspend fun cancel(transferId: ULong): Result = runCore { - requireCore().cancelTransfer(transferId) - refreshSnapshot() + override suspend fun cancel(transferId: ULong): Result = runCore { activeCore -> + activeCore.cancelTransfer(transferId) + refreshSnapshot(activeCore) } - override suspend fun delete(transferId: ULong): Result = runCore { - requireCore().deleteTransfer(transferId) - refreshSnapshot() + override suspend fun delete(transferId: ULong): Result = runCore { activeCore -> + activeCore.deleteTransfer(transferId) + refreshSnapshot(activeCore) _signals.tryEmit(CoreSignal.ApprovalChanged(transferId)) _signals.tryEmit(CoreSignal.ReceiverHistoryChanged(transferId)) } - override suspend fun clearReceiveHistory(): Result = runCore { - val deleted = requireCore().deleteReceiveHistory() - refreshSnapshot() + override suspend fun clearReceiveHistory(): Result = runCore { activeCore -> + val deleted = activeCore.deleteReceiveHistory() + refreshSnapshot(activeCore) deleted } - override suspend fun receiverRequests(transferId: ULong): Result> = runCore { - requireCore().listReceiverRequests(transferId).map(ReceiverRequest::toModel) + override suspend fun receiverRequests(transferId: ULong): Result> = runCore { activeCore -> + activeCore.listReceiverRequests(transferId).map(ReceiverRequest::toModel) } override suspend fun respondReceiverRequest( requestId: String, accepted: Boolean, reason: String?, - ): Result = runCore { - requireCore().respondReceiverRequest(requestId, accepted, reason) + ): Result = runCore { activeCore -> + activeCore.respondReceiverRequest(requestId, accepted, reason) } - override suspend fun refresh(): Result = runCore { refreshSnapshot() } + override suspend fun refresh(): Result = runCore(::refreshSnapshot) override suspend fun shareSources( sources: List, transferName: String, senderName: String, accessPolicy: ShareAccessPolicy, - ): Result = runCore { + ): Result = runCore { activeCore -> require(sources.isNotEmpty()) { "Select at least one file to share" } withPlatformPathAccess(sources) { - requireCore().shareFiles( + activeCore.shareFiles( sources = sources, metadata = ShareMetadataInput( transferId = nextTransferId(), @@ -215,7 +268,7 @@ class CoreRepository( ), ).toModel() }.also { share -> - refreshSnapshot() + refreshSnapshot(activeCore) _state.update { it.copy(lastShare = share) } } } @@ -232,8 +285,7 @@ class CoreRepository( } } - private fun refreshSnapshot() { - val activeCore = requireCore() + private fun refreshSnapshot(activeCore: VnidropCore) { val status = activeCore.status() _state.update { it.copy( @@ -244,10 +296,25 @@ class CoreRepository( } } - private suspend fun runCore(block: suspend () -> T): Result = + private suspend fun runCore(block: suspend (VnidropCore) -> T): Result = withContext(dispatcher) { try { - Result.success(block()) + Result.success( + lifecycleGate.withCall( + capture = ::requireCore, + block = block, + ), + ) + } catch (error: Throwable) { + if (error is CancellationException) throw error + Result.failure(error) + } + } + + private suspend fun runReconfiguration(block: suspend () -> T): Result = + withContext(dispatcher) { + try { + Result.success(lifecycleGate.withReconfiguration(block)) } catch (error: Throwable) { if (error is CancellationException) throw error Result.failure(error) @@ -263,6 +330,22 @@ class CoreRepository( } } +private fun RelaySettings.toNative(): CoreNetworkConfig = when (mode) { + RelayMode.Automatic -> defaultCoreNetworkConfig() + RelayMode.StrictCustom -> CoreNetworkConfig( + mode = CoreRelayMode.STRICT_CUSTOM, + relayUrls = relayUrls, + ) + RelayMode.CustomWithDirectFallback -> CoreNetworkConfig( + mode = CoreRelayMode.CUSTOM_WITH_DIRECT_FALLBACK, + relayUrls = relayUrls, + ) + RelayMode.LocalOnly -> CoreNetworkConfig( + mode = CoreRelayMode.LOCAL_ONLY, + relayUrls = emptyList(), + ) +} + private fun CoreEvent.toModel(): CoreEventModel = CoreEventModel( id = id, timestamp = timestamp, @@ -361,6 +444,7 @@ private fun ReceiverRequest.toModel(): ReceiverRequestModel = ReceiverRequestMod "refused" -> ReceiverDeliveryStatus.Refused "expired" -> ReceiverDeliveryStatus.Expired "completed" -> ReceiverDeliveryStatus.Completed + "failed" -> ReceiverDeliveryStatus.Failed else -> ReceiverDeliveryStatus.Unknown }, reason = reason, diff --git a/shared/src/commonMain/kotlin/com/vnidrop/app/core/FileSystemService.kt b/shared/src/commonMain/kotlin/com/vnidrop/app/core/FileSystemService.kt index 537f0b6..50355d4 100644 --- a/shared/src/commonMain/kotlin/com/vnidrop/app/core/FileSystemService.kt +++ b/shared/src/commonMain/kotlin/com/vnidrop/app/core/FileSystemService.kt @@ -40,7 +40,7 @@ interface FileSystemService { if (supportsCustomReceiveFolders) configuredFolder else defaultReceiveFolder() suspend fun validateReceiveFolder(folder: ReceiveFolder): FolderAccessStatus suspend fun inspectReceivedArtifacts(artifacts: List): ReceivedStorageInspection - suspend fun temporaryUsage(): ULong + suspend fun temporaryUsage(receiveFolder: ReceiveFolder): ULong fun createReceiveOutputSink(folder: ReceiveFolder): ReceiveOutputSinkV2? fun canRevealReceiveFolder(folder: ReceiveFolder): Boolean = false suspend fun revealReceiveFolder(folder: ReceiveFolder): Result = diff --git a/shared/src/commonMain/kotlin/com/vnidrop/app/feature/app/AppViewModel.kt b/shared/src/commonMain/kotlin/com/vnidrop/app/feature/app/AppViewModel.kt index 810a6dc..a90a163 100644 --- a/shared/src/commonMain/kotlin/com/vnidrop/app/feature/app/AppViewModel.kt +++ b/shared/src/commonMain/kotlin/com/vnidrop/app/feature/app/AppViewModel.kt @@ -15,6 +15,7 @@ import com.vnidrop.app.ui.theme.ThemeMode import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch @@ -46,7 +47,8 @@ class AppViewModel( AppLogger.info("lifecycle", "app started", mapOf("platform" to environment.name)) diagnostics?.record("app_open", mapOf("platform" to environment.name, "version" to environment.appVersion)) viewModelScope.launch { - repository.initialize(environment.defaultCoreDataDir).onFailure(messages::error) + val relaySettings = preferencesRepository.preferences.first().relaySettings + repository.initialize(environment.defaultCoreDataDir, relaySettings).onFailure(messages::error) } viewModelScope.launch { preferencesRepository.preferences.collect { preferences -> diff --git a/shared/src/commonMain/kotlin/com/vnidrop/app/feature/send/SendScreen.kt b/shared/src/commonMain/kotlin/com/vnidrop/app/feature/send/SendScreen.kt index a49c2a7..b46a171 100644 --- a/shared/src/commonMain/kotlin/com/vnidrop/app/feature/send/SendScreen.kt +++ b/shared/src/commonMain/kotlin/com/vnidrop/app/feature/send/SendScreen.kt @@ -12,6 +12,7 @@ import com.vnidrop.app.core.CoreState import com.vnidrop.app.core.ReceiverDeliveryStatus import com.vnidrop.app.core.ShareAccessPolicy import com.vnidrop.app.core.TransferDirection +import com.vnidrop.app.core.TransferStatus import com.vnidrop.app.ui.components.AdaptiveDrawer import com.vnidrop.app.ui.state.WindowClass @@ -96,7 +97,12 @@ fun SendScreen( } } - if (selectedTransfer != null && state.detailPanel != null) { + val canShowDetailPanel = selectedTransfer != null && when (state.detailPanel) { + TransferDetailPanel.Share -> selectedTransfer.status in setOf(TransferStatus.Importing, TransferStatus.Sharing) + TransferDetailPanel.Activity, TransferDetailPanel.Receivers -> true + null -> false + } + if (selectedTransfer != null && state.detailPanel != null && canShowDetailPanel) { AdaptiveDrawer(windowClass = windowClass, onDismissRequest = onCloseDetailPanel) { when (state.detailPanel) { TransferDetailPanel.Activity -> TransferActivityPanel(coreState.events, selectedTransfer.transferId) diff --git a/shared/src/commonMain/kotlin/com/vnidrop/app/feature/send/SendViewModel.kt b/shared/src/commonMain/kotlin/com/vnidrop/app/feature/send/SendViewModel.kt index 9a2db5f..8cfc7a1 100644 --- a/shared/src/commonMain/kotlin/com/vnidrop/app/feature/send/SendViewModel.kt +++ b/shared/src/commonMain/kotlin/com/vnidrop/app/feature/send/SendViewModel.kt @@ -209,7 +209,12 @@ class SendViewModel( ) } fun openActivity() = _state.update { it.copy(detailPanel = TransferDetailPanel.Activity) } - fun openShare() = _state.update { it.copy(detailPanel = TransferDetailPanel.Share) } + fun openShare() { + val selectedId = _state.value.selectedTransferId ?: return + val selected = coreState.value.transfers.firstOrNull { it.transferId == selectedId } ?: return + if (selected.status !in setOf(TransferStatus.Importing, TransferStatus.Sharing)) return + _state.update { it.copy(detailPanel = TransferDetailPanel.Share) } + } fun openReceivers() { val transferId = _state.value.selectedTransferId ?: return _state.update { it.copy(detailPanel = TransferDetailPanel.Receivers) } diff --git a/shared/src/commonMain/kotlin/com/vnidrop/app/feature/send/TransferDetails.kt b/shared/src/commonMain/kotlin/com/vnidrop/app/feature/send/TransferDetails.kt index d6d3d75..422db5d 100644 --- a/shared/src/commonMain/kotlin/com/vnidrop/app/feature/send/TransferDetails.kt +++ b/shared/src/commonMain/kotlin/com/vnidrop/app/feature/send/TransferDetails.kt @@ -46,6 +46,7 @@ import com.vnidrop.app.core.ReceiverDeliveryStatus import com.vnidrop.app.core.ReceiverRequestModel import com.vnidrop.app.core.ShareAccessPolicy import com.vnidrop.app.core.Transfer +import com.vnidrop.app.core.TransferStatus import com.vnidrop.app.ui.components.AppCard import com.vnidrop.app.ui.components.DestructiveButton import com.vnidrop.app.ui.components.PrimaryButton @@ -60,12 +61,19 @@ import com.vnidrop.app.ui.state.progressForReceiver import com.vnidrop.app.ui.theme.LocalVniDropColors import org.jetbrains.compose.resources.decodeToImageBitmap import org.jetbrains.compose.resources.stringResource +import kotlinx.coroutines.CancellationException import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import vnidrop.shared.generated.resources.* enum class InvitationAction { Export, Share, Nfc } +private sealed interface TransferQrRenderState { + data object Loading : TransferQrRenderState + data object Unavailable : TransferQrRenderState + data class Ready(val bitmap: androidx.compose.ui.graphics.ImageBitmap) : TransferQrRenderState +} + @Composable internal fun TransferDetails( transfer: Transfer, @@ -122,12 +130,29 @@ internal fun TransferDetails( count = pendingReceivers + completedReceivers, onClick = onReceivers, ) - HorizontalDivider(color = LocalVniDropColors.current.borderDefault) - DetailDestination( - title = stringResource(Res.string.transfer_share_title), - description = stringResource(Res.string.transfer_share_description), - onClick = onShare, - ) + when (transfer.status) { + TransferStatus.Sharing -> { + HorizontalDivider(color = LocalVniDropColors.current.borderDefault) + DetailDestination( + title = stringResource(Res.string.transfer_share_title), + description = stringResource(Res.string.transfer_share_description), + onClick = onShare, + ) + } + TransferStatus.Importing -> { + HorizontalDivider(color = LocalVniDropColors.current.borderDefault) + DetailDestination( + title = stringResource(Res.string.transfer_share_title), + description = stringResource(Res.string.transfer_event_preparing), + ) + } + TransferStatus.Receiving, + TransferStatus.Done, + TransferStatus.Failed, + TransferStatus.Cancelled, + TransferStatus.Stopped, + -> Unit + } } } } @@ -144,9 +169,12 @@ private fun receiversDescription(pending: Int, completed: Int): String = when { } @Composable -private fun DetailDestination(title: String, description: String, count: Int? = null, onClick: () -> Unit) { +private fun DetailDestination(title: String, description: String, count: Int? = null, onClick: (() -> Unit)? = null) { Row( - Modifier.fillMaxWidth().clickable(onClick = onClick).padding(16.dp), + Modifier + .fillMaxWidth() + .then(if (onClick == null) Modifier else Modifier.clickable(onClick = onClick)) + .padding(16.dp), verticalAlignment = Alignment.CenterVertically, ) { Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(3.dp)) { @@ -157,7 +185,9 @@ private fun DetailDestination(title: String, description: String, count: Int? = Text(count.toString(), modifier = Modifier.background(LocalVniDropColors.current.backgroundSelection, RoundedCornerShape(20.dp)).padding(horizontal = 9.dp, vertical = 3.dp)) Spacer(Modifier.width(8.dp)) } - PlatformIcon(AppIcon.ChevronRight, null, tint = LocalVniDropColors.current.foregroundLighter, modifier = Modifier.size(18.dp)) + if (onClick != null) { + PlatformIcon(AppIcon.ChevronRight, null, tint = LocalVniDropColors.current.foregroundLighter, modifier = Modifier.size(18.dp)) + } } } @@ -240,41 +270,71 @@ internal fun TransferSharePanel( DisposableEffect(actions) { onDispose(actions::cancelNfcWrite) } val ticket = transfer.ticket PanelContainer(stringResource(Res.string.transfer_share_title)) { + if (transfer.status == TransferStatus.Importing) { + Text(stringResource(Res.string.transfer_event_preparing), color = LocalVniDropColors.current.foregroundLighter) + return@PanelContainer + } + if (transfer.status != TransferStatus.Sharing) return@PanelContainer if (ticket == null) { Text(stringResource(Res.string.transfer_event_preparing), color = LocalVniDropColors.current.foregroundLighter) return@PanelContainer } - val renderedBitmap by produceState(qrBitmap, ticket, qrBitmap) { - if (value == null) { - value = withContext(Dispatchers.Default) { - runCatching { buildTransferQrCode(ticket).renderToBytes().decodeToImageBitmap() }.getOrNull() + val qrRenderState by produceState( + initialValue = qrBitmap?.let(TransferQrRenderState::Ready) ?: TransferQrRenderState.Loading, + key1 = ticket, + key2 = qrBitmap, + ) { + if (qrBitmap != null) { + value = TransferQrRenderState.Ready(qrBitmap) + return@produceState + } + value = try { + val bitmap = withContext(Dispatchers.Default) { + buildTransferQrCode(ticket).renderToBytes().decodeToImageBitmap() } - value?.let { onQrRendered(ticket, it) } + onQrRendered(ticket, bitmap) + TransferQrRenderState.Ready(bitmap) + } catch (error: CancellationException) { + throw error + } catch (_: Throwable) { + TransferQrRenderState.Unavailable } } - val renderedQr = renderedBitmap - Surface( - modifier = Modifier.align(Alignment.CenterHorizontally).size(268.dp), - shape = RoundedCornerShape(18.dp), - color = Color.White, - ) { - if (renderedQr != null) { + when (val qrState = qrRenderState) { + is TransferQrRenderState.Ready -> Surface( + modifier = Modifier.align(Alignment.CenterHorizontally).size(268.dp), + shape = RoundedCornerShape(18.dp), + color = Color.White, + ) { Image( - bitmap = renderedQr, + bitmap = qrState.bitmap, contentDescription = null, modifier = Modifier.padding(14.dp).fillMaxSize(), filterQuality = FilterQuality.None, ) - } else { + } + TransferQrRenderState.Loading -> Surface( + modifier = Modifier.align(Alignment.CenterHorizontally).size(268.dp), + shape = RoundedCornerShape(18.dp), + color = Color.White, + ) { Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) { CircularProgressIndicator() } } + TransferQrRenderState.Unavailable -> Text( + stringResource(Res.string.transfer_qr_unavailable), + modifier = Modifier.align(Alignment.CenterHorizontally), + color = LocalVniDropColors.current.foregroundLighter, + style = MaterialTheme.typography.bodySmall, + ) + } + if (qrRenderState is TransferQrRenderState.Ready) { + Text( + stringResource(Res.string.transfer_scan_qr), + modifier = Modifier.align(Alignment.CenterHorizontally), + color = LocalVniDropColors.current.foregroundLighter, + style = MaterialTheme.typography.bodySmall, + ) } - Text( - stringResource(Res.string.transfer_scan_qr), - modifier = Modifier.align(Alignment.CenterHorizontally), - color = LocalVniDropColors.current.foregroundLighter, - style = MaterialTheme.typography.bodySmall, - ) if (actions.nfcAvailability != NfcShareAvailability.Hidden) { var writingNfc by remember(ticket) { mutableStateOf(false) } SecondaryButton( @@ -349,13 +409,15 @@ private fun receiverStatusText(status: ReceiverDeliveryStatus) = stringResource( ReceiverDeliveryStatus.Refused -> Res.string.transfer_receiver_refused ReceiverDeliveryStatus.Expired -> Res.string.transfer_receiver_expired ReceiverDeliveryStatus.Completed -> Res.string.transfer_receiver_completed + ReceiverDeliveryStatus.Failed -> Res.string.transfer_receiver_failed ReceiverDeliveryStatus.Unknown -> Res.string.transfer_receiver_unknown }) @Composable private fun receiverStatusColor(status: ReceiverDeliveryStatus) = when (status) { ReceiverDeliveryStatus.Completed -> LocalVniDropColors.current.brandDefault - ReceiverDeliveryStatus.Refused, ReceiverDeliveryStatus.Expired -> LocalVniDropColors.current.destructiveDefault + ReceiverDeliveryStatus.Refused, ReceiverDeliveryStatus.Expired, ReceiverDeliveryStatus.Failed -> + LocalVniDropColors.current.destructiveDefault else -> LocalVniDropColors.current.foregroundLighter } diff --git a/shared/src/commonMain/kotlin/com/vnidrop/app/feature/settings/NetworkSettings.kt b/shared/src/commonMain/kotlin/com/vnidrop/app/feature/settings/NetworkSettings.kt new file mode 100644 index 0000000..12a87e6 --- /dev/null +++ b/shared/src/commonMain/kotlin/com/vnidrop/app/feature/settings/NetworkSettings.kt @@ -0,0 +1,315 @@ +package com.vnidrop.app.feature.settings + +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.foundation.text.selection.SelectionContainer +import androidx.compose.material3.IconButton +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.runtime.Composable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.unit.dp +import com.vnidrop.app.core.RelayMode +import com.vnidrop.app.core.usesCustomRelayUrls +import com.vnidrop.app.ui.components.PrimaryButton +import com.vnidrop.app.ui.icons.AppIcon +import com.vnidrop.app.ui.icons.PlatformIcon +import com.vnidrop.app.ui.theme.LocalVniDropColors +import org.jetbrains.compose.resources.stringResource +import vnidrop.shared.generated.resources.Res +import vnidrop.shared.generated.resources.approval_endpoint_id +import vnidrop.shared.generated.resources.relay_add_url +import vnidrop.shared.generated.resources.relay_apply +import vnidrop.shared.generated.resources.relay_apply_active_transfers +import vnidrop.shared.generated.resources.relay_apply_failed +import vnidrop.shared.generated.resources.relay_apply_restart_description +import vnidrop.shared.generated.resources.relay_applying +import vnidrop.shared.generated.resources.relay_custom_urls_help +import vnidrop.shared.generated.resources.relay_custom_urls_label +import vnidrop.shared.generated.resources.relay_mode_automatic +import vnidrop.shared.generated.resources.relay_mode_automatic_description +import vnidrop.shared.generated.resources.relay_mode_custom +import vnidrop.shared.generated.resources.relay_mode_custom_description +import vnidrop.shared.generated.resources.relay_mode_custom_direct_fallback +import vnidrop.shared.generated.resources.relay_mode_custom_direct_fallback_description +import vnidrop.shared.generated.resources.relay_mode_local_only +import vnidrop.shared.generated.resources.relay_mode_local_only_description +import vnidrop.shared.generated.resources.relay_privacy_description +import vnidrop.shared.generated.resources.relay_remove_url +import vnidrop.shared.generated.resources.relay_restore_failed +import vnidrop.shared.generated.resources.relay_strict_warning +import vnidrop.shared.generated.resources.relay_validation_duplicate_url +import vnidrop.shared.generated.resources.relay_validation_https_required +import vnidrop.shared.generated.resources.relay_validation_invalid_url +import vnidrop.shared.generated.resources.relay_validation_missing_url +import vnidrop.shared.generated.resources.relay_validation_too_many_urls +import vnidrop.shared.generated.resources.settings_network_title + +@Composable +internal fun NetworkSettings( + state: SettingsState, + onModeChanged: (RelayMode) -> Unit, + onUrlChanged: (Int, String) -> Unit, + onAddUrl: () -> Unit, + onRemoveUrl: (Int) -> Unit, + onApply: () -> Unit, + onBack: () -> Unit, + showBack: Boolean, +) { + val colors = LocalVniDropColors.current + Column(verticalArrangement = Arrangement.spacedBy(16.dp)) { + SettingsTopBar(stringResource(Res.string.settings_network_title), onBack, showBack) + SettingsGroup { + RelayModeRow( + icon = AppIcon.Globe, + title = stringResource(Res.string.relay_mode_automatic), + description = stringResource(Res.string.relay_mode_automatic_description), + selected = state.relayMode == RelayMode.Automatic, + enabled = !state.isApplyingRelaySettings, + onClick = { onModeChanged(RelayMode.Automatic) }, + ) + SettingsDivider() + RelayModeRow( + icon = AppIcon.Shield, + title = stringResource(Res.string.relay_mode_custom), + description = stringResource(Res.string.relay_mode_custom_description), + selected = state.relayMode == RelayMode.StrictCustom, + enabled = !state.isApplyingRelaySettings, + onClick = { onModeChanged(RelayMode.StrictCustom) }, + ) + SettingsDivider() + RelayModeRow( + icon = AppIcon.Radio, + title = stringResource(Res.string.relay_mode_custom_direct_fallback), + description = stringResource(Res.string.relay_mode_custom_direct_fallback_description), + selected = state.relayMode == RelayMode.CustomWithDirectFallback, + enabled = !state.isApplyingRelaySettings, + onClick = { onModeChanged(RelayMode.CustomWithDirectFallback) }, + ) + SettingsDivider() + RelayModeRow( + icon = AppIcon.CloudOff, + title = stringResource(Res.string.relay_mode_local_only), + description = stringResource(Res.string.relay_mode_local_only_description), + selected = state.relayMode == RelayMode.LocalOnly, + enabled = !state.isApplyingRelaySettings, + onClick = { onModeChanged(RelayMode.LocalOnly) }, + ) + } + Text( + stringResource(Res.string.relay_privacy_description), + color = colors.foregroundLighter, + style = MaterialTheme.typography.bodySmall, + ) + state.endpointId?.takeIf(String::isNotBlank)?.let { endpointId -> + SelectionContainer { + Text( + stringResource(Res.string.approval_endpoint_id, endpointId), + color = colors.foregroundLighter, + style = MaterialTheme.typography.bodySmall, + ) + } + } + if (state.relayMode.usesCustomRelayUrls) { + Text( + stringResource(Res.string.relay_custom_urls_label), + style = MaterialTheme.typography.titleSmall, + fontWeight = FontWeight.SemiBold, + ) + SettingsGroup { + state.relayUrls.forEachIndexed { index, url -> + RelayUrlRow( + value = url, + error = relayUrlErrorText(state.relayInputError, index), + enabled = !state.isApplyingRelaySettings, + onValueChange = { onUrlChanged(index, it) }, + onRemove = { onRemoveUrl(index) }, + ) + if (index < state.relayUrls.lastIndex) { + SettingsDivider(startPadding = 14.dp) + } + } + if (state.relayUrls.isNotEmpty()) { + SettingsDivider(startPadding = 14.dp) + } + TextButton( + onClick = onAddUrl, + enabled = state.relayUrls.size < MaximumRelayUrls && !state.isApplyingRelaySettings, + modifier = Modifier.padding(horizontal = 6.dp, vertical = 2.dp), + ) { + PlatformIcon(AppIcon.Add, contentDescription = null, modifier = Modifier.size(18.dp)) + Spacer(Modifier.width(8.dp)) + Text(stringResource(Res.string.relay_add_url)) + } + } + Text( + stringResource(Res.string.relay_custom_urls_help), + color = colors.foregroundLighter, + style = MaterialTheme.typography.bodySmall, + ) + if (state.relayMode == RelayMode.StrictCustom) { + Text( + stringResource(Res.string.relay_strict_warning), + color = colors.foregroundLight, + style = MaterialTheme.typography.bodySmall, + fontWeight = FontWeight.Medium, + ) + } + } + relayGlobalErrorText(state)?.let { error -> + Text( + error, + color = colors.destructiveDefault, + style = MaterialTheme.typography.bodySmall, + fontWeight = FontWeight.Medium, + ) + } + Text( + stringResource(Res.string.relay_apply_restart_description), + color = colors.foregroundLighter, + style = MaterialTheme.typography.bodySmall, + ) + PrimaryButton( + text = stringResource( + if (state.isApplyingRelaySettings) Res.string.relay_applying else Res.string.relay_apply, + ), + onClick = onApply, + modifier = Modifier.fillMaxWidth(), + enabled = state.hasRelaySettingsChanges && + !state.isApplyingRelaySettings && + !state.hasActiveNetworkWork, + ) + } +} + +@Composable +private fun RelayModeRow( + icon: AppIcon, + title: String, + description: String, + selected: Boolean, + enabled: Boolean, + onClick: () -> Unit, +) { + SettingsRow( + icon = icon, + title = title, + subtitle = description, + selected = selected, + onClick = onClick.takeIf { enabled }, + showsDisclosure = false, + trailing = if (selected) { + { + PlatformIcon( + AppIcon.Check, + contentDescription = null, + tint = LocalVniDropColors.current.brandLink, + modifier = Modifier.size(20.dp), + ) + } + } else { + null + }, + ) +} + +@Composable +private fun RelayUrlRow( + value: String, + error: String?, + enabled: Boolean, + onValueChange: (String) -> Unit, + onRemove: () -> Unit, +) { + val colors = LocalVniDropColors.current + Row( + modifier = Modifier + .fillMaxWidth() + .padding(start = 14.dp, end = 6.dp, top = 10.dp, bottom = 10.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + OutlinedTextField( + value = value, + onValueChange = onValueChange, + modifier = Modifier.weight(1f), + enabled = enabled, + singleLine = true, + isError = error != null, + placeholder = { Text("https://relay.example.com") }, + supportingText = error?.let { + { + Text(it, color = colors.destructiveDefault) + } + }, + shape = RoundedCornerShape(8.dp), + ) + IconButton(onClick = onRemove, enabled = enabled) { + PlatformIcon( + AppIcon.Delete, + contentDescription = stringResource(Res.string.relay_remove_url), + tint = colors.destructiveDefault, + ) + } + } +} + +@Composable +private fun relayUrlErrorText(error: RelaySettingsInputError?, index: Int): String? = when (error) { + is RelaySettingsInputError.HttpsRequired -> if (error.line == index + 1) { + stringResource(Res.string.relay_validation_https_required, error.line) + } else { + null + } + is RelaySettingsInputError.InvalidUrl -> if (error.line == index + 1) { + stringResource(Res.string.relay_validation_invalid_url, error.line) + } else { + null + } + is RelaySettingsInputError.DuplicateUrl -> if (error.line == index + 1) { + stringResource(Res.string.relay_validation_duplicate_url, error.line) + } else { + null + } + RelaySettingsInputError.MissingUrl, + is RelaySettingsInputError.TooManyUrls, + null, + -> null +} + +@Composable +private fun relayGlobalErrorText(state: SettingsState): String? { + if (state.hasActiveNetworkWork || state.relayApplyError == RelaySettingsApplyError.ActiveTransfers) { + return stringResource(Res.string.relay_apply_active_transfers) + } + state.relayInputError?.let { error -> + return when (error) { + RelaySettingsInputError.MissingUrl -> stringResource(Res.string.relay_validation_missing_url) + is RelaySettingsInputError.TooManyUrls -> stringResource( + Res.string.relay_validation_too_many_urls, + error.maximum, + ) + is RelaySettingsInputError.HttpsRequired, + is RelaySettingsInputError.InvalidUrl, + is RelaySettingsInputError.DuplicateUrl, + -> null + } + } + return when (state.relayApplyError) { + RelaySettingsApplyError.ApplyFailed -> stringResource(Res.string.relay_apply_failed) + RelaySettingsApplyError.RestoreFailed -> stringResource(Res.string.relay_restore_failed) + RelaySettingsApplyError.ActiveTransfers, + null, + -> null + } +} diff --git a/shared/src/commonMain/kotlin/com/vnidrop/app/feature/settings/RelaySettingsValidation.kt b/shared/src/commonMain/kotlin/com/vnidrop/app/feature/settings/RelaySettingsValidation.kt new file mode 100644 index 0000000..c41e211 --- /dev/null +++ b/shared/src/commonMain/kotlin/com/vnidrop/app/feature/settings/RelaySettingsValidation.kt @@ -0,0 +1,148 @@ +package com.vnidrop.app.feature.settings + +import com.vnidrop.app.core.RelayMode +import com.vnidrop.app.core.RelaySettings +import com.vnidrop.app.core.usesCustomRelayUrls + +sealed interface RelaySettingsInputError { + data object MissingUrl : RelaySettingsInputError + data class TooManyUrls(val maximum: Int) : RelaySettingsInputError + data class HttpsRequired(val line: Int) : RelaySettingsInputError + data class InvalidUrl(val line: Int) : RelaySettingsInputError + data class DuplicateUrl(val line: Int) : RelaySettingsInputError +} + +data class RelaySettingsValidation( + val settings: RelaySettings? = null, + val error: RelaySettingsInputError? = null, +) + +fun validateRelaySettings( + mode: RelayMode, + relayUrls: List, + retainedUrls: List = emptyList(), +): RelaySettingsValidation { + if (!mode.usesCustomRelayUrls) { + return RelaySettingsValidation(RelaySettings(mode, retainedUrls)) + } + val lines = relayUrls + .mapIndexedNotNull { index, raw -> raw.trim().takeIf(String::isNotEmpty)?.let { index + 1 to it } } + .toList() + if (lines.isEmpty()) return RelaySettingsValidation(error = RelaySettingsInputError.MissingUrl) + if (lines.size > MaximumRelayUrls) { + return RelaySettingsValidation(error = RelaySettingsInputError.TooManyUrls(MaximumRelayUrls)) + } + + val normalized = mutableListOf() + for ((line, raw) in lines) { + when (val result = normalizeRelayUrl(raw)) { + RelayUrlResult.HttpsRequired -> { + return RelaySettingsValidation(error = RelaySettingsInputError.HttpsRequired(line)) + } + RelayUrlResult.Invalid -> { + return RelaySettingsValidation(error = RelaySettingsInputError.InvalidUrl(line)) + } + is RelayUrlResult.Valid -> { + if (result.url in normalized) { + return RelaySettingsValidation(error = RelaySettingsInputError.DuplicateUrl(line)) + } + normalized += result.url + } + } + } + return RelaySettingsValidation(RelaySettings(mode, normalized)) +} + +private sealed interface RelayUrlResult { + data object HttpsRequired : RelayUrlResult + data object Invalid : RelayUrlResult + data class Valid(val url: String) : RelayUrlResult +} + +private fun normalizeRelayUrl(raw: String): RelayUrlResult { + if (!raw.startsWith(HttpsPrefix, ignoreCase = true)) return RelayUrlResult.HttpsRequired + if (raw.encodeToByteArray().size > MaximumRelayUrlLength || raw.any { it.isWhitespace() || it.isISOControl() }) { + return RelayUrlResult.Invalid + } + val remainder = raw.substring(HttpsPrefix.length) + if (remainder.isEmpty() || '?' in remainder || '#' in remainder) return RelayUrlResult.Invalid + val authority = remainder.substringBefore('/') + val path = remainder.removePrefix(authority) + if (!isValidAuthority(authority) || path !in setOf("", "/")) return RelayUrlResult.Invalid + + val normalizedAuthority = if (authority.startsWith('[')) { + val closingBracket = authority.indexOf(']') + authority.substring(0, closingBracket + 1).lowercase() + authority.substring(closingBracket + 1) + } else { + val portSeparator = authority.lastIndexOf(':').takeIf { authority.count { char -> char == ':' } == 1 } + if (portSeparator == null) authority.lowercase() + else authority.substring(0, portSeparator).lowercase() + authority.substring(portSeparator) + } + return RelayUrlResult.Valid("$HttpsPrefix${normalizedAuthority.removeSuffix(":443")}") +} + +private fun isValidAuthority(authority: String): Boolean { + if (authority.isBlank() || '@' in authority) return false + if (authority.startsWith('[')) { + val closingBracket = authority.indexOf(']') + if (closingBracket <= 1) return false + val address = authority.substring(1, closingBracket) + if (!isValidIpv6Address(address)) return false + return isValidPortSuffix(authority.substring(closingBracket + 1)) + } + if (authority.count { it == ':' } > 1) return false + val host = authority.substringBeforeLast(':', authority) + val portSuffix = authority.removePrefix(host) + if (host.isBlank() || host.startsWith('.') || host.endsWith('.') || host.startsWith('-') || host.endsWith('-')) return false + if (host.any { !it.isLetterOrDigit() && it != '.' && it != '-' }) return false + return isValidPortSuffix(portSuffix) +} + +private fun isValidIpv6Address(address: String): Boolean { + if (address.isEmpty() || ":::" in address) return false + val compressionIndex = address.indexOf("::") + val hasCompression = compressionIndex >= 0 + if (hasCompression && address.indexOf("::", compressionIndex + 2) >= 0) return false + if (!hasCompression && (address.startsWith(':') || address.endsWith(':'))) return false + + val left = if (hasCompression) address.substring(0, compressionIndex) else address + val right = if (hasCompression) address.substring(compressionIndex + 2) else "" + val segments = buildList { + if (left.isNotEmpty()) addAll(left.split(':')) + if (right.isNotEmpty()) addAll(right.split(':')) + } + if (segments.any(String::isEmpty)) return false + + var addressUnits = 0 + for ((index, segment) in segments.withIndex()) { + if ('.' in segment) { + if (index != segments.lastIndex || !isValidIpv4Tail(segment)) return false + addressUnits += 2 + } else { + if (segment.length !in 1..4 || segment.any { !it.isHexDigit() }) return false + addressUnits += 1 + } + } + return if (hasCompression) addressUnits < 8 else addressUnits == 8 +} + +private fun isValidIpv4Tail(address: String): Boolean { + val octets = address.split('.') + return octets.size == 4 && octets.all { octet -> + octet.isNotEmpty() && octet.all(Char::isDigit) && octet.toIntOrNull() in 0..255 + } +} + +private fun Char.isHexDigit(): Boolean = + this in '0'..'9' || lowercaseChar() in 'a'..'f' + +private fun isValidPortSuffix(suffix: String): Boolean { + if (suffix.isEmpty()) return true + if (!suffix.startsWith(':')) return false + val port = suffix.drop(1).toIntOrNull() ?: return false + return port in 1..65535 +} + +private const val HttpsPrefix = "https://" +internal const val MaximumRelayUrls = 8 +private const val MaximumRelayUrlLength = 2_048 diff --git a/shared/src/commonMain/kotlin/com/vnidrop/app/feature/settings/SettingsOverview.kt b/shared/src/commonMain/kotlin/com/vnidrop/app/feature/settings/SettingsOverview.kt index e5e262a..61835b5 100644 --- a/shared/src/commonMain/kotlin/com/vnidrop/app/feature/settings/SettingsOverview.kt +++ b/shared/src/commonMain/kotlin/com/vnidrop/app/feature/settings/SettingsOverview.kt @@ -7,6 +7,7 @@ import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp +import com.vnidrop.app.core.RelayMode import com.vnidrop.app.ui.icons.AppIcon import com.vnidrop.app.ui.theme.ThemeMode import org.jetbrains.compose.resources.stringResource @@ -18,7 +19,12 @@ import vnidrop.shared.generated.resources.appearance_system_mode import vnidrop.shared.generated.resources.appearance_title import vnidrop.shared.generated.resources.notifications_title import vnidrop.shared.generated.resources.preferences_title +import vnidrop.shared.generated.resources.relay_mode_automatic +import vnidrop.shared.generated.resources.relay_mode_custom +import vnidrop.shared.generated.resources.relay_mode_custom_direct_fallback +import vnidrop.shared.generated.resources.relay_mode_local_only import vnidrop.shared.generated.resources.settings_title +import vnidrop.shared.generated.resources.settings_network_title import vnidrop.shared.generated.resources.storage_title @Composable @@ -64,7 +70,17 @@ internal fun SettingsOverview( selected = state.selectedSection == SettingsSection.Storage, onClick = { onSectionSelected(SettingsSection.Storage) }, ) - SettingsDivider() + } + SettingsGroup { + SettingsRow( + icon = AppIcon.Globe, + title = stringResource(Res.string.settings_network_title), + value = relayModeLabel(state.savedRelaySettings.mode), + selected = state.selectedSection == SettingsSection.Network, + onClick = { onSectionSelected(SettingsSection.Network) }, + ) + } + SettingsGroup { SettingsRow( icon = AppIcon.Info, title = stringResource(Res.string.about_title), @@ -76,6 +92,14 @@ internal fun SettingsOverview( } } +@Composable +private fun relayModeLabel(mode: RelayMode): String = when (mode) { + RelayMode.Automatic -> stringResource(Res.string.relay_mode_automatic) + RelayMode.StrictCustom -> stringResource(Res.string.relay_mode_custom) + RelayMode.CustomWithDirectFallback -> stringResource(Res.string.relay_mode_custom_direct_fallback) + RelayMode.LocalOnly -> stringResource(Res.string.relay_mode_local_only) +} + @Composable private fun themeModeLabel(mode: ThemeMode): String = when (mode) { ThemeMode.System -> stringResource(Res.string.appearance_system_mode) diff --git a/shared/src/commonMain/kotlin/com/vnidrop/app/feature/settings/SettingsRoute.kt b/shared/src/commonMain/kotlin/com/vnidrop/app/feature/settings/SettingsRoute.kt index 93c3bd7..16bbdd3 100644 --- a/shared/src/commonMain/kotlin/com/vnidrop/app/feature/settings/SettingsRoute.kt +++ b/shared/src/commonMain/kotlin/com/vnidrop/app/feature/settings/SettingsRoute.kt @@ -24,6 +24,11 @@ fun SettingsRoute(viewModel: SettingsViewModel, windowClass: WindowClass) { onSectionSelected = viewModel::selectSection, onUsernameChanged = viewModel::setUsername, onThemeModeChanged = viewModel::setThemeMode, + onRelayModeChanged = viewModel::setRelayMode, + onRelayUrlChanged = viewModel::setRelayUrl, + onAddRelayUrl = viewModel::addRelayUrl, + onRemoveRelayUrl = viewModel::removeRelayUrl, + onApplyRelaySettings = viewModel::applyRelaySettings, onChooseFolder = viewModel::chooseReceiveFolder, onResetFolder = viewModel::resetReceiveFolder, onNotificationsChanged = viewModel::setNotificationsEnabled, @@ -36,5 +41,6 @@ fun SettingsRoute(viewModel: SettingsViewModel, windowClass: WindowClass) { onBugIncludeLogsChanged = viewModel::setBugIncludeLogs, onSubmitBugReport = viewModel::submitBugReport, onDeleteAllTransfers = viewModel::deleteAllTransfers, + onClearTransferCache = viewModel::clearTransferCache, ) } diff --git a/shared/src/commonMain/kotlin/com/vnidrop/app/feature/settings/SettingsScreen.kt b/shared/src/commonMain/kotlin/com/vnidrop/app/feature/settings/SettingsScreen.kt index 35212a8..920f983 100644 --- a/shared/src/commonMain/kotlin/com/vnidrop/app/feature/settings/SettingsScreen.kt +++ b/shared/src/commonMain/kotlin/com/vnidrop/app/feature/settings/SettingsScreen.kt @@ -9,6 +9,7 @@ import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp import com.vnidrop.app.ui.state.WindowClass +import com.vnidrop.app.core.RelayMode import com.vnidrop.app.ui.theme.ThemeMode @Composable @@ -30,6 +31,12 @@ fun SettingsScreen( onBugIncludeLogsChanged: (Boolean) -> Unit, onSubmitBugReport: () -> Unit, onDeleteAllTransfers: () -> Unit = {}, + onClearTransferCache: () -> Unit = {}, + onRelayModeChanged: (RelayMode) -> Unit = {}, + onRelayUrlChanged: (Int, String) -> Unit = { _, _ -> }, + onAddRelayUrl: () -> Unit = {}, + onRemoveRelayUrl: (Int) -> Unit = {}, + onApplyRelaySettings: () -> Unit = {}, ) { if (windowClass == WindowClass.Desktop) { Row( @@ -42,6 +49,7 @@ fun SettingsScreen( Column(Modifier.weight(1f)) { SettingsSectionContent( state = state, + windowClass = windowClass, section = state.selectedSection.takeUnless { it == SettingsSection.Overview } ?: SettingsSection.Preferences, onBack = {}, showBack = false, @@ -60,6 +68,12 @@ fun SettingsScreen( onBugIncludeLogsChanged = onBugIncludeLogsChanged, onSubmitBugReport = onSubmitBugReport, onDeleteAllTransfers = onDeleteAllTransfers, + onClearTransferCache = onClearTransferCache, + onRelayModeChanged = onRelayModeChanged, + onRelayUrlChanged = onRelayUrlChanged, + onAddRelayUrl = onAddRelayUrl, + onRemoveRelayUrl = onRemoveRelayUrl, + onApplyRelaySettings = onApplyRelaySettings, ) } } @@ -68,6 +82,7 @@ fun SettingsScreen( SettingsSection.Overview -> SettingsOverview(state, onSectionSelected, largeTitle = true) else -> SettingsSectionContent( state = state, + windowClass = windowClass, section = state.selectedSection, onBack = { onSectionSelected( @@ -94,6 +109,12 @@ fun SettingsScreen( onBugIncludeLogsChanged = onBugIncludeLogsChanged, onSubmitBugReport = onSubmitBugReport, onDeleteAllTransfers = onDeleteAllTransfers, + onClearTransferCache = onClearTransferCache, + onRelayModeChanged = onRelayModeChanged, + onRelayUrlChanged = onRelayUrlChanged, + onAddRelayUrl = onAddRelayUrl, + onRemoveRelayUrl = onRemoveRelayUrl, + onApplyRelaySettings = onApplyRelaySettings, ) } } @@ -102,6 +123,7 @@ fun SettingsScreen( @Composable private fun SettingsSectionContent( state: SettingsState, + windowClass: WindowClass, section: SettingsSection, onBack: () -> Unit, showBack: Boolean, @@ -120,13 +142,36 @@ private fun SettingsSectionContent( onBugIncludeLogsChanged: (Boolean) -> Unit, onSubmitBugReport: () -> Unit, onDeleteAllTransfers: () -> Unit, + onClearTransferCache: () -> Unit, + onRelayModeChanged: (RelayMode) -> Unit, + onRelayUrlChanged: (Int, String) -> Unit, + onAddRelayUrl: () -> Unit, + onRemoveRelayUrl: (Int) -> Unit, + onApplyRelaySettings: () -> Unit, ) { when (section) { SettingsSection.Overview -> Unit SettingsSection.Preferences -> PreferencesSettings(state, onUsernameChanged, onChooseFolder, onResetFolder, onBack, showBack) SettingsSection.Appearance -> AppearanceSettings(state.themeMode, onThemeModeChanged, onBack, showBack) + SettingsSection.Network -> NetworkSettings( + state = state, + onModeChanged = onRelayModeChanged, + onUrlChanged = onRelayUrlChanged, + onAddUrl = onAddRelayUrl, + onRemoveUrl = onRemoveRelayUrl, + onApply = onApplyRelaySettings, + onBack = onBack, + showBack = showBack, + ) SettingsSection.Notifications -> NotificationSettings(state, onNotificationsChanged, onOpenNotificationSettings, onBack, showBack) - SettingsSection.Storage -> StorageSettings(state, onDeleteAllTransfers, onBack, showBack) + SettingsSection.Storage -> StorageSettings( + state, + windowClass, + onDeleteAllTransfers, + onClearTransferCache, + onBack, + showBack, + ) SettingsSection.About -> AboutSettings( state = state, onDiagnosticsChanged = onDiagnosticsChanged, diff --git a/shared/src/commonMain/kotlin/com/vnidrop/app/feature/settings/SettingsViewModel.kt b/shared/src/commonMain/kotlin/com/vnidrop/app/feature/settings/SettingsViewModel.kt index e3deea1..1bde443 100644 --- a/shared/src/commonMain/kotlin/com/vnidrop/app/feature/settings/SettingsViewModel.kt +++ b/shared/src/commonMain/kotlin/com/vnidrop/app/feature/settings/SettingsViewModel.kt @@ -7,8 +7,13 @@ import com.vnidrop.app.DeviceInfoProvider import com.vnidrop.app.PlatformEnvironment import com.vnidrop.app.core.FileSystemService import com.vnidrop.app.core.CoreGateway +import com.vnidrop.app.core.CoreLifecycleBusyException import com.vnidrop.app.core.FolderAccessStatus import com.vnidrop.app.core.ReceiveFolder +import com.vnidrop.app.core.RelayMode +import com.vnidrop.app.core.RelaySettings +import com.vnidrop.app.core.TransferStatus +import com.vnidrop.app.core.usesCustomRelayUrls import com.vnidrop.app.diagnostics.BugReportDraft import com.vnidrop.app.diagnostics.BugReportService import com.vnidrop.app.diagnostics.DiagnosticsBuildConfig @@ -43,17 +48,27 @@ import vnidrop.shared.generated.resources.notifications_enabled_message import vnidrop.shared.generated.resources.notifications_permission_denied import vnidrop.shared.generated.resources.notifications_settings_open_failed import vnidrop.shared.generated.resources.notifications_unsupported +import vnidrop.shared.generated.resources.relay_settings_applied +import vnidrop.shared.generated.resources.storage_transfer_cache_cleared +import vnidrop.shared.generated.resources.storage_transfers_deleted enum class SettingsSection { Overview, Preferences, Appearance, + Network, Notifications, Storage, About, BugReport, } +enum class RelaySettingsApplyError { + ActiveTransfers, + ApplyFailed, + RestoreFailed, +} + data class StorageBreakdown( val transferCacheBytes: ULong, val appDataBytes: ULong, @@ -74,6 +89,14 @@ data class SettingsState( val isValidatingFolder: Boolean = false, val supportsCustomReceiveFolders: Boolean = true, val themeMode: ThemeMode = ThemeMode.System, + val savedRelaySettings: RelaySettings = RelaySettings(), + val relayMode: RelayMode = RelayMode.Automatic, + val relayUrls: List = emptyList(), + val relayInputError: RelaySettingsInputError? = null, + val relayApplyError: RelaySettingsApplyError? = null, + val isApplyingRelaySettings: Boolean = false, + val hasActiveNetworkWork: Boolean = false, + val endpointId: String? = null, val notificationsEnabled: Boolean = false, val notificationPermission: NotificationPermission = NotificationPermission.NotDetermined, val diagnosticsEnabled: Boolean = false, @@ -90,7 +113,12 @@ data class SettingsState( val storage: StorageBreakdown? = null, val isCalculatingStorage: Boolean = false, val isDeletingTransfers: Boolean = false, -) + val isClearingTransferCache: Boolean = false, +) { + val hasRelaySettingsChanges: Boolean + get() = relayMode != savedRelaySettings.mode || + (relayMode.usesCustomRelayUrls && relayUrls != savedRelaySettings.relayUrls) +} sealed interface SettingsEffect { data object OpenReceiveFolderPicker : SettingsEffect @@ -121,6 +149,7 @@ class SettingsViewModel( private var enableNotificationsAfterSettings = false private var usernamePersistJob: Job? = null private var hasLocalUsernameDraft = false + private var hasLocalRelayDraft = false init { viewModelScope.launch { @@ -134,6 +163,13 @@ class SettingsViewModel( themeMode = preferences.themeMode, notificationsEnabled = preferences.notificationsEnabled, diagnosticsEnabled = preferences.diagnosticsEnabled, + savedRelaySettings = preferences.relaySettings, + relayMode = if (hasLocalRelayDraft) current.relayMode else preferences.relaySettings.mode, + relayUrls = if (hasLocalRelayDraft) { + current.relayUrls + } else { + preferences.relaySettings.relayUrls + }, ) } if (receiveFolder != previousFolder) { @@ -141,6 +177,19 @@ class SettingsViewModel( } } } + viewModelScope.launch { + repository.state.collect { coreState -> + val status = coreState.status + val hasActiveWork = status?.let { it.activeTransfers > 0UL || it.activeShares > 0UL } == true || + coreState.transfers.any { it.status in ActiveTransferStatuses } + _state.update { + it.copy( + hasActiveNetworkWork = hasActiveWork, + endpointId = coreState.status?.endpointId, + ) + } + } + } refreshNotificationPermission() loadDeviceInfo() } @@ -162,6 +211,7 @@ class SettingsViewModel( viewModelScope.launch { _state.update { it.copy(isCalculatingStorage = true) } try { + val receiveFolder = _state.value.receiveFolder ?: fileSystemService.defaultReceiveFolder() val coreUsage = repository.storageUsage().getOrThrow() val artifacts = repository.receivedArtifacts().getOrThrow() val received = fileSystemService.inspectReceivedArtifacts(artifacts) @@ -170,7 +220,7 @@ class SettingsViewModel( storage = StorageBreakdown( transferCacheBytes = coreUsage.blobStoreBytes, appDataBytes = coreUsage.appDataBytes, - temporaryBytes = fileSystemService.temporaryUsage(), + temporaryBytes = fileSystemService.temporaryUsage(receiveFolder), receivedBytes = received.existingBytes, receivedFileCount = received.existingCount, missingReceivedFileCount = received.missingCount, @@ -189,18 +239,45 @@ class SettingsViewModel( } fun deleteAllTransfers() { - if (_state.value.isDeletingTransfers) return + if (_state.value.isDeletingTransfers || _state.value.isClearingTransferCache) return viewModelScope.launch { _state.update { it.copy(isDeletingTransfers = true) } val failures = repository.state.value.transfers .map { repository.delete(it.transferId) } .count { it.isFailure } + val cleanup = repository.clearTransferCache() _state.update { it.copy(isDeletingTransfers = false) } - if (failures == 0) { - loadStorageUsage() - } else { + loadStorageUsage() + if (failures > 0) { messages.error(IllegalStateException("Could not delete $failures transfer records")) + } else if (cleanup.isSuccess) { + messages.tryShow(UiMessage(UiText.Resource(Res.string.storage_transfers_deleted), UiMessageTone.Success)) } + cleanup.onFailure(messages::error) + } + } + + fun clearTransferCache() { + if ( + _state.value.isDeletingTransfers || + _state.value.isClearingTransferCache || + _state.value.hasActiveNetworkWork + ) return + viewModelScope.launch { + _state.update { it.copy(isClearingTransferCache = true) } + repository.clearTransferCache().fold( + onSuccess = { + _state.update { it.copy(isClearingTransferCache = false) } + loadStorageUsage() + messages.tryShow( + UiMessage(UiText.Resource(Res.string.storage_transfer_cache_cleared), UiMessageTone.Success), + ) + }, + onFailure = { error -> + _state.update { it.copy(isClearingTransferCache = false) } + messages.error(error) + }, + ) } } @@ -218,6 +295,132 @@ class SettingsViewModel( viewModelScope.launch { preferencesRepository.setThemeMode(mode) } } + fun setRelayMode(mode: RelayMode) { + hasLocalRelayDraft = true + _state.update { + it.copy( + relayMode = mode, + relayUrls = if (mode.usesCustomRelayUrls && it.relayUrls.isEmpty()) listOf("") else it.relayUrls, + relayInputError = null, + relayApplyError = null, + ) + } + hasLocalRelayDraft = _state.value.hasRelaySettingsChanges + } + + fun setRelayUrl(index: Int, value: String) { + if (index !in _state.value.relayUrls.indices) return + hasLocalRelayDraft = true + _state.update { + it.copy( + relayUrls = it.relayUrls.toMutableList().apply { this[index] = value }, + relayInputError = null, + relayApplyError = null, + ) + } + hasLocalRelayDraft = _state.value.hasRelaySettingsChanges + } + + fun addRelayUrl() { + if (_state.value.relayUrls.size >= MaximumRelayUrls) return + hasLocalRelayDraft = true + _state.update { + it.copy( + relayUrls = it.relayUrls + "", + relayInputError = null, + relayApplyError = null, + ) + } + hasLocalRelayDraft = _state.value.hasRelaySettingsChanges + } + + fun removeRelayUrl(index: Int) { + if (index !in _state.value.relayUrls.indices) return + hasLocalRelayDraft = true + _state.update { + val remaining = it.relayUrls.toMutableList().apply { removeAt(index) } + it.copy( + relayUrls = remaining.ifEmpty { listOf("") }, + relayInputError = null, + relayApplyError = null, + ) + } + hasLocalRelayDraft = _state.value.hasRelaySettingsChanges + } + + fun applyRelaySettings() { + val snapshot = _state.value + if (snapshot.isApplyingRelaySettings || !snapshot.hasRelaySettingsChanges) return + val validation = validateRelaySettings( + mode = snapshot.relayMode, + relayUrls = snapshot.relayUrls, + retainedUrls = snapshot.savedRelaySettings.relayUrls, + ) + val desired = validation.settings + if (desired == null) { + _state.update { it.copy(relayInputError = validation.error, relayApplyError = null) } + return + } + if (snapshot.hasActiveNetworkWork) { + _state.update { + it.copy(relayInputError = null, relayApplyError = RelaySettingsApplyError.ActiveTransfers) + } + return + } + + _state.update { + it.copy( + isApplyingRelaySettings = true, + relayInputError = null, + relayApplyError = null, + ) + } + viewModelScope.launch { + val previous = snapshot.savedRelaySettings + val applied = repository.initialize(environment.defaultCoreDataDir, desired) + if (applied.isFailure) { + val busy = applied.exceptionOrNull() is CoreLifecycleBusyException + if (busy || repository.state.value.isInitialized) { + _state.update { + it.copy( + isApplyingRelaySettings = false, + relayApplyError = if (repository.state.value.isInitialized) { + RelaySettingsApplyError.ActiveTransfers + } else { + RelaySettingsApplyError.ApplyFailed + }, + ) + } + } else { + finishFailedRelayApply(previous) + } + return@launch + } + try { + preferencesRepository.setRelaySettings(desired) + } catch (error: CancellationException) { + throw error + } catch (_: Throwable) { + finishFailedRelayApply(previous) + return@launch + } + hasLocalRelayDraft = false + _state.update { + it.copy( + savedRelaySettings = desired, + relayMode = desired.mode, + relayUrls = desired.relayUrls, + isApplyingRelaySettings = false, + relayInputError = null, + relayApplyError = null, + ) + } + messages.show( + UiMessage(UiText.Resource(Res.string.relay_settings_applied), UiMessageTone.Success), + ) + } + } + fun chooseReceiveFolder() { if (!fileSystemService.supportsCustomReceiveFolders) return viewModelScope.launch { effects.send(SettingsEffect.OpenReceiveFolderPicker) } @@ -417,7 +620,22 @@ class SettingsViewModel( _state.update { it.copy(folderAccessStatus = status, isValidatingFolder = false) } } + private suspend fun finishFailedRelayApply(previous: RelaySettings) { + val restored = repository.initialize(environment.defaultCoreDataDir, previous).isSuccess + _state.update { + it.copy( + isApplyingRelaySettings = false, + relayApplyError = if (restored) { + RelaySettingsApplyError.ApplyFailed + } else { + RelaySettingsApplyError.RestoreFailed + }, + ) + } + } + private companion object { const val UsernamePersistDebounceMs = 350L + val ActiveTransferStatuses = setOf(TransferStatus.Importing, TransferStatus.Sharing, TransferStatus.Receiving) } } diff --git a/shared/src/commonMain/kotlin/com/vnidrop/app/feature/settings/StorageSettings.kt b/shared/src/commonMain/kotlin/com/vnidrop/app/feature/settings/StorageSettings.kt index f5c4c75..d5d48fc 100644 --- a/shared/src/commonMain/kotlin/com/vnidrop/app/feature/settings/StorageSettings.kt +++ b/shared/src/commonMain/kotlin/com/vnidrop/app/feature/settings/StorageSettings.kt @@ -2,21 +2,42 @@ package com.vnidrop.app.feature.settings import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.heightIn +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size import androidx.compose.material3.Button import androidx.compose.material3.ButtonDefaults import androidx.compose.material3.CircularProgressIndicator import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp -import com.vnidrop.app.ui.icons.AppIcon +import com.vnidrop.app.ui.components.AdaptiveDrawer +import com.vnidrop.app.ui.components.DestructiveButton +import com.vnidrop.app.ui.components.SecondaryButton import com.vnidrop.app.ui.state.formatBytes +import com.vnidrop.app.ui.state.WindowClass import com.vnidrop.app.ui.theme.LocalVniDropColors import org.jetbrains.compose.resources.stringResource import vnidrop.shared.generated.resources.Res +import vnidrop.shared.generated.resources.button_cancel import vnidrop.shared.generated.resources.storage_app_data import vnidrop.shared.generated.resources.storage_calculating +import vnidrop.shared.generated.resources.storage_clear_transfer_cache +import vnidrop.shared.generated.resources.storage_clear_transfer_cache_description +import vnidrop.shared.generated.resources.storage_clearing_transfer_cache import vnidrop.shared.generated.resources.storage_delete_transfers +import vnidrop.shared.generated.resources.storage_delete_transfers_description import vnidrop.shared.generated.resources.storage_deleting import vnidrop.shared.generated.resources.storage_total import vnidrop.shared.generated.resources.storage_received_files @@ -28,41 +49,60 @@ import vnidrop.shared.generated.resources.storage_footer @Composable internal fun StorageSettings( state: SettingsState, + windowClass: WindowClass, onDeleteAllTransfers: () -> Unit, + onClearTransferCache: () -> Unit, onBack: () -> Unit, showBack: Boolean, ) { + var showDeleteConfirmation by rememberSaveable { mutableStateOf(false) } + var showClearCacheConfirmation by rememberSaveable { mutableStateOf(false) } Column(verticalArrangement = Arrangement.spacedBy(16.dp)) { SettingsTopBar(stringResource(Res.string.storage_title), onBack, showBack) val storage = state.storage if (storage == null || state.isCalculatingStorage) { SettingsGroup { - SettingsRow( - icon = AppIcon.Storage, + StorageRow( title = stringResource(Res.string.storage_calculating), - trailing = { CircularProgressIndicator() }, + trailing = { CircularProgressIndicator(Modifier.size(20.dp), strokeWidth = 2.dp) }, ) } } else { SettingsGroup { - StorageRow(AppIcon.TransferData, stringResource(Res.string.storage_transfer_data), storage.transferCacheBytes) - SettingsDivider() - StorageRow(AppIcon.Storage, stringResource(Res.string.storage_app_data), storage.appDataBytes) - SettingsDivider() - StorageRow(AppIcon.Temporary, stringResource(Res.string.storage_temporary), storage.temporaryBytes) - SettingsDivider() - SettingsRow( - icon = AppIcon.Folder, - title = stringResource(Res.string.storage_received_files), - value = formatBytes(storage.receivedBytes), + StorageRow(stringResource(Res.string.storage_received_files), storage.receivedBytes) + SettingsDivider(startPadding = 16.dp) + StorageRow(stringResource(Res.string.storage_transfer_data), storage.transferCacheBytes) + SettingsDivider(startPadding = 16.dp) + StorageRow(stringResource(Res.string.storage_app_data), storage.appDataBytes) + SettingsDivider(startPadding = 16.dp) + StorageRow(stringResource(Res.string.storage_temporary), storage.temporaryBytes) + SettingsDivider(startPadding = 16.dp) + StorageRow( + title = stringResource(Res.string.storage_total), + bytes = storage.deviceImpactBytes, + emphasized = true, ) - SettingsDivider() - StorageRow(AppIcon.TotalStorage, stringResource(Res.string.storage_total), storage.deviceImpactBytes) } } + SecondaryButton( + text = stringResource( + if (state.isClearingTransferCache) { + Res.string.storage_clearing_transfer_cache + } else { + Res.string.storage_clear_transfer_cache + }, + ), + onClick = { showClearCacheConfirmation = true }, + enabled = !state.isDeletingTransfers && + !state.isClearingTransferCache && + !state.isCalculatingStorage && + !state.hasActiveNetworkWork, + ) Button( - onClick = onDeleteAllTransfers, - enabled = !state.isDeletingTransfers, + onClick = { showDeleteConfirmation = true }, + enabled = !state.isDeletingTransfers && + !state.isClearingTransferCache && + !state.isCalculatingStorage, colors = ButtonDefaults.buttonColors(containerColor = MaterialTheme.colorScheme.error), ) { Text(stringResource(if (state.isDeletingTransfers) Res.string.storage_deleting else Res.string.storage_delete_transfers)) @@ -73,9 +113,124 @@ internal fun StorageSettings( color = LocalVniDropColors.current.foregroundLighter, ) } + if (showClearCacheConfirmation) { + AdaptiveDrawer( + windowClass = windowClass, + onDismissRequest = { showClearCacheConfirmation = false }, + ) { + ClearTransferCachePanel( + onCancel = { showClearCacheConfirmation = false }, + onConfirm = { + showClearCacheConfirmation = false + onClearTransferCache() + }, + ) + } + } + if (showDeleteConfirmation) { + AdaptiveDrawer( + windowClass = windowClass, + onDismissRequest = { showDeleteConfirmation = false }, + ) { + DeleteAllTransfersPanel( + onCancel = { showDeleteConfirmation = false }, + onConfirm = { + showDeleteConfirmation = false + onDeleteAllTransfers() + }, + ) + } + } } @Composable -private fun StorageRow(icon: AppIcon, title: String, bytes: ULong) { - SettingsRow(icon = icon, title = title, value = formatBytes(bytes)) +private fun ClearTransferCachePanel( + onCancel: () -> Unit, + onConfirm: () -> Unit, +) { + Column( + Modifier.fillMaxWidth().padding(horizontal = 20.dp, vertical = 14.dp), + verticalArrangement = Arrangement.spacedBy(14.dp), + ) { + Text( + stringResource(Res.string.storage_clear_transfer_cache), + style = MaterialTheme.typography.titleLarge, + fontWeight = FontWeight.Bold, + ) + Text( + stringResource(Res.string.storage_clear_transfer_cache_description), + color = LocalVniDropColors.current.foregroundLighter, + style = MaterialTheme.typography.bodyMedium, + ) + Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(10.dp, Alignment.End)) { + SecondaryButton(stringResource(Res.string.button_cancel), onClick = onCancel) + DestructiveButton( + stringResource(Res.string.storage_clear_transfer_cache), + onClick = onConfirm, + modifier = Modifier.testTag("confirm-clear-transfer-cache"), + ) + } + } +} + +@Composable +private fun DeleteAllTransfersPanel( + onCancel: () -> Unit, + onConfirm: () -> Unit, +) { + Column( + Modifier.fillMaxWidth().padding(horizontal = 20.dp, vertical = 14.dp), + verticalArrangement = Arrangement.spacedBy(14.dp), + ) { + Text( + stringResource(Res.string.storage_delete_transfers), + style = MaterialTheme.typography.titleLarge, + fontWeight = FontWeight.Bold, + ) + Text( + stringResource(Res.string.storage_delete_transfers_description), + color = LocalVniDropColors.current.foregroundLighter, + style = MaterialTheme.typography.bodyMedium, + ) + Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(10.dp, Alignment.End)) { + SecondaryButton(stringResource(Res.string.button_cancel), onClick = onCancel) + DestructiveButton( + stringResource(Res.string.storage_delete_transfers), + onClick = onConfirm, + modifier = Modifier.testTag("confirm-delete-all-transfers"), + ) + } + } +} + +@Composable +private fun StorageRow( + title: String, + bytes: ULong? = null, + emphasized: Boolean = false, + trailing: @Composable (() -> Unit)? = null, +) { + Row( + modifier = Modifier + .fillMaxWidth() + .heightIn(min = 52.dp) + .padding(horizontal = 16.dp, vertical = 10.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + Text( + title, + modifier = Modifier.weight(1f), + style = MaterialTheme.typography.bodyLarge, + fontWeight = if (emphasized) FontWeight.SemiBold else FontWeight.Normal, + ) + if (bytes != null) { + Text( + formatBytes(bytes), + color = LocalVniDropColors.current.foregroundLighter, + style = MaterialTheme.typography.bodyMedium, + fontWeight = if (emphasized) FontWeight.SemiBold else FontWeight.Normal, + ) + } + trailing?.invoke() + } } diff --git a/shared/src/commonMain/kotlin/com/vnidrop/app/preferences/AppPreferencesRepository.kt b/shared/src/commonMain/kotlin/com/vnidrop/app/preferences/AppPreferencesRepository.kt index d630af9..6f3090d 100644 --- a/shared/src/commonMain/kotlin/com/vnidrop/app/preferences/AppPreferencesRepository.kt +++ b/shared/src/commonMain/kotlin/com/vnidrop/app/preferences/AppPreferencesRepository.kt @@ -3,12 +3,14 @@ package com.vnidrop.app.preferences import androidx.datastore.core.DataStore import androidx.datastore.preferences.core.Preferences import androidx.datastore.preferences.core.PreferenceDataStoreFactory -import androidx.datastore.preferences.core.edit -import androidx.datastore.preferences.core.emptyPreferences -import androidx.datastore.preferences.core.stringPreferencesKey import androidx.datastore.preferences.core.booleanPreferencesKey +import androidx.datastore.preferences.core.edit +import androidx.datastore.preferences.core.preferencesOf +import androidx.datastore.preferences.core.stringPreferencesKey import com.vnidrop.app.core.ReceiveFolder import com.vnidrop.app.core.ReceiveFolderKind +import com.vnidrop.app.core.RelayMode +import com.vnidrop.app.core.RelaySettings import com.vnidrop.app.ui.theme.ThemeMode import com.vnidrop.app.util.randomUuidString import kotlinx.coroutines.flow.Flow @@ -26,6 +28,7 @@ data class AppPreferences( val diagnosticsEnabled: Boolean = false, /** Stable anonymous install id; never an account or advertising id. */ val diagnosticsInstallId: String = "", + val relaySettings: RelaySettings = RelaySettings(), ) class AppPreferencesDefaults( @@ -44,6 +47,7 @@ interface PreferencesRepository { suspend fun setThemeMode(mode: ThemeMode) suspend fun setNotificationsEnabled(enabled: Boolean) suspend fun setDiagnosticsEnabled(enabled: Boolean) + suspend fun setRelaySettings(settings: RelaySettings) /** Ensures a durable install id exists and returns it. */ suspend fun ensureDiagnosticsInstallId(): String } @@ -53,8 +57,27 @@ class AppPreferencesRepository( private val defaults: AppPreferencesDefaults, ) : PreferencesRepository { override val preferences: Flow = dataStore.data - .catch { emit(emptyPreferences()) } + .catch { + emit(preferencesOf(PreferenceKeys.RelayMode to RelayMode.StrictCustom.name)) + } .map { prefs -> + val storedRelayMode = prefs[PreferenceKeys.RelayMode] + val parsedRelayMode = storedRelayMode?.let(::relayModeOrNull) + val relayMode = when (storedRelayMode) { + null -> RelayMode.Automatic + else -> parsedRelayMode ?: RelayMode.StrictCustom + } + val relayUrls = if (storedRelayMode != null && parsedRelayMode == null) { + emptyList() + } else { + prefs[PreferenceKeys.RelayUrls] + .orEmpty() + .lineSequence() + .map(String::trim) + .filter(String::isNotEmpty) + .distinct() + .toList() + } AppPreferences( username = prefs[PreferenceKeys.Username]?.takeIf { it.isNotBlank() } ?: defaults.username, receiveFolder = resolveReceiveFolder(prefs, defaults.receiveFolder), @@ -62,6 +85,10 @@ class AppPreferencesRepository( notificationsEnabled = prefs[PreferenceKeys.NotificationsEnabled] ?: defaults.notificationsEnabled, diagnosticsEnabled = prefs[PreferenceKeys.DiagnosticsEnabled] ?: defaults.diagnosticsEnabled, diagnosticsInstallId = prefs[PreferenceKeys.DiagnosticsInstallId].orEmpty(), + relaySettings = RelaySettings( + mode = relayMode, + relayUrls = relayUrls, + ), ) } @@ -101,6 +128,13 @@ class AppPreferencesRepository( } } + override suspend fun setRelaySettings(settings: RelaySettings) { + dataStore.edit { prefs -> + prefs[PreferenceKeys.RelayMode] = settings.mode.name + prefs[PreferenceKeys.RelayUrls] = settings.relayUrls.joinToString("\n") + } + } + override suspend fun ensureDiagnosticsInstallId(): String { val existing = preferences.first().diagnosticsInstallId if (existing.isNotBlank()) return existing @@ -128,6 +162,8 @@ private object PreferenceKeys { val NotificationsEnabled = booleanPreferencesKey("notifications_enabled") val DiagnosticsEnabled = booleanPreferencesKey("diagnostics_enabled") val DiagnosticsInstallId = stringPreferencesKey("diagnostics_install_id") + val RelayMode = stringPreferencesKey("relay_mode") + val RelayUrls = stringPreferencesKey("relay_urls") } private fun resolveReceiveFolder(prefs: Preferences, defaults: ReceiveFolder): ReceiveFolder { @@ -162,4 +198,8 @@ private fun receiveFolderKindOrNull(raw: String): ReceiveFolderKind? = private fun themeModeOrNull(raw: String): ThemeMode? = runCatching { ThemeMode.valueOf(raw) }.getOrNull() +private fun relayModeOrNull(raw: String): RelayMode? = + if (raw == "Custom") RelayMode.StrictCustom + else runCatching { RelayMode.valueOf(raw) }.getOrNull() + private const val AppPreferencesFileName = "app_preferences.preferences_pb" diff --git a/shared/src/commonTest/kotlin/com/vnidrop/app/core/CoreLifecycleGateTest.kt b/shared/src/commonTest/kotlin/com/vnidrop/app/core/CoreLifecycleGateTest.kt new file mode 100644 index 0000000..4982c91 --- /dev/null +++ b/shared/src/commonTest/kotlin/com/vnidrop/app/core/CoreLifecycleGateTest.kt @@ -0,0 +1,82 @@ +package com.vnidrop.app.core + +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.awaitCancellation +import kotlinx.coroutines.launch +import kotlinx.coroutines.test.runTest +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFailsWith + +class CoreLifecycleGateTest { + @Test + fun concurrentCallsHoldIndependentLeasesAndBlockReconfiguration() = runTest { + val gate = CoreLifecycleGate() + val firstEntered = CompletableDeferred() + val secondEntered = CompletableDeferred() + val release = CompletableDeferred() + val first = launch { + gate.withCall(capture = { "core" }) { captured -> + assertEquals("core", captured) + firstEntered.complete(Unit) + release.await() + } + } + firstEntered.await() + val second = launch { + gate.withCall(capture = { "core" }) { + secondEntered.complete(Unit) + release.await() + } + } + secondEntered.await() + + assertFailsWith { + gate.withReconfiguration { error("must not run") } + } + + release.complete(Unit) + first.join() + second.join() + gate.withReconfiguration { } + } + + @Test + fun callsCannotStartDuringReconfiguration() = runTest { + val gate = CoreLifecycleGate() + val entered = CompletableDeferred() + val release = CompletableDeferred() + val reconfiguration = launch { + gate.withReconfiguration { + entered.complete(Unit) + release.await() + } + } + entered.await() + + assertFailsWith { + gate.withCall(capture = { "core" }) { error("must not run") } + } + + release.complete(Unit) + reconfiguration.join() + } + + @Test + fun cancellingCallReleasesItsLease() = runTest { + val gate = CoreLifecycleGate() + val entered = CompletableDeferred() + val call = launch { + gate.withCall(capture = { "core" }) { + entered.complete(Unit) + awaitCancellation() + } + } + entered.await() + + call.cancel() + call.join() + + gate.withReconfiguration { } + } +} diff --git a/shared/src/commonTest/kotlin/com/vnidrop/app/feature/ViewModelsTest.kt b/shared/src/commonTest/kotlin/com/vnidrop/app/feature/ViewModelsTest.kt index 28a0e81..7d9535a 100644 --- a/shared/src/commonTest/kotlin/com/vnidrop/app/feature/ViewModelsTest.kt +++ b/shared/src/commonTest/kotlin/com/vnidrop/app/feature/ViewModelsTest.kt @@ -3,12 +3,15 @@ package com.vnidrop.app.feature import com.vnidrop.app.DeviceInfo import com.vnidrop.app.PlatformEnvironment import com.vnidrop.app.core.CoreState +import com.vnidrop.app.core.CoreStatus import com.vnidrop.app.core.CoreSignal import com.vnidrop.app.core.PickedShareFile import com.vnidrop.app.core.ReceiveFolder import com.vnidrop.app.core.ReceiveFolderKind import com.vnidrop.app.core.ReceiverDeliveryStatus import com.vnidrop.app.core.ReceiverRequestModel +import com.vnidrop.app.core.RelayMode +import com.vnidrop.app.core.RelaySettings import com.vnidrop.app.core.Share import com.vnidrop.app.core.ShareAccessPolicy import com.vnidrop.app.core.Transfer @@ -24,6 +27,8 @@ import com.vnidrop.app.feature.receive.ReceiveHistoryDeleteTarget import com.vnidrop.app.feature.receive.ReceiveViewModel import com.vnidrop.app.feature.send.SendViewModel import com.vnidrop.app.feature.settings.SettingsSection +import com.vnidrop.app.feature.settings.RelaySettingsApplyError +import com.vnidrop.app.feature.settings.RelaySettingsInputError import com.vnidrop.app.feature.settings.SettingsViewModel import com.vnidrop.app.notifications.NotificationPermission import com.vnidrop.app.preferences.AppPreferences @@ -74,10 +79,26 @@ class ViewModelsTest { val viewModel = AppViewModel(environment(), core, preferences(), UiMessageController()) advanceUntilIdle() assertTrue(core.state.value.isInitialized) + assertEquals(listOf(RelaySettings()), core.initializedRelaySettings) viewModel.selectDestination(AppDestination.Settings) assertEquals(AppDestination.Settings, viewModel.state.value.destination) } + @Test + fun appViewModelInitializesCoreWithSavedRelaySettings() = runTest { + Dispatchers.setMain(StandardTestDispatcher(testScheduler)) + val custom = RelaySettings(RelayMode.StrictCustom, listOf("https://relay.example.com")) + val preferences = preferences().apply { + mutablePreferences.value = mutablePreferences.value.copy(relaySettings = custom) + } + val core = FakeCoreGateway() + + AppViewModel(environment(), core, preferences, UiMessageController()) + advanceUntilIdle() + + assertEquals(listOf(custom), core.initializedRelaySettings) + } + @Test fun settingsEnablesNotificationsOnlyAfterPermission() = runTest { Dispatchers.setMain(StandardTestDispatcher(testScheduler)) @@ -116,6 +137,207 @@ class ViewModelsTest { assertEquals("Ada ", viewModel.state.value.username) } + @Test + fun settingsClearsTransferCacheExplicitly() = runTest { + Dispatchers.setMain(StandardTestDispatcher(testScheduler)) + val core = FakeCoreGateway().apply { + clearTransferCacheResult = Result.success(3_700_000_000UL) + } + val viewModel = settingsViewModel(repository = core) + advanceUntilIdle() + + viewModel.clearTransferCache() + advanceUntilIdle() + + assertEquals(1, core.clearTransferCacheCount) + assertFalse(viewModel.state.value.isClearingTransferCache) + } + + @Test + fun settingsDoesNotClearTransferCacheDuringActiveNetworkWork() = runTest { + Dispatchers.setMain(StandardTestDispatcher(testScheduler)) + val core = FakeCoreGateway().apply { + mutableState.value = CoreState(status = CoreStatus("endpoint", 1UL, 0UL)) + } + val viewModel = settingsViewModel(repository = core) + advanceUntilIdle() + + viewModel.clearTransferCache() + advanceUntilIdle() + + assertEquals(0, core.clearTransferCacheCount) + } + + @Test + fun settingsDeleteAllTransfersImmediatelyClearsUnusedCache() = runTest { + Dispatchers.setMain(StandardTestDispatcher(testScheduler)) + val core = FakeCoreGateway().apply { + mutableState.value = CoreState( + isInitialized = true, + transfers = listOf(receivedTransfer(41UL, TransferStatus.Done)), + ) + } + val viewModel = settingsViewModel(repository = core) + advanceUntilIdle() + + viewModel.deleteAllTransfers() + advanceUntilIdle() + + assertEquals(listOf(41UL), core.deletedTransfers) + assertEquals(1, core.clearTransferCacheCount) + assertFalse(viewModel.state.value.isDeletingTransfers) + } + + @Test + fun settingsAppliesNormalizedCustomRelaysAndPersistsThem() = runTest { + Dispatchers.setMain(StandardTestDispatcher(testScheduler)) + val preferences = preferences() + val core = FakeCoreGateway() + val viewModel = settingsViewModel(preferences = preferences, repository = core) + advanceUntilIdle() + + viewModel.setRelayMode(RelayMode.StrictCustom) + viewModel.setRelayUrl(0, " HTTPS://Relay.Example.com/ ") + viewModel.addRelayUrl() + viewModel.setRelayUrl(1, "https://backup.example.com:443") + viewModel.applyRelaySettings() + advanceUntilIdle() + + val expected = RelaySettings( + RelayMode.StrictCustom, + listOf("https://relay.example.com", "https://backup.example.com"), + ) + assertEquals(expected, preferences.mutablePreferences.value.relaySettings) + assertEquals(listOf(expected), core.initializedRelaySettings) + assertEquals(expected, viewModel.state.value.savedRelaySettings) + assertFalse(viewModel.state.value.hasRelaySettingsChanges) + } + + @Test + fun settingsRejectsInvalidRelayUrlWithoutEnteringLoadingState() = runTest { + Dispatchers.setMain(StandardTestDispatcher(testScheduler)) + val core = FakeCoreGateway() + val viewModel = settingsViewModel(repository = core) + advanceUntilIdle() + + viewModel.setRelayMode(RelayMode.StrictCustom) + viewModel.setRelayUrl(0, "relay.example.com") + viewModel.applyRelaySettings() + + assertFalse(viewModel.state.value.isApplyingRelaySettings) + assertEquals(RelaySettingsInputError.HttpsRequired(1), viewModel.state.value.relayInputError) + assertEquals(emptyList(), core.initializedRelaySettings) + } + + @Test + fun settingsEditsCustomRelaysAsIndividualRows() = runTest { + Dispatchers.setMain(StandardTestDispatcher(testScheduler)) + val viewModel = settingsViewModel() + advanceUntilIdle() + + viewModel.setRelayMode(RelayMode.StrictCustom) + viewModel.setRelayUrl(0, "https://first.example.com") + viewModel.addRelayUrl() + viewModel.setRelayUrl(1, "https://second.example.com") + viewModel.removeRelayUrl(0) + + assertEquals(listOf("https://second.example.com"), viewModel.state.value.relayUrls) + } + + @Test + fun settingsAppliesCustomFallbackAndLocalOnlyWhileRetainingRelayDrafts() = runTest { + Dispatchers.setMain(StandardTestDispatcher(testScheduler)) + val preferences = preferences() + val core = FakeCoreGateway() + val viewModel = settingsViewModel(preferences = preferences, repository = core) + advanceUntilIdle() + + viewModel.setRelayMode(RelayMode.CustomWithDirectFallback) + viewModel.setRelayUrl(0, "https://relay.example.com") + viewModel.applyRelaySettings() + advanceUntilIdle() + viewModel.setRelayMode(RelayMode.LocalOnly) + viewModel.applyRelaySettings() + advanceUntilIdle() + + val fallback = RelaySettings( + RelayMode.CustomWithDirectFallback, + listOf("https://relay.example.com"), + ) + val localOnly = RelaySettings( + RelayMode.LocalOnly, + listOf("https://relay.example.com"), + ) + assertEquals(listOf(fallback, localOnly), core.initializedRelaySettings) + assertEquals(localOnly, preferences.mutablePreferences.value.relaySettings) + assertFalse(viewModel.state.value.hasRelaySettingsChanges) + } + + @Test + fun settingsIgnoresDuplicateApplyBeforeRestartBegins() = runTest { + Dispatchers.setMain(StandardTestDispatcher(testScheduler)) + val core = FakeCoreGateway() + val viewModel = settingsViewModel(repository = core) + advanceUntilIdle() + + viewModel.setRelayMode(RelayMode.StrictCustom) + viewModel.setRelayUrl(0, "https://relay.example.com") + viewModel.applyRelaySettings() + viewModel.applyRelaySettings() + assertTrue(viewModel.state.value.isApplyingRelaySettings) + advanceUntilIdle() + + assertEquals(1, core.initializedRelaySettings.size) + } + + @Test + fun settingsDoesNotRestartNetworkWhileTransfersAreActive() = runTest { + Dispatchers.setMain(StandardTestDispatcher(testScheduler)) + val core = FakeCoreGateway().apply { + mutableState.value = CoreState(status = CoreStatus("endpoint", 0UL, 1UL)) + } + val viewModel = settingsViewModel(repository = core) + advanceUntilIdle() + assertEquals("endpoint", viewModel.state.value.endpointId) + + viewModel.setRelayMode(RelayMode.StrictCustom) + viewModel.setRelayUrl(0, "https://relay.example.com") + viewModel.applyRelaySettings() + advanceUntilIdle() + + assertEquals(emptyList(), core.initializedRelaySettings) + assertEquals(RelaySettingsApplyError.ActiveTransfers, viewModel.state.value.relayApplyError) + } + + @Test + fun settingsRestoresPreviousNetworkConfigurationWhenApplyFails() = runTest { + Dispatchers.setMain(StandardTestDispatcher(testScheduler)) + val core = FakeCoreGateway().apply { + initializeHandler = { settings -> + if (settings.mode == RelayMode.StrictCustom) Result.failure(IllegalStateException("unreachable")) + else Result.success(Unit) + } + } + val preferences = preferences() + val viewModel = settingsViewModel(preferences = preferences, repository = core) + advanceUntilIdle() + + viewModel.setRelayMode(RelayMode.StrictCustom) + viewModel.setRelayUrl(0, "https://relay.example.com") + viewModel.applyRelaySettings() + advanceUntilIdle() + + assertEquals( + listOf( + RelaySettings(RelayMode.StrictCustom, listOf("https://relay.example.com")), + RelaySettings(), + ), + core.initializedRelaySettings, + ) + assertEquals(RelaySettings(), preferences.mutablePreferences.value.relaySettings) + assertEquals(RelaySettingsApplyError.ApplyFailed, viewModel.state.value.relayApplyError) + } + @Test fun settingsKeepsNotificationsDisabledWhenPermissionIsDenied() = runTest { Dispatchers.setMain(StandardTestDispatcher(testScheduler)) @@ -722,11 +944,12 @@ class ViewModelsTest { transport: DiagnosticsTransport = RecordingDiagnosticsTransport(), fileSystem: FakeFileSystemService = FakeFileSystemService(folder), diagnosticsIncluded: Boolean = false, + repository: FakeCoreGateway = FakeCoreGateway(), ) = SettingsViewModel( environment(), { DeviceInfo("Device", "Model", "OS", "Wi-Fi", "80%") }, fileSystem, - FakeCoreGateway(), + repository, preferences, notifications, UiMessageController(), diff --git a/shared/src/commonTest/kotlin/com/vnidrop/app/feature/send/TransferQrCodeTest.kt b/shared/src/commonTest/kotlin/com/vnidrop/app/feature/send/TransferQrCodeTest.kt index d90620a..5840be0 100644 --- a/shared/src/commonTest/kotlin/com/vnidrop/app/feature/send/TransferQrCodeTest.kt +++ b/shared/src/commonTest/kotlin/com/vnidrop/app/feature/send/TransferQrCodeTest.kt @@ -2,6 +2,7 @@ package com.vnidrop.app.feature.send import kotlin.test.Test import kotlin.test.assertEquals +import kotlin.test.assertFailsWith class TransferQrCodeTest { @Test @@ -19,4 +20,12 @@ class TransferQrCodeTest { assertEquals(101, qrCode.rawData.size) assertEquals(872, qrCode.canvasSize) } + + @Test + fun versionFortyCapacityBoundaryRejectsOversizedTicket() { + assertEquals(40, transferQrInformationDensity("a".repeat(2_953))) + assertFailsWith { + transferQrInformationDensity("a".repeat(2_954)) + } + } } diff --git a/shared/src/commonTest/kotlin/com/vnidrop/app/feature/settings/RelaySettingsValidationTest.kt b/shared/src/commonTest/kotlin/com/vnidrop/app/feature/settings/RelaySettingsValidationTest.kt new file mode 100644 index 0000000..cac78fb --- /dev/null +++ b/shared/src/commonTest/kotlin/com/vnidrop/app/feature/settings/RelaySettingsValidationTest.kt @@ -0,0 +1,113 @@ +package com.vnidrop.app.feature.settings + +import com.vnidrop.app.core.RelayMode +import com.vnidrop.app.core.RelaySettings +import kotlin.test.Test +import kotlin.test.assertEquals + +class RelaySettingsValidationTest { + @Test + fun customFallbackUsesTheSameValidatedRelayList() { + val result = validateRelaySettings( + mode = RelayMode.CustomWithDirectFallback, + relayUrls = listOf("https://relay.example.com/"), + ) + + assertEquals( + RelaySettings( + RelayMode.CustomWithDirectFallback, + listOf("https://relay.example.com"), + ), + result.settings, + ) + } + + @Test + fun modesWithoutCustomRelaysRetainTheLastRelayList() { + val retained = listOf("https://relay.example.com") + + assertEquals( + RelaySettings(RelayMode.Automatic, retained), + validateRelaySettings(RelayMode.Automatic, listOf("invalid"), retained).settings, + ) + assertEquals( + RelaySettings(RelayMode.LocalOnly, retained), + validateRelaySettings(RelayMode.LocalOnly, listOf("invalid"), retained).settings, + ) + } + + @Test + fun customRelayUrlsAreNormalized() { + val result = validateRelaySettings( + mode = RelayMode.StrictCustom, + relayUrls = listOf(" HTTPS://Relay.Example.com/ ", "https://[2001:DB8::1]:443"), + ) + + assertEquals( + RelaySettings( + RelayMode.StrictCustom, + listOf("https://relay.example.com", "https://[2001:db8::1]"), + ), + result.settings, + ) + assertEquals(null, result.error) + } + + @Test + fun customRelayUrlsRequireHttpsAndRootPath() { + assertEquals( + RelaySettingsInputError.HttpsRequired(1), + validateRelaySettings(RelayMode.StrictCustom, listOf("http://relay.example.com")).error, + ) + assertEquals( + RelaySettingsInputError.InvalidUrl(1), + validateRelaySettings(RelayMode.StrictCustom, listOf("https://relay.example.com/custom")).error, + ) + } + + @Test + fun duplicateNormalizedRelayUrlsAreRejected() { + val result = validateRelaySettings( + RelayMode.StrictCustom, + listOf("https://relay.example.com", "HTTPS://RELAY.EXAMPLE.COM:443/"), + ) + + assertEquals(RelaySettingsInputError.DuplicateUrl(2), result.error) + } + + @Test + fun structurallyValidIpv6RelayUrlsAreAccepted() { + val result = validateRelaySettings( + RelayMode.StrictCustom, + listOf("https://[::1]:443", "https://[2001:db8::1]", "https://[::ffff:192.0.2.1]"), + ) + + assertEquals( + RelaySettings( + RelayMode.StrictCustom, + listOf( + "https://[::1]", + "https://[2001:db8::1]", + "https://[::ffff:192.0.2.1]", + ), + ), + result.settings, + ) + } + + @Test + fun malformedIpv6RelayUrlsAreRejected() { + listOf( + "https://[::::]", + "https://[1::2::3]", + "https://[1:2:3:4:5:6:7]", + "https://[1:2:3:4:5:6:7:8::]", + ).forEach { url -> + assertEquals( + RelaySettingsInputError.InvalidUrl(1), + validateRelaySettings(RelayMode.StrictCustom, listOf(url)).error, + url, + ) + } + } +} diff --git a/shared/src/commonTest/kotlin/com/vnidrop/app/support/Fakes.kt b/shared/src/commonTest/kotlin/com/vnidrop/app/support/Fakes.kt index 8b310e8..4e09b09 100644 --- a/shared/src/commonTest/kotlin/com/vnidrop/app/support/Fakes.kt +++ b/shared/src/commonTest/kotlin/com/vnidrop/app/support/Fakes.kt @@ -10,6 +10,7 @@ import com.vnidrop.app.core.PickedShareFile import com.vnidrop.app.core.ReceiveFolder import com.vnidrop.app.core.ReceivedArtifactModel import com.vnidrop.app.core.ReceivedStorageInspection +import com.vnidrop.app.core.RelaySettings import com.vnidrop.app.core.ReceiverRequestModel import com.vnidrop.app.core.Share import com.vnidrop.app.core.ShareAccessPolicy @@ -46,14 +47,18 @@ class FakeCoreGateway : CoreGateway { var receiveSuspend: Boolean = false private var receiveGate: CompletableDeferred? = null var deleteResult: Result = Result.success(Unit) + var clearTransferCacheResult: Result = Result.success(0UL) var clearReceiveHistoryResult: Result = Result.success(0UL) val deletedTransfers = mutableListOf() val cancelledTransfers = mutableListOf() var clearReceiveHistoryCount = 0 + var clearTransferCacheCount = 0 var receiveCount = 0 var lastReceiveTicket: String? = null var lastReceiveReceiverName: String? = null var lastShareAccessPolicy: ShareAccessPolicy? = null + val initializedRelaySettings = mutableListOf() + var initializeHandler: (RelaySettings) -> Result = { Result.success(Unit) } fun completeSuspendedReceive() { receiveGate?.complete(Unit) @@ -66,9 +71,11 @@ class FakeCoreGateway : CoreGateway { gate.await() } - override suspend fun initialize(appDataDir: String): Result { - mutableState.value = mutableState.value.copy(isInitialized = true) - return Result.success(Unit) + override suspend fun initialize(appDataDir: String, relaySettings: RelaySettings): Result { + initializedRelaySettings += relaySettings + return initializeHandler(relaySettings).onSuccess { + mutableState.value = mutableState.value.copy(isInitialized = true) + } } override fun shutdown() = Unit var lastShareSourceCount: Int = 0 @@ -149,6 +156,10 @@ class FakeCoreGateway : CoreGateway { override suspend fun storageUsage(): Result = Result.success( CoreStorageUsageModel(0UL, 0UL, 0UL, 0UL, 0UL), ) + override suspend fun clearTransferCache(): Result { + clearTransferCacheCount += 1 + return clearTransferCacheResult + } override suspend fun receivedArtifacts(): Result> = Result.success(emptyList()) override suspend fun cancel(transferId: ULong): Result { cancelledTransfers += transferId @@ -201,6 +212,9 @@ class FakePreferencesRepository( override suspend fun setDiagnosticsEnabled(enabled: Boolean) { mutablePreferences.value = mutablePreferences.value.copy(diagnosticsEnabled = enabled) } + override suspend fun setRelaySettings(settings: RelaySettings) { + mutablePreferences.value = mutablePreferences.value.copy(relaySettings = settings) + } override suspend fun ensureDiagnosticsInstallId(): String { val existing = mutablePreferences.value.diagnosticsInstallId if (existing.isNotBlank()) return existing @@ -244,7 +258,7 @@ class FakeFileSystemService( override suspend fun validateReceiveFolder(folder: ReceiveFolder) = FolderAccessStatus.Writable override suspend fun inspectReceivedArtifacts(artifacts: List) = ReceivedStorageInspection(artifacts.fold(0UL) { total, item -> total + item.logicalSize }, artifacts.size, 0, 0) - override suspend fun temporaryUsage(): ULong = 0UL + override suspend fun temporaryUsage(receiveFolder: ReceiveFolder): ULong = 0UL override fun createReceiveOutputSink(folder: ReceiveFolder): ReceiveOutputSinkV2? = null override fun canRevealReceiveFolder(folder: ReceiveFolder) = canRevealFolder override suspend fun revealReceiveFolder(folder: ReceiveFolder): Result { diff --git a/shared/src/jvmMain/kotlin/com/vnidrop/app/core/FileSystemService.jvm.kt b/shared/src/jvmMain/kotlin/com/vnidrop/app/core/FileSystemService.jvm.kt index 8e1541b..c566035 100644 --- a/shared/src/jvmMain/kotlin/com/vnidrop/app/core/FileSystemService.jvm.kt +++ b/shared/src/jvmMain/kotlin/com/vnidrop/app/core/FileSystemService.jvm.kt @@ -4,6 +4,8 @@ import androidx.compose.runtime.Composable import androidx.compose.runtime.remember import uniffi.vnidrop.ReceiveOutputSinkV2 import java.io.File +import java.nio.file.Files +import java.nio.file.LinkOption @Composable actual fun rememberFileSystemService(): FileSystemService = @@ -42,7 +44,9 @@ private class JvmFileSystemService : FileSystemService { return ReceivedStorageInspection(bytes, existing, missing, 0) } - override suspend fun temporaryUsage(): ULong = 0UL + override suspend fun temporaryUsage(receiveFolder: ReceiveFolder): ULong { + return desktopTemporaryUsage(receiveFolder) + } override fun createReceiveOutputSink(folder: ReceiveFolder): ReceiveOutputSinkV2? = null @@ -65,3 +69,22 @@ private class JvmFileSystemService : FileSystemService { return repository.shareSources(sources, transferName, senderName, accessPolicy) } } + +internal fun desktopTemporaryUsage(receiveFolder: ReceiveFolder): ULong { + if (receiveFolder.kind != ReceiveFolderKind.FileSystemPath) return 0UL + val root = File(receiveFolder.value).toPath() + if (!Files.isDirectory(root, LinkOption.NOFOLLOW_LINKS)) return 0UL + return runCatching { + Files.walk(root).use { paths -> + paths.iterator().asSequence() + .filter { path -> + val name = path.fileName?.toString().orEmpty() + Files.isRegularFile(path, LinkOption.NOFOLLOW_LINKS) && + name.startsWith(".") && + name.contains(".vnidrop-") && + name.endsWith(".part") + } + .fold(0UL) { total, path -> total + Files.size(path).toULong() } + } + }.getOrDefault(0UL) +} diff --git a/shared/src/jvmTest/kotlin/com/vnidrop/app/core/CoreRepositoryStorageTest.kt b/shared/src/jvmTest/kotlin/com/vnidrop/app/core/CoreRepositoryStorageTest.kt new file mode 100644 index 0000000..4665b54 --- /dev/null +++ b/shared/src/jvmTest/kotlin/com/vnidrop/app/core/CoreRepositoryStorageTest.kt @@ -0,0 +1,43 @@ +package com.vnidrop.app.core + +import java.nio.file.Files +import kotlin.io.path.createTempDirectory +import kotlinx.coroutines.test.runTest +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertTrue + +class CoreRepositoryStorageTest { + @Test + fun cacheClearWaitsForActiveSharesThenRestartsWithTheSameIdentity() = runTest { + val appData = createTempDirectory("vnidrop-cache-clear") + val source = Files.write(appData.resolve("source.bin"), ByteArray(64 * 1024) { 5 }) + val repository = CoreRepository() + try { + assertTrue( + repository.initialize( + appData.toString(), + RelaySettings(mode = RelayMode.LocalOnly), + ).isSuccess, + ) + val endpointId = repository.state.value.status?.endpointId + val share = repository.sharePath( + path = source.toString(), + transferName = "source.bin", + senderName = "Sender", + accessPolicy = ShareAccessPolicy.RequireApproval, + ).getOrThrow() + + assertTrue(repository.clearTransferCache().isFailure) + assertTrue(repository.state.value.isInitialized) + + repository.delete(share.transferId).getOrThrow() + assertTrue(repository.clearTransferCache().getOrThrow() >= 64UL * 1024UL) + assertTrue(repository.state.value.isInitialized) + assertEquals(endpointId, repository.state.value.status?.endpointId) + } finally { + repository.shutdown() + appData.toFile().deleteRecursively() + } + } +} diff --git a/shared/src/jvmTest/kotlin/com/vnidrop/app/core/FileSystemServiceTest.kt b/shared/src/jvmTest/kotlin/com/vnidrop/app/core/FileSystemServiceTest.kt new file mode 100644 index 0000000..b8909f7 --- /dev/null +++ b/shared/src/jvmTest/kotlin/com/vnidrop/app/core/FileSystemServiceTest.kt @@ -0,0 +1,29 @@ +package com.vnidrop.app.core + +import java.nio.file.Files +import kotlin.io.path.createDirectories +import kotlin.io.path.createTempDirectory +import kotlin.test.Test +import kotlin.test.assertEquals + +class FileSystemServiceTest { + @Test + fun desktopTemporaryUsageCountsOnlyVnidropPartFiles() { + val root = createTempDirectory("vnidrop-temporary-usage") + try { + val nested = root.resolve("nested").createDirectories() + Files.write(nested.resolve(".photo.jpg.vnidrop-test.part"), ByteArray(7)) + Files.write(nested.resolve("photo.jpg"), ByteArray(13)) + Files.write(nested.resolve(".unrelated.part"), ByteArray(17)) + + assertEquals( + 7UL, + desktopTemporaryUsage( + ReceiveFolder(ReceiveFolderKind.FileSystemPath, root.toString(), "Test"), + ), + ) + } finally { + root.toFile().deleteRecursively() + } + } +} diff --git a/shared/src/jvmTest/kotlin/com/vnidrop/app/preferences/AppPreferencesRepositoryTest.kt b/shared/src/jvmTest/kotlin/com/vnidrop/app/preferences/AppPreferencesRepositoryTest.kt index b8693d0..0959281 100644 --- a/shared/src/jvmTest/kotlin/com/vnidrop/app/preferences/AppPreferencesRepositoryTest.kt +++ b/shared/src/jvmTest/kotlin/com/vnidrop/app/preferences/AppPreferencesRepositoryTest.kt @@ -1,12 +1,19 @@ package com.vnidrop.app.preferences +import androidx.datastore.core.DataStore +import androidx.datastore.preferences.core.Preferences +import androidx.datastore.preferences.core.edit +import androidx.datastore.preferences.core.stringPreferencesKey import com.vnidrop.app.core.ReceiveFolder import com.vnidrop.app.core.ReceiveFolderKind +import com.vnidrop.app.core.RelayMode +import com.vnidrop.app.core.RelaySettings import com.vnidrop.app.ui.theme.ThemeMode import java.nio.file.Files import kotlin.test.Test import kotlin.test.assertEquals import kotlinx.coroutines.flow.first +import kotlinx.coroutines.flow.flow import kotlinx.coroutines.runBlocking class AppPreferencesRepositoryTest { @@ -19,6 +26,89 @@ class AppPreferencesRepositoryTest { assertEquals("Device Name", preferences.username) assertEquals(defaultFolder, preferences.receiveFolder) assertEquals(ThemeMode.System, preferences.themeMode) + assertEquals(RelaySettings(), preferences.relaySettings) + } + + @Test + fun customRelaySettingsArePersisted() = runBlocking { + val repository = repositoryForTest() + val custom = RelaySettings( + mode = RelayMode.StrictCustom, + relayUrls = listOf("https://relay.example.com", "https://backup.example.com:443"), + ) + + repository.setRelaySettings(custom) + + assertEquals(custom, repository.preferences.first().relaySettings) + } + + @Test + fun legacyCustomRelayModeMigratesToStrictCustom() = runBlocking { + val directory = Files.createTempDirectory("vnidrop-preferences-test").toString() + val dataStore = createAppPreferencesDataStore(directory) + dataStore.edit { preferences -> + preferences[stringPreferencesKey("relay_mode")] = "Custom" + preferences[stringPreferencesKey("relay_urls")] = "https://relay.example.com" + } + val repository = AppPreferencesRepository( + dataStore = dataStore, + defaults = AppPreferencesDefaults( + username = "Device Name", + receiveFolder = defaultFolder, + themeMode = ThemeMode.System, + ), + ) + + assertEquals( + RelaySettings(RelayMode.StrictCustom, listOf("https://relay.example.com")), + repository.preferences.first().relaySettings, + ) + } + + @Test + fun unknownStoredRelayModeFailsClosedAndCanBeReset() = runBlocking { + val directory = Files.createTempDirectory("vnidrop-preferences-test").toString() + val dataStore = createAppPreferencesDataStore(directory) + dataStore.edit { preferences -> + preferences[stringPreferencesKey("relay_mode")] = "FUTURE_MODE" + preferences[stringPreferencesKey("relay_urls")] = "https://relay.example.com" + } + val repository = AppPreferencesRepository( + dataStore = dataStore, + defaults = AppPreferencesDefaults( + username = "Device Name", + receiveFolder = defaultFolder, + themeMode = ThemeMode.System, + ), + ) + + assertEquals(RelaySettings(RelayMode.StrictCustom), repository.preferences.first().relaySettings) + + repository.setRelaySettings(RelaySettings()) + assertEquals(RelaySettings(), repository.preferences.first().relaySettings) + } + + @Test + fun unreadablePreferencesFailClosedInsteadOfUsingPublicRelays() = runBlocking { + val dataStore = object : DataStore { + override val data = flow { + throw IllegalStateException("corrupt preferences") + } + + override suspend fun updateData( + transform: suspend (t: Preferences) -> Preferences, + ): Preferences = error("not used") + } + val repository = AppPreferencesRepository( + dataStore = dataStore, + defaults = AppPreferencesDefaults( + username = "Device Name", + receiveFolder = defaultFolder, + themeMode = ThemeMode.System, + ), + ) + + assertEquals(RelaySettings(RelayMode.StrictCustom), repository.preferences.first().relaySettings) } @Test diff --git a/shared/src/jvmTest/kotlin/com/vnidrop/app/ui/FoundationComposeTest.kt b/shared/src/jvmTest/kotlin/com/vnidrop/app/ui/FoundationComposeTest.kt index 056d7f3..bbf7060 100644 --- a/shared/src/jvmTest/kotlin/com/vnidrop/app/ui/FoundationComposeTest.kt +++ b/shared/src/jvmTest/kotlin/com/vnidrop/app/ui/FoundationComposeTest.kt @@ -64,6 +64,7 @@ import com.vnidrop.app.ui.theme.VniDropTheme import com.vnidrop.app.ui.theme.LocalVniDropColors import kotlin.test.Test import kotlin.test.assertEquals +import kotlin.test.assertFalse import kotlin.test.assertTrue @OptIn(ExperimentalTestApi::class) @@ -113,6 +114,114 @@ class FoundationComposeTest { onNodeWithText("Get notified about new receive requests while VniDrop is in the background.").assertIsDisplayed() } + @Test + fun phoneSettingsOpensCustomRelayConfiguration() = runComposeUiTest { + val state = mutableStateOf(SettingsState(endpointId = "endpoint-for-allowlist")) + var applied = false + setContent { + VniDropTheme(isDarkTheme = false) { + SettingsScreen( + state = state.value, + windowClass = WindowClass.Phone, + onSectionSelected = { state.value = state.value.copy(selectedSection = it) }, + onUsernameChanged = {}, + onThemeModeChanged = {}, + onChooseFolder = {}, + onResetFolder = {}, + onNotificationsChanged = {}, + onOpenNotificationSettings = {}, + onDiagnosticsChanged = {}, + onBugWhatChanged = {}, + onBugExpectedChanged = {}, + onBugStepsChanged = {}, + onBugContactChanged = {}, + onBugIncludeLogsChanged = {}, + onSubmitBugReport = {}, + onRelayModeChanged = { + state.value = state.value.copy( + relayMode = it, + relayUrls = state.value.relayUrls.ifEmpty { listOf("") }, + ) + }, + onRelayUrlChanged = { index, value -> + state.value = state.value.copy( + relayUrls = state.value.relayUrls.toMutableList().apply { this[index] = value }, + ) + }, + onAddRelayUrl = { + state.value = state.value.copy(relayUrls = state.value.relayUrls + "") + }, + onRemoveRelayUrl = { index -> + state.value = state.value.copy( + relayUrls = state.value.relayUrls.toMutableList().apply { removeAt(index) }.ifEmpty { listOf("") }, + ) + }, + onApplyRelaySettings = { applied = true }, + ) + } + } + + onNodeWithText("Network").performClick() + onNodeWithText("Device ID: endpoint-for-allowlist").assertIsDisplayed() + onNodeWithText("Strict custom").performClick() + onNodeWithText( + "Strict custom mode will not start unless at least one configured relay is reachable. " + + "VniDrop never uses public relays or public discovery in this mode.", + ).assertIsDisplayed() + onNodeWithText("Add relay server").assertIsDisplayed() + onNodeWithText("Apply network settings").performClick() + runOnIdle { assertTrue(applied) } + } + + @Test + fun storageDeleteAllTransfersRequiresConfirmation() = runComposeUiTest { + var deleteRequested = false + var cacheClearRequested = false + setContent { + VniDropTheme(isDarkTheme = false) { + SettingsScreen( + state = SettingsState(selectedSection = SettingsSection.Storage), + windowClass = WindowClass.Desktop, + onSectionSelected = {}, + onUsernameChanged = {}, + onThemeModeChanged = {}, + onChooseFolder = {}, + onResetFolder = {}, + onNotificationsChanged = {}, + onOpenNotificationSettings = {}, + onDiagnosticsChanged = {}, + onBugWhatChanged = {}, + onBugExpectedChanged = {}, + onBugStepsChanged = {}, + onBugContactChanged = {}, + onBugIncludeLogsChanged = {}, + onSubmitBugReport = {}, + onDeleteAllTransfers = { deleteRequested = true }, + onClearTransferCache = { cacheClearRequested = true }, + ) + } + } + + onNodeWithText("Clear transfer cache").performClick() + onNodeWithText( + "Removes cached transfer content after briefly restarting VniDrop. " + + "Finish ongoing transfers and stop active shares first. Received files and transfer history are not deleted.", + ).assertIsDisplayed() + runOnIdle { assertFalse(cacheClearRequested) } + onNodeWithTag("confirm-clear-transfer-cache").performClick() + runOnIdle { assertTrue(cacheClearRequested) } + + onNodeWithText("Delete all transfers").performClick() + onNodeWithText( + "This clears all sent and received transfer records from your history and immediately reclaims unused transfer cache. " + + "Ongoing transfers and received files are not deleted. This can’t be undone.", + ).assertIsDisplayed() + runOnIdle { assertFalse(deleteRequested) } + + onNodeWithTag("confirm-delete-all-transfers").performClick() + runOnIdle { assertTrue(deleteRequested) } + } + @Test fun aboutSettingsShowsTheSharedProductAndPrivacyContent() = runComposeUiTest { setContent { @@ -536,6 +645,56 @@ class FoundationComposeTest { onNodeWithContentDescription("Close").assertIsDisplayed() } + @Test + fun stoppedAndFailedTransfersDoNotExposeStaleInvitations() = runComposeUiTest { + val transfer = mutableStateOf(outgoingTransfer().copy(status = TransferStatus.Stopped)) + setContent { + VniDropTheme(isDarkTheme = false) { + SendScreen( + coreState = CoreState(isInitialized = true, transfers = listOf(transfer.value)), + state = SendState( + selectedTransferId = transfer.value.transferId, + detailPanel = com.vnidrop.app.feature.send.TransferDetailPanel.Share, + ), + windowClass = WindowClass.Desktop, + onOpenComposer = {}, onDismissComposer = {}, onSelectFile = {}, onClearFile = {}, + onTransferNameChanged = {}, onSenderNameChanged = {}, onAccessPolicyChanged = {}, + onCreateShare = {}, onTransferSelected = {}, onCloseTransferDetails = {}, onCopyTicket = {}, + ) + } + } + + onAllNodesWithText("Share").assertCountEquals(0) + onAllNodesWithText("Save .vnd file").assertCountEquals(0) + + runOnIdle { transfer.value = transfer.value.copy(status = TransferStatus.Failed) } + onAllNodesWithText("Share").assertCountEquals(0) + onAllNodesWithText("Save .vnd file").assertCountEquals(0) + } + + @Test + fun oversizedInvitationShowsQrUnavailableInsteadOfLoadingForever() = runComposeUiTest { + val transfer = outgoingTransfer().copy(ticket = "a".repeat(2_954)) + setContent { + VniDropTheme(isDarkTheme = false) { + SendScreen( + coreState = CoreState(isInitialized = true, transfers = listOf(transfer)), + state = SendState( + selectedTransferId = transfer.transferId, + detailPanel = com.vnidrop.app.feature.send.TransferDetailPanel.Share, + ), + windowClass = WindowClass.Desktop, + onOpenComposer = {}, onDismissComposer = {}, onSelectFile = {}, onClearFile = {}, + onTransferNameChanged = {}, onSenderNameChanged = {}, onAccessPolicyChanged = {}, + onCreateShare = {}, onTransferSelected = {}, onCloseTransferDetails = {}, onCopyTicket = {}, + ) + } + } + + onNodeWithText("QR unavailable for this invitation. Use Share or Download instead.").assertIsDisplayed() + onNodeWithText("Save .vnd file").assertIsDisplayed() + } + @Test fun phoneReceiveEmptyStateOpensAcquisitionMethods() = runComposeUiTest { val state = mutableStateOf(ReceiveState())