feat(call): vendor native lifecycle plugin

This commit is contained in:
Erwan Leboucher committed 2026-07-30 14:06:14 +02:00
1 parent fb87569e25
commit 8d16da8560
34 files changed
+2572 -18

No files matched your search

+1
View File
@@ -116,6 +116,7 @@
"slate-history": "^0.113.1",
"slate-react": "^0.125.1",
"tauri-plugin-android-fs-api": "28.4.0",
"tauri-plugin-call-lifecycle-api": "file:src-tauri/plugins/tauri-plugin-call-lifecycle",
"ua-parser-js": "^2.0.10",
"virtua": "^0.49.2",
"workbox-precaching": "^7.4.1"
+10
View File
@@ -253,6 +253,9 @@ importers:
tauri-plugin-android-fs-api:
specifier: 28.4.0
version: 28.4.0
tauri-plugin-call-lifecycle-api:
specifier: file:src-tauri/plugins/tauri-plugin-call-lifecycle
version: file:src-tauri/plugins/tauri-plugin-call-lifecycle
ua-parser-js:
specifier: ^2.0.10
version: 2.0.10
@@ -5338,6 +5341,9 @@ packages:
[email protected]:
resolution: {integrity: sha512-YOo1P+cRjuaoPbTNZprMhr56ruKO4hIDq7kJOum91NqkN+VWY9F+UPAdjZokhzJSsbkeY0nsb1VDLXb2/h3f3w==}
tauri-plugin-call-lifecycle-api@file:src-tauri/plugins/tauri-plugin-call-lifecycle:
resolution: {directory: src-tauri/plugins/tauri-plugin-call-lifecycle, type: directory}
[email protected]:
resolution: {integrity: sha512-eYE6iEI62Ni1H8oIa7KlDU6uQBtqr4Eajni3wX7rpfXD8ysFx8z0+dri+KWEPWpBsxXfxu58x/0jvTVT1ekOSg==}
@@ -10770,6 +10776,10 @@ snapshots:
'@tauri-apps/api': 2.11.1
create-web-stream: 1.1.3
tauri-plugin-call-lifecycle-api@file:src-tauri/plugins/tauri-plugin-call-lifecycle:
dependencies:
'@tauri-apps/api': 2.11.1
[email protected]:
dependencies:
streamx: 2.28.0
+627 -10
View File
@@ -563,6 +563,16 @@ dependencies = [
"piper",
]
[[package]]
name = "bmrng"
version = "0.5.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d54df9073108f1558f90ae6c5bf5ab9c917c4185f5527b280c87a993cbead0ac"
dependencies = [
"futures-core",
"tokio",
]
[[package]]
name = "borsh"
version = "1.8.0"
@@ -930,7 +940,7 @@ dependencies = [
"anstream",
"anstyle",
"clap_lex",
"strsim",
"strsim 0.11.1",
]
[[package]]
@@ -998,6 +1008,17 @@ dependencies = [
"objc",
]
[[package]]
name = "codespan-reporting"
version = "0.13.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "af491d569909a7e4dee0ad7db7f5341fef5c614d5b8ec8cf765732aba3cff681"
dependencies = [
"serde",
"termcolor",
"unicode-width",
]
[[package]]
name = "colorchoice"
version = "1.0.5"
@@ -1325,14 +1346,100 @@ version = "1.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f27ae1dd37df86211c42e150270f82743308803d90a6f6e6651cd730d5e1732f"
[[package]]
name = "cxx"
version = "1.0.198"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6fe442a792c7c736eea18b32a7f8a3b63cf8aafabda6760042dc2fdeda456291"
dependencies = [
"cc",
"cxx-build",
"cxxbridge-cmd",
"cxxbridge-flags",
"cxxbridge-macro",
"foldhash 0.2.0",
"link-cplusplus",
]
[[package]]
name = "cxx-build"
version = "1.0.198"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e3184a94384c663718698311a78a51ac00c484c10b4eeac06fb0a068c5f64fa2"
dependencies = [
"cc",
"codespan-reporting",
"indexmap 2.14.0",
"proc-macro2",
"quote",
"scratch",
"syn 3.0.3",
]
[[package]]
name = "cxxbridge-cmd"
version = "1.0.198"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0148d8fd1199329ddf1d157a5e134e51ceff37c6a7ddd38615c399d81cb05d8d"
dependencies = [
"clap",
"codespan-reporting",
"indexmap 2.14.0",
"proc-macro2",
"quote",
"syn 3.0.3",
]
[[package]]
name = "cxxbridge-flags"
version = "1.0.198"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "52850339faed2eaadd24e286dc1d8268cc6f8a7bd9524d713adc9099566b4c89"
[[package]]
name = "cxxbridge-macro"
version = "1.0.198"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2c77c856545d886c9bd5215409ebb63b925e262135248b50c79e5a5f194ee47c"
dependencies = [
"indexmap 2.14.0",
"proc-macro2",
"quote",
"syn 3.0.3",
]
[[package]]
name = "darling"
version = "0.14.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7b750cb3417fd1b327431a470f388520309479ab0bf5e323505daf0290cd3850"
dependencies = [
"darling_core 0.14.4",
"darling_macro 0.14.4",
]
[[package]]
name = "darling"
version = "0.23.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "25ae13da2f202d56bd7f91c25fba009e7717a1e4a1cc98a76d844b65ae912e9d"
dependencies = [
"darling_core",
"darling_macro",
"darling_core 0.23.0",
"darling_macro 0.23.0",
]
[[package]]
name = "darling_core"
version = "0.14.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "109c1ca6e6b7f82cc233a97004ea8ed7ca123a9af07a8230878fcfda9b158bf0"
dependencies = [
"fnv",
"ident_case",
"proc-macro2",
"quote",
"strsim 0.10.0",
"syn 1.0.109",
]
[[package]]
@@ -1344,21 +1451,38 @@ dependencies = [
"ident_case",
"proc-macro2",
"quote",
"strsim",
"strsim 0.11.1",
"syn 2.0.119",
]
[[package]]
name = "darling_macro"
version = "0.14.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a4aab4dbc9f7611d8b55048a3a16d2d010c2c8334e46304b40ac1cc14bf3b48e"
dependencies = [
"darling_core 0.14.4",
"quote",
"syn 1.0.109",
]
[[package]]
name = "darling_macro"
version = "0.23.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ac3984ec7bd6cfa798e62b4a642426a5be0e68f9401cfc2a01e3fa9ea2fcdb8d"
dependencies = [
"darling_core",
"darling_core 0.23.0",
"quote",
"syn 2.0.119",
]
[[package]]
name = "data-encoding"
version = "2.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a4ae5f15dda3c708c0ade84bfee31ccab44a3da4f88015ed22f63732abe300c8"
[[package]]
name = "data-url"
version = "0.3.2"
@@ -1477,6 +1601,21 @@ version = "1.6.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "abd57806937c9cc163efc8ea3910e00a62e2aeb0b8119f1793a978088f8f6b04"
[[package]]
name = "device-info"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a2ca8e71544c1b67dcdbc2699ab258828aff985e5bc8d5f6b486d90d7df2f848"
dependencies = [
"core-foundation 0.10.1",
"jni 0.21.1",
"libc",
"thiserror 2.0.19",
"wasm-bindgen",
"web-sys",
"windows-sys 0.59.0",
]
[[package]]
name = "devtools-core"
version = "0.3.6"
@@ -1527,6 +1666,7 @@ checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"
dependencies = [
"block-buffer",
"crypto-common",
"subtle",
]
[[package]]
@@ -1953,6 +2093,12 @@ dependencies = [
"winapi",
]
[[package]]
name = "fixedbitset"
version = "0.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0ce7134b9999ecaf8bcd65542e436736ef32ddca1b3e06094cb6ec5755203b80"
[[package]]
name = "fixedbitset"
version = "0.5.7"
@@ -2024,6 +2170,27 @@ dependencies = [
"percent-encoding",
]
[[package]]
name = "from_variants"
version = "1.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4e859c8f2057687618905dbe99fc76e836e0a69738865ef90e46fc214a41bbf2"
dependencies = [
"from_variants_impl",
]
[[package]]
name = "from_variants_impl"
version = "1.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "55a5e644a80e6d96b2b4910fa7993301d7b7926c045b475b62202b20a36ce69e"
dependencies = [
"darling 0.14.4",
"proc-macro2",
"quote",
"syn 1.0.109",
]
[[package]]
name = "fs-err"
version = "3.3.1"
@@ -2033,6 +2200,16 @@ dependencies = [
"autocfg",
]
[[package]]
name = "fs2"
version = "0.4.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9564fc758e15025b46aa6643b1b77d047d1a56a1aea6e01002ac0c7026876213"
dependencies = [
"libc",
"winapi",
]
[[package]]
name = "futf"
version = "0.1.5"
@@ -2618,6 +2795,15 @@ version = "0.4.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70"
[[package]]
name = "hmac"
version = "0.12.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e"
dependencies = [
"digest",
]
[[package]]
name = "hostname"
version = "0.4.2"
@@ -2788,6 +2974,7 @@ dependencies = [
"hyper 1.11.0",
"hyper-util",
"rustls",
"rustls-native-certs",
"tokio",
"tokio-rustls",
"tower-service",
@@ -3108,6 +3295,15 @@ version = "1.70.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695"
[[package]]
name = "itertools"
version = "0.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b1c173a5686ce8bfa551b3563d0c2170bf24ca44da99c7ca4bfdab5418c3fe57"
dependencies = [
"either",
]
[[package]]
name = "itertools"
version = "0.12.1"
@@ -3299,6 +3495,21 @@ dependencies = [
"serde_json",
]
[[package]]
name = "jsonwebtoken"
version = "10.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "eba32bfb4ffdeaca3e34431072faf01745c9b26d25504aa7a6cf5684334fc4fc"
dependencies = [
"base64 0.22.1",
"getrandom 0.2.17",
"js-sys",
"serde",
"serde_json",
"signature",
"zeroize",
]
[[package]]
name = "keyboard-types"
version = "0.7.0"
@@ -3431,6 +3642,39 @@ dependencies = [
"redox_syscall 0.9.0",
]
[[package]]
name = "libwebrtc"
version = "0.3.42"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6f5497ff0694ddcee8f88129c78139defa5ec3fc434c3e182906ed0a72372bd9"
dependencies = [
"cxx",
"jni 0.21.1",
"js-sys",
"lazy_static",
"livekit-runtime",
"log",
"parking_lot",
"rtrb",
"serde",
"serde_json",
"thiserror 2.0.19",
"tokio",
"wasm-bindgen",
"wasm-bindgen-futures",
"web-sys",
"webrtc-sys",
]
[[package]]
name = "link-cplusplus"
version = "1.0.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7f78c730aaa7d0b9336a299029ea49f9ee53b0ed06e9202e8cb7db9bae7b8c82"
dependencies = [
"cc",
]
[[package]]
name = "linux-raw-sys"
version = "0.12.1"
@@ -3449,6 +3693,145 @@ version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "11d3d7f243d5c5a8b9bb5d6dd2b1602c0cb0b9db1621bafc7ed66e35ff9fe092"
[[package]]
name = "livekit"
version = "0.7.53"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "aa8ed793e154d63b588397ea7a84cfb3606b6d049f4d24137d9d9e0384617059"
dependencies = [
"base64 0.22.1",
"bmrng",
"bytes",
"chrono",
"futures-util",
"lazy_static",
"libloading 0.8.9",
"libwebrtc",
"livekit-api",
"livekit-common",
"livekit-data-stream",
"livekit-datatrack",
"livekit-protocol",
"livekit-runtime",
"log",
"parking_lot",
"prost",
"semver",
"serde",
"serde_json",
"thiserror 1.0.69",
"tokio",
"tokio-stream",
]
[[package]]
name = "livekit-api"
version = "0.5.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e827d3444235ddccf360fc1d4737034e86ee2ea2c0a696f148ecc08e7249bfd3"
dependencies = [
"base64 0.21.7",
"bytes",
"device-info",
"flate2",
"futures-util",
"hmac",
"http 1.4.2",
"jsonwebtoken",
"livekit-common",
"livekit-protocol",
"livekit-runtime",
"log",
"os_info",
"parking_lot",
"pbjson-types",
"prost",
"rand 0.9.5",
"reqwest 0.12.28",
"scopeguard",
"serde",
"serde_json",
"sha2",
"signature",
"thiserror 2.0.19",
"tokio",
"tokio-tungstenite",
"url",
]
[[package]]
name = "livekit-common"
version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "42a76cd816c062654d105b697ebab136da87d14126ee77b2f13280cb895bcb58"
dependencies = [
"livekit-protocol",
]
[[package]]
name = "livekit-data-stream"
version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "69ad1cca8f05fbe29026d99931884641199df544c33777d1f1b321df6f1031dd"
dependencies = [
"bmrng",
"bytes",
"chrono",
"flate2",
"futures-util",
"livekit-common",
"livekit-protocol",
"log",
"parking_lot",
"prost",
"thiserror 2.0.19",
"tokio",
"uuid",
]
[[package]]
name = "livekit-datatrack"
version = "0.1.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "201bec4becf4db2b0af616a73ff3b2421f6af3693c287b82f5182028ee36e5f5"
dependencies = [
"anyhow",
"bytes",
"from_variants",
"futures-core",
"futures-util",
"indexmap 2.14.0",
"livekit-protocol",
"livekit-runtime",
"log",
"rand 0.9.5",
"thiserror 2.0.19",
"tokio",
"tokio-stream",
]
[[package]]
name = "livekit-protocol"
version = "0.7.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4d26880e94e2f9bab298445e7d86a3794453d211a12ddbd051bd9991a343f9ff"
dependencies = [
"pbjson",
"pbjson-types",
"prost",
"serde",
]
[[package]]
name = "livekit-runtime"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "532e84c6cdc5fe774f2b5d9912597b5f3bea561927a48296d03e24549d21c3f6"
dependencies = [
"tokio",
"tokio-stream",
]
[[package]]
name = "local-ip-address"
version = "0.5.7"
@@ -3656,6 +4039,12 @@ dependencies = [
"windows-sys 0.61.2",
]
[[package]]
name = "multimap"
version = "0.10.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1d87ecb2933e8aeadb3e3a02b828fed80a7528047e68b4f424523a0981a3a084"
[[package]]
name = "ndk"
version = "0.9.0"
@@ -4294,6 +4683,43 @@ dependencies = [
"regex",
]
[[package]]
name = "pbjson"
version = "0.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1030c719b0ec2a2d25a5df729d6cff1acf3cc230bf766f4f97833591f7577b90"
dependencies = [
"base64 0.21.7",
"serde",
]
[[package]]
name = "pbjson-build"
version = "0.6.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2580e33f2292d34be285c5bc3dba5259542b083cfad6037b6d70345f24dcb735"
dependencies = [
"heck 0.4.1",
"itertools 0.11.0",
"prost",
"prost-types",
]
[[package]]
name = "pbjson-types"
version = "0.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "18f596653ba4ac51bdecbb4ef6773bc7f56042dc13927910de1684ad3d32aa12"
dependencies = [
"bytes",
"chrono",
"pbjson",
"pbjson-build",
"prost",
"prost-build",
"serde",
]
[[package]]
name = "percent-encoding"
version = "2.3.2"
@@ -4342,13 +4768,23 @@ dependencies = [
"pest",
]
[[package]]
name = "petgraph"
version = "0.6.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b4c5cc86750666a3ed20bdaf5ca2a0344f9c67674cae0515bec2da16fbaa47db"
dependencies = [
"fixedbitset 0.4.2",
"indexmap 2.14.0",
]
[[package]]
name = "petgraph"
version = "0.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8701b58ea97060d5e5b155d383a69952a60943f0e6dfe30b04c287beb0b27455"
dependencies = [
"fixedbitset",
"fixedbitset 0.5.7",
"hashbrown 0.15.5",
"indexmap 2.14.0",
]
@@ -4673,6 +5109,16 @@ version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "925383efa346730478fb4838dbe9137d2a47675ad789c546d150a6e1dd4ab31c"
[[package]]
name = "prettyplease"
version = "0.2.37"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "479ca8adacdd7ce8f1fb39ce9ecccbfe93a3f1344b3d0d97f20bc0196208f62b"
dependencies = [
"proc-macro2",
"syn 2.0.119",
]
[[package]]
name = "proc-macro-crate"
version = "1.3.1"
@@ -4751,6 +5197,27 @@ dependencies = [
"prost-derive",
]
[[package]]
name = "prost-build"
version = "0.12.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "22505a5c94da8e3b7c2996394d1c933236c4d743e81a410bcca4e6989fc066a4"
dependencies = [
"bytes",
"heck 0.5.0",
"itertools 0.12.1",
"log",
"multimap",
"once_cell",
"petgraph 0.6.5",
"prettyplease",
"prost",
"prost-types",
"regex",
"syn 2.0.119",
"tempfile",
]
[[package]]
name = "prost-derive"
version = "0.12.6"
@@ -4758,7 +5225,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "81bddcdb20abf9501610992b6759a4c888aef7d1a7247ef75e2404275ac24af1"
dependencies = [
"anyhow",
"itertools",
"itertools 0.12.1",
"proc-macro2",
"quote",
"syn 2.0.119",
@@ -5118,6 +5585,7 @@ dependencies = [
"cookie",
"cookie_store",
"encoding_rs",
"futures-channel",
"futures-core",
"futures-util",
"h2 0.4.15",
@@ -5134,6 +5602,7 @@ dependencies = [
"pin-project-lite",
"quinn",
"rustls",
"rustls-native-certs",
"rustls-pki-types",
"serde",
"serde_json",
@@ -5241,6 +5710,12 @@ dependencies = [
"portable-atomic-util",
]
[[package]]
name = "rtrb"
version = "0.3.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4ade083ccbb4bf536df69d1f6432cc23deb7acccff86b183f3923a6fd56a1153"
[[package]]
name = "rust-ini"
version = "0.21.3"
@@ -5403,6 +5878,7 @@ dependencies = [
"tauri",
"tauri-build",
"tauri-plugin-android-fs",
"tauri-plugin-call-lifecycle",
"tauri-plugin-clipboard-manager",
"tauri-plugin-deep-link",
"tauri-plugin-devtools",
@@ -5512,6 +5988,12 @@ version = "1.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"
[[package]]
name = "scratch"
version = "1.0.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d68f2ec51b097e4c1a75b681a8bec621909b5e91f15bb7b840c4f2f7b01148b2"
[[package]]
name = "sctk-adwaita"
version = "0.11.1"
@@ -5525,6 +6007,16 @@ dependencies = [
"tiny-skia",
]
[[package]]
name = "secrecy"
version = "0.10.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e891af845473308773346dc847b2c23ee78fe442e0472ac50e22a18a93d3ae5a"
dependencies = [
"serde",
"zeroize",
]
[[package]]
name = "security-framework"
version = "3.7.0"
@@ -5839,7 +6331,7 @@ version = "3.21.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "84d57bc0c8b9a17920c178daa6bb924850d54a9c97ab45194bb8c17ad66bb660"
dependencies = [
"darling",
"darling 0.23.0",
"proc-macro2",
"quote",
"syn 2.0.119",
@@ -5886,6 +6378,17 @@ dependencies = [
"stable_deref_trait",
]
[[package]]
name = "sha1"
version = "0.10.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a978451301f4db1d02937a4ab3ccce137717b81826e79b7d49ffe3244a13c3b8"
dependencies = [
"cfg-if",
"cpufeatures 0.2.17",
"digest",
]
[[package]]
name = "sha1_smol"
version = "1.0.1"
@@ -5928,6 +6431,15 @@ dependencies = [
"libc",
]
[[package]]
name = "signature"
version = "2.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "77549399552de45a898a580c1b41d445bf730df867cc44e6c0233bbc4b8329de"
dependencies = [
"rand_core 0.6.4",
]
[[package]]
name = "simd-adler32"
version = "0.3.10"
@@ -6161,6 +6673,12 @@ dependencies = [
"quote",
]
[[package]]
name = "strsim"
version = "0.10.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "73473c0e59e6d5812c5dfe2a064a6444949f089e20eec9a2e5506596494e4623"
[[package]]
name = "strsim"
version = "0.11.1"
@@ -6562,6 +7080,19 @@ dependencies = [
"thiserror 2.0.19",
]
[[package]]
name = "tauri-plugin-call-lifecycle"
version = "0.1.0"
dependencies = [
"livekit",
"secrecy",
"serde",
"tauri",
"tauri-plugin",
"thiserror 2.0.19",
"tokio",
]
[[package]]
name = "tauri-plugin-clipboard-manager"
version = "2.3.2"
@@ -6898,7 +7429,7 @@ dependencies = [
"tokio",
"url",
"windows-sys 0.60.2",
"zip",
"zip 4.6.1",
]
[[package]]
@@ -7361,6 +7892,19 @@ dependencies = [
"futures-core",
"pin-project-lite",
"tokio",
"tokio-util",
]
[[package]]
name = "tokio-tungstenite"
version = "0.29.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8f72a05e828585856dacd553fba484c242c46e391fb0e58917c942ee9202915c"
dependencies = [
"futures-util",
"log",
"tokio",
"tungstenite",
]
[[package]]
@@ -7732,7 +8276,7 @@ checksum = "b8765b90061cba6c22b5831f675da109ae5561588290f9fa2317adab2714d5a6"
dependencies = [
"memchr",
"nom",
"petgraph",
"petgraph 0.8.3",
]
[[package]]
@@ -7769,6 +8313,23 @@ version = "0.25.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d2df906b07856748fa3f6e0ad0cbaa047052d4a7dd609e231c4f72cee8c36f31"
[[package]]
name = "tungstenite"
version = "0.29.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6c01152af293afb9c7c2a57e4b559c5620b421f6d133261c60dd2d0cdb38e6b8"
dependencies = [
"bytes",
"data-encoding",
"http 1.4.2",
"httparse",
"log",
"rand 0.9.5",
"sha1",
"thiserror 2.0.19",
"url",
]
[[package]]
name = "typeid"
version = "1.0.3"
@@ -8361,6 +8922,36 @@ dependencies = [
"rustls-pki-types",
]
[[package]]
name = "webrtc-sys"
version = "0.3.39"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7a555de886b8d4961e6c2878ac3ca1f716b75c77f60311c5cf6ed136d0df14e1"
dependencies = [
"cc",
"cxx",
"cxx-build",
"glob",
"log",
"pkg-config",
"webrtc-sys-build",
]
[[package]]
name = "webrtc-sys-build"
version = "0.3.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7d46da6b5a5cbd091fae0400f77189f4ca4807c0d9442b85838a584f28720570"
dependencies = [
"anyhow",
"fs2",
"regex",
"reqwest 0.12.28",
"scratch",
"semver",
"zip 0.6.6",
]
[[package]]
name = "webview2-com"
version = "0.38.2"
@@ -9468,6 +10059,20 @@ name = "zeroize"
version = "1.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e13c156562582aa81c60cb29407084cdb54c4164760106ab78e6c5b0858cf64e"
dependencies = [
"zeroize_derive",
]
[[package]]
name = "zeroize_derive"
version = "1.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3c50655cbb0fe3fc43170059e702f1ce5e19b84cec58dc87b037a09935c2f328"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.119",
]
[[package]]
name = "zerotrie"
@@ -9502,6 +10107,18 @@ dependencies = [
"syn 2.0.119",
]
[[package]]
name = "zip"
version = "0.6.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "760394e246e4c28189f19d488c058bf16f564016aefac5d32bb1f3b51d5e9261"
dependencies = [
"byteorder",
"crc32fast",
"crossbeam-utils",
"flate2",
]
[[package]]
name = "zip"
version = "4.6.1"
+1
View File
@@ -103,6 +103,7 @@ tauri-plugin-updater = { version = "2", optional = true }
tauri-plugin-process = "2"
tauri-plugin-window-state = "2.4.1"
tauri-plugin-global-shortcut = "2"
tauri-plugin-call-lifecycle = { path = "plugins/tauri-plugin-call-lifecycle" }
[target.'cfg(any(target_os = "linux", target_os = "dragonfly", target_os = "freebsd", target_os = "openbsd", target_os = "netbsd"))'.dependencies]
gtk = "0.18"
+2 -1
View File
@@ -9,6 +9,7 @@
"store:default",
"notifications:default",
"process:default",
"dialog:default"
"dialog:default",
"call-lifecycle:default"
]
}
@@ -0,0 +1,20 @@
/.vs
.DS_Store
.Thumbs.db
*.sublime*
.idea/
debug.log
package-lock.json
.vscode/settings.json
yarn.lock
/.tauri
/target
Cargo.lock
node_modules/
dist
# The guest package is consumed directly by Sable's local file dependency.
!dist-js/
!dist-js/**
@@ -0,0 +1,23 @@
[package]
name = "tauri-plugin-call-lifecycle"
version = "0.1.0"
authors = [ "Sable Contributors" ]
description = ""
edition = "2021"
rust-version = "1.77.2"
exclude = ["/examples", "/dist-js", "/guest-js", "/node_modules"]
links = "tauri-plugin-call-lifecycle"
[dependencies]
tauri = { version = "2.11.3" }
livekit = "0.7"
secrecy = { version = "0.10", features = ["serde"] }
serde = "1.0"
thiserror = "2"
tokio = { version = "1", features = ["macros", "rt", "sync"] }
[build-dependencies]
tauri-plugin = { version = "2.6.3", features = ["build"] }
[dev-dependencies]
serde_json = "1.0"
@@ -0,0 +1,8 @@
const COMMANDS: &[&str] = &["connect", "disconnect", "get_state"];
fn main() {
tauri_plugin::Builder::new(COMMANDS)
.android_path("android")
.ios_path("ios")
.build();
}
@@ -0,0 +1,17 @@
'use strict';
var core = require('@tauri-apps/api/core');
async function connect(request) {
return await core.invoke('plugin:call-lifecycle|connect', { payload: request });
}
async function disconnect(request) {
return await core.invoke('plugin:call-lifecycle|disconnect', { payload: request });
}
async function getState() {
return await core.invoke('plugin:call-lifecycle|get_state');
}
exports.connect = connect;
exports.disconnect = disconnect;
exports.getState = getState;
@@ -0,0 +1,23 @@
export interface ConnectRequest {
connectionId: string;
serverUrl: string;
participantToken: string;
}
export interface DisconnectRequest {
connectionId: string;
}
export type ConnectionState = 'idle' | 'connecting' | 'connected' | 'reconnecting' | 'disconnecting';
export interface CallState {
revision: number;
state: ConnectionState;
connectionId: string | null;
}
export interface CallLifecycleError {
revision: number;
code: string;
message: string;
connectionId: string | null;
}
export declare function connect(request: ConnectRequest): Promise<CallState>;
export declare function disconnect(request: DisconnectRequest): Promise<CallState>;
export declare function getState(): Promise<CallState>;
@@ -0,0 +1,13 @@
import { invoke } from '@tauri-apps/api/core';
async function connect(request) {
return await invoke('plugin:call-lifecycle|connect', { payload: request });
}
async function disconnect(request) {
return await invoke('plugin:call-lifecycle|disconnect', { payload: request });
}
async function getState() {
return await invoke('plugin:call-lifecycle|get_state');
}
export { connect, disconnect, getState };
@@ -0,0 +1,43 @@
import { invoke } from '@tauri-apps/api/core'
export interface ConnectRequest {
connectionId: string
serverUrl: string
participantToken: string
}
export interface DisconnectRequest {
connectionId: string
}
export type ConnectionState =
| 'idle'
| 'connecting'
| 'connected'
| 'reconnecting'
| 'disconnecting'
export interface CallState {
revision: number
state: ConnectionState
connectionId: string | null
}
export interface CallLifecycleError {
revision: number
code: string
message: string
connectionId: string | null
}
export async function connect(request: ConnectRequest): Promise<CallState> {
return await invoke<CallState>('plugin:call-lifecycle|connect', { payload: request })
}
export async function disconnect(request: DisconnectRequest): Promise<CallState> {
return await invoke<CallState>('plugin:call-lifecycle|disconnect', { payload: request })
}
export async function getState(): Promise<CallState> {
return await invoke<CallState>('plugin:call-lifecycle|get_state')
}
@@ -0,0 +1,30 @@
{
"name": "tauri-plugin-call-lifecycle-api",
"version": "0.1.0",
"author": "Sable Contributors",
"description": "",
"type": "module",
"types": "./dist-js/index.d.ts",
"main": "./dist-js/index.cjs",
"module": "./dist-js/index.js",
"exports": {
"types": "./dist-js/index.d.ts",
"import": "./dist-js/index.js",
"require": "./dist-js/index.cjs"
},
"files": ["dist-js"],
"scripts": {
"build": "rollup -c",
"prepublishOnly": "pnpm build",
"pretest": "pnpm build"
},
"dependencies": {
"@tauri-apps/api": "^2.0.0"
},
"devDependencies": {
"@rollup/plugin-typescript": "^12.0.0",
"rollup": "^4.9.6",
"typescript": "^6.0.0",
"tslib": "^2.6.2"
}
}
@@ -0,0 +1,13 @@
# Automatically generated - DO NOT EDIT!
"$schema" = "../../schemas/schema.json"
[[permission]]
identifier = "allow-connect"
description = "Enables the connect command without any pre-configured scope."
commands.allow = ["connect"]
[[permission]]
identifier = "deny-connect"
description = "Denies the connect command without any pre-configured scope."
commands.deny = ["connect"]
@@ -0,0 +1,13 @@
# Automatically generated - DO NOT EDIT!
"$schema" = "../../schemas/schema.json"
[[permission]]
identifier = "allow-disconnect"
description = "Enables the disconnect command without any pre-configured scope."
commands.allow = ["disconnect"]
[[permission]]
identifier = "deny-disconnect"
description = "Denies the disconnect command without any pre-configured scope."
commands.deny = ["disconnect"]
@@ -0,0 +1,13 @@
# Automatically generated - DO NOT EDIT!
"$schema" = "../../schemas/schema.json"
[[permission]]
identifier = "allow-get-state"
description = "Enables the get_state command without any pre-configured scope."
commands.allow = ["get_state"]
[[permission]]
identifier = "deny-get-state"
description = "Denies the get_state command without any pre-configured scope."
commands.deny = ["get_state"]
@@ -0,0 +1,97 @@
## Default Permission
Default permissions for the plugin
#### This default permission set includes the following:
- `allow-connect`
- `allow-disconnect`
- `allow-get-state`
## Permission Table
<table>
<tr>
<th>Identifier</th>
<th>Description</th>
</tr>
<tr>
<td>
`call-lifecycle:allow-connect`
</td>
<td>
Enables the connect command without any pre-configured scope.
</td>
</tr>
<tr>
<td>
`call-lifecycle:deny-connect`
</td>
<td>
Denies the connect command without any pre-configured scope.
</td>
</tr>
<tr>
<td>
`call-lifecycle:allow-disconnect`
</td>
<td>
Enables the disconnect command without any pre-configured scope.
</td>
</tr>
<tr>
<td>
`call-lifecycle:deny-disconnect`
</td>
<td>
Denies the disconnect command without any pre-configured scope.
</td>
</tr>
<tr>
<td>
`call-lifecycle:allow-get-state`
</td>
<td>
Enables the get_state command without any pre-configured scope.
</td>
</tr>
<tr>
<td>
`call-lifecycle:deny-get-state`
</td>
<td>
Denies the get_state command without any pre-configured scope.
</td>
</tr>
</table>
@@ -0,0 +1,3 @@
[default]
description = "Default permissions for the plugin"
permissions = ["allow-connect", "allow-disconnect", "allow-get-state"]
@@ -0,0 +1,342 @@
{
"$schema": "http://json-schema.org/draft-07/schema#",
"title": "PermissionFile",
"description": "Permission file that can define a default permission, a set of permissions or a list of inlined permissions.",
"type": "object",
"properties": {
"default": {
"description": "The default permission set for the plugin",
"anyOf": [
{
"$ref": "#/definitions/DefaultPermission"
},
{
"type": "null"
}
]
},
"set": {
"description": "A list of permissions sets defined",
"type": "array",
"items": {
"$ref": "#/definitions/PermissionSet"
}
},
"permission": {
"description": "A list of inlined permissions",
"default": [],
"type": "array",
"items": {
"$ref": "#/definitions/Permission"
}
}
},
"definitions": {
"DefaultPermission": {
"description": "The default permission set of the plugin.\n\nWorks similarly to a permission with the \"default\" identifier.",
"type": "object",
"required": [
"permissions"
],
"properties": {
"version": {
"description": "The version of the permission.",
"type": [
"integer",
"null"
],
"format": "uint64",
"minimum": 1.0
},
"description": {
"description": "Human-readable description of what the permission does. Tauri convention is to use `<h4>` headings in markdown content for Tauri documentation generation purposes.",
"type": [
"string",
"null"
]
},
"permissions": {
"description": "All permissions this set contains.",
"type": "array",
"items": {
"type": "string"
}
}
}
},
"PermissionSet": {
"description": "A set of direct permissions grouped together under a new name.",
"type": "object",
"required": [
"description",
"identifier",
"permissions"
],
"properties": {
"identifier": {
"description": "A unique identifier for the permission.",
"type": "string"
},
"description": {
"description": "Human-readable description of what the permission does.",
"type": "string"
},
"permissions": {
"description": "All permissions this set contains.",
"type": "array",
"items": {
"$ref": "#/definitions/PermissionKind"
}
}
}
},
"Permission": {
"description": "Descriptions of explicit privileges of commands.\n\nIt can enable commands to be accessible in the frontend of the application.\n\nIf the scope is defined it can be used to fine grain control the access of individual or multiple commands.",
"type": "object",
"required": [
"identifier"
],
"properties": {
"version": {
"description": "The version of the permission.",
"type": [
"integer",
"null"
],
"format": "uint64",
"minimum": 1.0
},
"identifier": {
"description": "A unique identifier for the permission.",
"type": "string"
},
"description": {
"description": "Human-readable description of what the permission does. Tauri internal convention is to use `<h4>` headings in markdown content for Tauri documentation generation purposes.",
"type": [
"string",
"null"
]
},
"commands": {
"description": "Allowed or denied commands when using this permission.",
"default": {
"allow": [],
"deny": []
},
"allOf": [
{
"$ref": "#/definitions/Commands"
}
]
},
"scope": {
"description": "Allowed or denied scoped when using this permission.",
"allOf": [
{
"$ref": "#/definitions/Scopes"
}
]
},
"platforms": {
"description": "Target platforms this permission applies. By default all platforms are affected by this permission.",
"type": [
"array",
"null"
],
"items": {
"$ref": "#/definitions/Target"
}
}
}
},
"Commands": {
"description": "Allowed and denied commands inside a permission.\n\nIf two commands clash inside of `allow` and `deny`, it should be denied by default.",
"type": "object",
"properties": {
"allow": {
"description": "Allowed command.",
"default": [],
"type": "array",
"items": {
"type": "string"
}
},
"deny": {
"description": "Denied command, which takes priority.",
"default": [],
"type": "array",
"items": {
"type": "string"
}
}
}
},
"Scopes": {
"description": "An argument for fine grained behavior control of Tauri commands.\n\nIt can be of any serde serializable type and is used to allow or prevent certain actions inside a Tauri command. The configured scope is passed to the command and will be enforced by the command implementation.\n\n## Example\n\n```json { \"allow\": [{ \"path\": \"$HOME/**\" }], \"deny\": [{ \"path\": \"$HOME/secret.txt\" }] } ```",
"type": "object",
"properties": {
"allow": {
"description": "Data that defines what is allowed by the scope.",
"type": [
"array",
"null"
],
"items": {
"$ref": "#/definitions/Value"
}
},
"deny": {
"description": "Data that defines what is denied by the scope. This should be prioritized by validation logic.",
"type": [
"array",
"null"
],
"items": {
"$ref": "#/definitions/Value"
}
}
}
},
"Value": {
"description": "All supported ACL values.",
"anyOf": [
{
"description": "Represents a null JSON value.",
"type": "null"
},
{
"description": "Represents a [`bool`].",
"type": "boolean"
},
{
"description": "Represents a valid ACL [`Number`].",
"allOf": [
{
"$ref": "#/definitions/Number"
}
]
},
{
"description": "Represents a [`String`].",
"type": "string"
},
{
"description": "Represents a list of other [`Value`]s.",
"type": "array",
"items": {
"$ref": "#/definitions/Value"
}
},
{
"description": "Represents a map of [`String`] keys to [`Value`]s.",
"type": "object",
"additionalProperties": {
"$ref": "#/definitions/Value"
}
}
]
},
"Number": {
"description": "A valid ACL number.",
"anyOf": [
{
"description": "Represents an [`i64`].",
"type": "integer",
"format": "int64"
},
{
"description": "Represents a [`f64`].",
"type": "number",
"format": "double"
}
]
},
"Target": {
"description": "Platform target.",
"oneOf": [
{
"description": "MacOS.",
"type": "string",
"enum": [
"macOS"
]
},
{
"description": "Windows.",
"type": "string",
"enum": [
"windows"
]
},
{
"description": "Linux.",
"type": "string",
"enum": [
"linux"
]
},
{
"description": "Android.",
"type": "string",
"enum": [
"android"
]
},
{
"description": "iOS.",
"type": "string",
"enum": [
"iOS"
]
}
]
},
"PermissionKind": {
"type": "string",
"oneOf": [
{
"description": "Enables the connect command without any pre-configured scope.",
"type": "string",
"const": "allow-connect",
"markdownDescription": "Enables the connect command without any pre-configured scope."
},
{
"description": "Denies the connect command without any pre-configured scope.",
"type": "string",
"const": "deny-connect",
"markdownDescription": "Denies the connect command without any pre-configured scope."
},
{
"description": "Enables the disconnect command without any pre-configured scope.",
"type": "string",
"const": "allow-disconnect",
"markdownDescription": "Enables the disconnect command without any pre-configured scope."
},
{
"description": "Denies the disconnect command without any pre-configured scope.",
"type": "string",
"const": "deny-disconnect",
"markdownDescription": "Denies the disconnect command without any pre-configured scope."
},
{
"description": "Enables the get_state command without any pre-configured scope.",
"type": "string",
"const": "allow-get-state",
"markdownDescription": "Enables the get_state command without any pre-configured scope."
},
{
"description": "Denies the get_state command without any pre-configured scope.",
"type": "string",
"const": "deny-get-state",
"markdownDescription": "Denies the get_state command without any pre-configured scope."
},
{
"description": "Default permissions for the plugin\n#### This default permission set includes:\n\n- `allow-connect`\n- `allow-disconnect`\n- `allow-get-state`",
"type": "string",
"const": "default",
"markdownDescription": "Default permissions for the plugin\n#### This default permission set includes:\n\n- `allow-connect`\n- `allow-disconnect`\n- `allow-get-state`"
}
]
}
}
}
@@ -0,0 +1,32 @@
import { readFileSync } from 'node:fs'
import { dirname, join } from 'node:path'
import { cwd } from 'node:process'
import typescript from '@rollup/plugin-typescript'
const pkg = JSON.parse(readFileSync(join(cwd(), 'package.json'), 'utf8'))
export default {
input: 'guest-js/index.ts',
output: [
{
file: pkg.exports.import,
format: 'esm'
},
{
file: pkg.exports.require,
format: 'cjs'
}
],
plugins: [
typescript({
declaration: true,
declarationDir: dirname(pkg.exports.import),
rootDir: 'guest-js'
})
],
external: [
/^@tauri-apps\/api/,
...Object.keys(pkg.dependencies || {}),
...Object.keys(pkg.peerDependencies || {})
]
}
@@ -0,0 +1,634 @@
use std::marker::PhantomData;
use livekit::{Room, RoomEvent, RoomOptions};
use secrecy::ExposeSecret;
use tauri::{async_runtime, AppHandle, Emitter, Runtime};
use tokio::sync::{mpsc, oneshot};
#[cfg(test)]
use std::sync::{
atomic::{AtomicUsize, Ordering},
Arc,
};
use crate::error::{Error, Result};
use crate::models::{
CallLifecycleError, CallState, ConnectRequest, ConnectionState, DisconnectRequest,
};
pub(crate) const STATE_EVENT: &str = "plugin:call-lifecycle://state";
pub(crate) const ERROR_EVENT: &str = "plugin:call-lifecycle://error";
type RoomEvents = mpsc::UnboundedReceiver<RoomEvent>;
struct ConnectedRoom {
room: OwnedRoom,
events: RoomEvents,
}
enum OwnedRoom {
LiveKit(Room),
#[cfg(test)]
Fake(Arc<AtomicUsize>),
}
impl OwnedRoom {
async fn close(self) -> std::result::Result<(), ()> {
match self {
Self::LiveKit(room) => room.close().await.map_err(|_| ()),
#[cfg(test)]
Self::Fake(closes) => {
closes.fetch_add(1, Ordering::SeqCst);
Ok(())
}
}
}
}
pub(crate) enum Command {
Connect(ConnectRequest, oneshot::Sender<Result<CallState>>),
Disconnect(DisconnectRequest, oneshot::Sender<Result<CallState>>),
GetState(oneshot::Sender<CallState>),
}
enum InternalMessage {
ConnectFinished {
connection_id: String,
room: Option<ConnectedRoom>,
},
}
struct PendingConnection {
connection_id: String,
task: async_runtime::JoinHandle<()>,
response: oneshot::Sender<Result<CallState>>,
}
struct ActiveConnection {
connection_id: String,
room: OwnedRoom,
events: RoomEvents,
}
pub struct CallLifecycle<R: Runtime> {
commands: mpsc::Sender<Command>,
_runtime: PhantomData<fn() -> R>,
}
impl<R: Runtime> CallLifecycle<R> {
pub(crate) fn new(app: AppHandle<R>) -> Self {
let (commands, command_rx) = mpsc::channel(32);
let (internal_tx, internal_rx) = mpsc::unbounded_channel();
async_runtime::spawn(run_actor(app, command_rx, internal_tx, internal_rx));
Self {
commands,
_runtime: PhantomData,
}
}
pub async fn connect(&self, request: ConnectRequest) -> Result<CallState> {
let (response, result) = oneshot::channel();
self.commands
.send(Command::Connect(request, response))
.await
.map_err(|_| Error::ActorUnavailable)?;
result.await.map_err(|_| Error::ActorUnavailable)?
}
pub async fn disconnect(&self, request: DisconnectRequest) -> Result<CallState> {
let (response, result) = oneshot::channel();
self.commands
.send(Command::Disconnect(request, response))
.await
.map_err(|_| Error::ActorUnavailable)?;
result.await.map_err(|_| Error::ActorUnavailable)?
}
pub async fn get_state(&self) -> Result<CallState> {
let (response, result) = oneshot::channel();
self.commands
.send(Command::GetState(response))
.await
.map_err(|_| Error::ActorUnavailable)?;
result.await.map_err(|_| Error::ActorUnavailable)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum ConnectDecision {
Start,
Same,
Busy,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum DisconnectDecision {
None,
CancelPending,
CloseActive,
Stale,
}
#[derive(Debug, Clone)]
struct StateMachine {
state: ConnectionState,
revision: u64,
connection_id: Option<String>,
}
impl Default for StateMachine {
fn default() -> Self {
Self {
state: ConnectionState::Idle,
revision: 0,
connection_id: None,
}
}
}
impl StateMachine {
fn snapshot(&self) -> CallState {
CallState {
revision: self.revision,
state: self.state,
connection_id: self.connection_id.clone(),
}
}
fn connect_decision(&self, connection_id: &str) -> ConnectDecision {
match self.connection_id.as_deref() {
None => ConnectDecision::Start,
Some(current) if current == connection_id => ConnectDecision::Same,
Some(_) => ConnectDecision::Busy,
}
}
fn disconnect_decision(&self, connection_id: &str) -> DisconnectDecision {
if self.connection_id.as_deref() != Some(connection_id) {
return if self.connection_id.is_some() {
DisconnectDecision::Stale
} else {
DisconnectDecision::None
};
}
match self.state {
ConnectionState::Connecting => DisconnectDecision::CancelPending,
ConnectionState::Idle | ConnectionState::Disconnecting => DisconnectDecision::None,
ConnectionState::Connected | ConnectionState::Reconnecting => {
DisconnectDecision::CloseActive
}
}
}
fn transition(&mut self, state: ConnectionState, connection_id: Option<String>) {
self.revision += 1;
self.state = state;
self.connection_id = connection_id;
}
}
struct Actor<R: Runtime> {
app: AppHandle<R>,
commands: mpsc::Receiver<Command>,
internal_tx: mpsc::UnboundedSender<InternalMessage>,
internal_rx: mpsc::UnboundedReceiver<InternalMessage>,
machine: StateMachine,
pending: Option<PendingConnection>,
active: Option<ActiveConnection>,
}
async fn run_actor<R: Runtime>(
app: AppHandle<R>,
commands: mpsc::Receiver<Command>,
internal_tx: mpsc::UnboundedSender<InternalMessage>,
internal_rx: mpsc::UnboundedReceiver<InternalMessage>,
) {
let mut actor = Actor {
app,
commands,
internal_tx,
internal_rx,
machine: StateMachine::default(),
pending: None,
active: None,
};
actor.emit_state();
loop {
if actor.active.is_some() {
tokio::select! {
command = actor.commands.recv() => {
let Some(command) = command else { break };
actor.handle_command(command).await;
}
internal = actor.internal_rx.recv() => {
let Some(internal) = internal else { break };
actor.handle_internal(internal).await;
}
event = receive_room_event(&mut actor.active) => {
match event {
Some(event) => actor.handle_room_event(event).await,
None => {
close_active_connection(actor.active.take()).await;
actor.transition(ConnectionState::Idle, None);
}
}
}
}
} else {
tokio::select! {
command = actor.commands.recv() => {
let Some(command) = command else { break };
actor.handle_command(command).await;
}
internal = actor.internal_rx.recv() => {
let Some(internal) = internal else { break };
actor.handle_internal(internal).await;
}
}
}
}
actor.cleanup().await;
}
async fn receive_room_event(active: &mut Option<ActiveConnection>) -> Option<RoomEvent> {
match active.as_mut() {
Some(active) => active.events.recv().await,
None => std::future::pending().await,
}
}
impl<R: Runtime> Actor<R> {
fn emit_state(&self) {
let _ = self.app.emit(STATE_EVENT, self.machine.snapshot());
}
fn emit_error(&self, error: &Error, connection_id: Option<String>) {
let payload = CallLifecycleError {
revision: self.machine.revision,
code: error.code(),
message: error.message(),
connection_id,
};
let _ = self.app.emit(ERROR_EVENT, payload);
}
fn transition(&mut self, state: ConnectionState, connection_id: Option<String>) {
self.machine.transition(state, connection_id);
self.emit_state();
}
async fn handle_command(&mut self, command: Command) {
match command {
Command::Connect(request, response) => self.handle_connect(request, response).await,
Command::Disconnect(request, response) => {
self.handle_disconnect(request, response).await
}
Command::GetState(response) => {
let _ = response.send(self.machine.snapshot());
}
}
}
async fn handle_connect(
&mut self,
request: ConnectRequest,
response: oneshot::Sender<Result<CallState>>,
) {
match self.machine.connect_decision(&request.connection_id) {
ConnectDecision::Same => {
let _ = response.send(Ok(self.machine.snapshot()));
}
ConnectDecision::Busy => {
let error = Error::Busy;
self.emit_error(&error, Some(request.connection_id));
let _ = response.send(Err(error));
}
ConnectDecision::Start => {
let connection_id = request.connection_id.clone();
self.transition(ConnectionState::Connecting, Some(connection_id.clone()));
let internal_tx = self.internal_tx.clone();
let task = async_runtime::spawn(async move {
let room = Room::connect(
&request.server_url,
request.participant_token.expose_secret(),
RoomOptions::default(),
)
.await
.ok()
.map(|(room, events)| ConnectedRoom {
room: OwnedRoom::LiveKit(room),
events,
});
let _ = internal_tx.send(InternalMessage::ConnectFinished {
connection_id,
room,
});
});
self.pending = Some(PendingConnection {
connection_id: request.connection_id,
task,
response,
});
}
}
}
async fn handle_disconnect(
&mut self,
request: DisconnectRequest,
response: oneshot::Sender<Result<CallState>>,
) {
match self.machine.disconnect_decision(&request.connection_id) {
DisconnectDecision::None => {
let _ = response.send(Ok(self.machine.snapshot()));
}
DisconnectDecision::Stale => {
let error = Error::StaleConnection;
self.emit_error(&error, Some(request.connection_id));
let _ = response.send(Err(error));
}
DisconnectDecision::CancelPending => {
if let Some(pending) = self.pending.take() {
pending.task.abort();
let _ = pending.task.await;
close_queued_rooms(&mut self.internal_rx).await;
}
self.transition(ConnectionState::Disconnecting, Some(request.connection_id));
self.transition(ConnectionState::Idle, None);
let _ = response.send(Ok(self.machine.snapshot()));
}
DisconnectDecision::CloseActive => {
let active = self.active.take();
self.transition(
ConnectionState::Disconnecting,
Some(request.connection_id.clone()),
);
let Some(active) = active else {
self.transition(ConnectionState::Idle, None);
let _ = response.send(Ok(self.machine.snapshot()));
return;
};
let close_result = active.room.close().await;
self.transition(ConnectionState::Idle, None);
if close_result.is_err() {
let error = Error::CloseFailed;
self.emit_error(&error, Some(active.connection_id));
let _ = response.send(Err(error));
} else {
let _ = response.send(Ok(self.machine.snapshot()));
}
}
}
}
async fn handle_internal(&mut self, message: InternalMessage) {
match message {
InternalMessage::ConnectFinished {
connection_id,
room,
} => {
let Some(pending) = self.pending.take() else {
close_connected_room(room).await;
return;
};
if pending.connection_id != connection_id {
close_connected_room(room).await;
let _ = pending.task.await;
return;
}
let _ = pending.task.await;
let Some(ConnectedRoom { room, events }) = room else {
let error = Error::ConnectFailed;
self.emit_error(&error, Some(connection_id));
self.transition(ConnectionState::Idle, None);
let _ = pending.response.send(Err(error));
return;
};
self.active = Some(ActiveConnection {
connection_id: connection_id.clone(),
room,
events,
});
self.transition(ConnectionState::Connected, Some(connection_id));
let _ = pending.response.send(Ok(self.machine.snapshot()));
}
}
}
async fn handle_room_event(&mut self, event: RoomEvent) {
match event {
RoomEvent::Reconnecting => {
if let Some(connection_id) = self.machine.connection_id.clone() {
self.transition(ConnectionState::Reconnecting, Some(connection_id));
}
}
RoomEvent::Reconnected => {
if let Some(connection_id) = self.machine.connection_id.clone() {
self.transition(ConnectionState::Connected, Some(connection_id));
}
}
RoomEvent::Disconnected { .. } => {
close_active_connection(self.active.take()).await;
self.transition(ConnectionState::Idle, None);
}
_ => {}
}
}
async fn cleanup(&mut self) {
if let Some(pending) = self.pending.take() {
pending.task.abort();
let _ = pending.task.await;
let _ = pending.response.send(Err(Error::ActorUnavailable));
}
close_queued_rooms(&mut self.internal_rx).await;
close_active_connection(self.active.take()).await;
}
}
async fn close_active_connection(active: Option<ActiveConnection>) {
if let Some(active) = active {
let _ = active.room.close().await;
}
}
async fn close_connected_room(room: Option<ConnectedRoom>) {
if let Some(room) = room {
let _ = room.room.close().await;
}
}
async fn close_queued_rooms(internal_rx: &mut mpsc::UnboundedReceiver<InternalMessage>) {
while let Ok(message) = internal_rx.try_recv() {
let InternalMessage::ConnectFinished {
room: Some(room), ..
} = message
else {
continue;
};
close_connected_room(Some(room)).await;
}
}
#[cfg(test)]
mod tests {
use super::{ConnectDecision, DisconnectDecision, StateMachine};
use crate::error::Error;
use crate::models::{CallLifecycleError, ConnectRequest, ConnectionState};
use secrecy::SecretString;
use std::sync::{
atomic::{AtomicUsize, Ordering},
Arc,
};
#[test]
fn same_id_is_idempotent_and_different_id_is_busy() {
let mut machine = StateMachine::default();
assert_eq!(machine.connect_decision("one"), ConnectDecision::Start);
machine.transition(ConnectionState::Connecting, Some("one".into()));
assert_eq!(machine.connect_decision("one"), ConnectDecision::Same);
assert_eq!(machine.connect_decision("two"), ConnectDecision::Busy);
assert_eq!(machine.snapshot().revision, 1);
}
#[test]
fn stale_disconnect_does_not_close_active_connection() {
let mut machine = StateMachine::default();
machine.transition(ConnectionState::Connected, Some("one".into()));
assert_eq!(
machine.disconnect_decision("two"),
DisconnectDecision::Stale
);
assert_eq!(machine.snapshot().state, ConnectionState::Connected);
assert_eq!(
machine.disconnect_decision("one"),
DisconnectDecision::CloseActive
);
}
#[test]
fn mismatched_disconnect_is_typed_stale_error() {
let mut machine = StateMachine::default();
machine.transition(ConnectionState::Connected, Some("one".into()));
assert_eq!(
machine.disconnect_decision("two"),
DisconnectDecision::Stale
);
assert_eq!(machine.snapshot().state, ConnectionState::Connected);
assert_eq!(machine.snapshot().connection_id.as_deref(), Some("one"));
}
#[test]
fn participant_token_debug_is_redacted() {
let request = ConnectRequest {
connection_id: "connection".into(),
server_url: "wss://livekit.example".into(),
participant_token: SecretString::from("secret-jwt"),
};
let debug = format!("{request:?}");
assert!(!debug.contains("secret-jwt"));
assert!(debug.contains("REDACTED"));
}
#[test]
fn errors_and_states_have_stable_sanitized_shapes() {
let error = serde_json::to_value(Error::StaleConnection).unwrap();
assert_eq!(
error,
serde_json::json!({
"code": "stale_connection",
"message": "connection ID does not match active call"
})
);
let state = serde_json::to_value(ConnectionState::Reconnecting).unwrap();
assert_eq!(state, serde_json::json!("reconnecting"));
let event = CallLifecycleError {
revision: 7,
code: "stale_connection",
message: "connection ID does not match active call",
connection_id: Some("old".into()),
};
let event = serde_json::to_value(event).unwrap();
assert_eq!(event["revision"], 7);
}
#[tokio::test]
async fn queued_completed_room_is_closed_once_when_disconnect_wins() {
let closes = Arc::new(AtomicUsize::new(0));
let (sender, mut receiver) = tokio::sync::mpsc::unbounded_channel();
let (_events_sender, events) = tokio::sync::mpsc::unbounded_channel();
sender
.send(super::InternalMessage::ConnectFinished {
connection_id: "one".into(),
room: Some(super::ConnectedRoom {
room: super::OwnedRoom::Fake(closes.clone()),
events,
}),
})
.unwrap();
super::close_queued_rooms(&mut receiver).await;
super::close_queued_rooms(&mut receiver).await;
assert_eq!(closes.load(Ordering::SeqCst), 1);
}
#[tokio::test]
async fn terminal_active_room_paths_close_owned_rooms_once() {
let event_receiver_closes = Arc::new(AtomicUsize::new(0));
let (_events_sender, events) = tokio::sync::mpsc::unbounded_channel::<livekit::RoomEvent>();
super::close_active_connection(Some(super::ActiveConnection {
connection_id: "event-ended".into(),
room: super::OwnedRoom::Fake(event_receiver_closes.clone()),
events,
}))
.await;
let disconnected_closes = Arc::new(AtomicUsize::new(0));
let (_events_sender, events) = tokio::sync::mpsc::unbounded_channel::<livekit::RoomEvent>();
super::close_active_connection(Some(super::ActiveConnection {
connection_id: "disconnected".into(),
room: super::OwnedRoom::Fake(disconnected_closes.clone()),
events,
}))
.await;
assert_eq!(event_receiver_closes.load(Ordering::SeqCst), 1);
assert_eq!(disconnected_closes.load(Ordering::SeqCst), 1);
}
#[tokio::test]
async fn stale_completion_closes_owned_room_once() {
let closes = Arc::new(AtomicUsize::new(0));
let (_events_sender, events) = tokio::sync::mpsc::unbounded_channel::<livekit::RoomEvent>();
super::close_connected_room(Some(super::ConnectedRoom {
room: super::OwnedRoom::Fake(closes.clone()),
events,
}))
.await;
assert_eq!(closes.load(Ordering::SeqCst), 1);
}
#[test]
fn explicit_disconnect_has_one_close_transition() {
let mut machine = StateMachine::default();
machine.transition(ConnectionState::Connected, Some("one".into()));
assert_eq!(
machine.disconnect_decision("one"),
DisconnectDecision::CloseActive
);
machine.transition(ConnectionState::Disconnecting, Some("one".into()));
machine.transition(ConnectionState::Idle, None);
assert_eq!(machine.disconnect_decision("one"), DisconnectDecision::None);
assert_eq!(machine.snapshot().revision, 3);
}
}
@@ -0,0 +1,26 @@
use tauri::{command, AppHandle, Runtime};
use crate::models::*;
use crate::CallLifecycleExt;
use crate::Result;
#[command]
pub(crate) async fn connect<R: Runtime>(
app: AppHandle<R>,
payload: ConnectRequest,
) -> Result<CallState> {
app.call_lifecycle().connect(payload).await
}
#[command]
pub(crate) async fn disconnect<R: Runtime>(
app: AppHandle<R>,
payload: DisconnectRequest,
) -> Result<CallState> {
app.call_lifecycle().disconnect(payload).await
}
#[command]
pub(crate) async fn get_state<R: Runtime>(app: AppHandle<R>) -> Result<CallState> {
app.call_lifecycle().get_state().await
}
@@ -0,0 +1,51 @@
use serde::{ser::SerializeStruct, ser::Serializer, Serialize};
pub type Result<T> = std::result::Result<T, Error>;
#[derive(Debug, thiserror::Error)]
pub enum Error {
#[error("call is already active")]
Busy,
#[error("call connection failed")]
ConnectFailed,
#[error("connection ID does not match active call")]
StaleConnection,
#[error("call shutdown failed")]
CloseFailed,
#[error("call lifecycle actor unavailable")]
ActorUnavailable,
}
impl Serialize for Error {
fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
where
S: Serializer,
{
let mut error = serializer.serialize_struct("Error", 2)?;
error.serialize_field("code", self.code())?;
error.serialize_field("message", self.message())?;
error.end()
}
}
impl Error {
pub fn code(&self) -> &'static str {
match self {
Self::Busy => "busy",
Self::ConnectFailed => "connect_failed",
Self::StaleConnection => "stale_connection",
Self::CloseFailed => "close_failed",
Self::ActorUnavailable => "actor_unavailable",
}
}
pub fn message(&self) -> &'static str {
match self {
Self::Busy => "another call is active",
Self::ConnectFailed => "call connection failed",
Self::StaleConnection => "connection ID does not match active call",
Self::CloseFailed => "call shutdown failed",
Self::ActorUnavailable => "call lifecycle unavailable",
}
}
}
@@ -0,0 +1,42 @@
use tauri::{
plugin::{Builder, TauriPlugin},
Manager, Runtime,
};
pub use models::*;
mod actor;
mod commands;
mod error;
mod models;
pub use error::{Error, Result};
use actor::CallLifecycle;
/// Extensions to [`tauri::App`], [`tauri::AppHandle`] and [`tauri::Window`] to access the call-lifecycle APIs.
pub trait CallLifecycleExt<R: Runtime> {
fn call_lifecycle(&self) -> &CallLifecycle<R>;
}
impl<R: Runtime, T: Manager<R>> crate::CallLifecycleExt<R> for T {
fn call_lifecycle(&self) -> &CallLifecycle<R> {
self.state::<CallLifecycle<R>>().inner()
}
}
/// Initializes the plugin.
pub fn init<R: Runtime>() -> TauriPlugin<R> {
Builder::new("call-lifecycle")
.invoke_handler(tauri::generate_handler![
commands::connect,
commands::disconnect,
commands::get_state
])
.setup(|app, _api| {
let call_lifecycle = CallLifecycle::new(app.clone());
app.manage(call_lifecycle);
Ok(())
})
.build()
}
@@ -0,0 +1,43 @@
use secrecy::SecretString;
use serde::{Deserialize, Serialize};
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ConnectRequest {
pub connection_id: String,
pub server_url: String,
pub participant_token: SecretString,
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct DisconnectRequest {
pub connection_id: String,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum ConnectionState {
Idle,
Connecting,
Connected,
Reconnecting,
Disconnecting,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CallState {
pub revision: u64,
pub state: ConnectionState,
pub connection_id: Option<String>,
}
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CallLifecycleError {
pub revision: u64,
pub code: &'static str,
pub message: &'static str,
pub connection_id: Option<String>,
}
@@ -0,0 +1,14 @@
{
"compilerOptions": {
"target": "es2021",
"module": "esnext",
"moduleResolution": "bundler",
"skipLibCheck": true,
"strict": true,
"noUnusedLocals": true,
"noImplicitAny": true,
"noEmit": true
},
"include": ["guest-js/*.ts"],
"exclude": ["dist-js", "node_modules"]
}
+2 -1
View File
@@ -345,7 +345,8 @@ pub fn run() {
#[cfg(desktop)]
let builder = builder
.plugin(tauri_plugin_process::init())
.plugin(tauri_plugin_dialog::init());
.plugin(tauri_plugin_dialog::init())
.plugin(tauri_plugin_call_lifecycle::init());
#[cfg(target_os = "ios")]
let builder = builder
+17 -6
View File
@@ -1,4 +1,5 @@
import to from 'await-to-js';
import type { LivekitTransportConfig } from '$types/matrix-sdk';
import { trimTrailingSlash } from './utils/common';
export enum AutoDiscoveryAction {
@@ -22,12 +23,22 @@ export type AutoDiscoveryInfo = Record<string, unknown> & {
account?: string;
issuer?: string;
};
'org.matrix.msc4143.rtc_foci'?: [
{
livekit_service_url: string;
type: 'livekit';
},
];
'org.matrix.msc4143.rtc_foci'?: LivekitTransportConfig[];
};
export const getLivekitTransports = (
discovery: Pick<AutoDiscoveryInfo, 'org.matrix.msc4143.rtc_foci'> | undefined
): LivekitTransportConfig[] => {
const foci = discovery?.['org.matrix.msc4143.rtc_foci'];
if (!Array.isArray(foci)) return [];
return foci.filter(
(focus): focus is LivekitTransportConfig =>
typeof focus === 'object' &&
focus !== null &&
focus.type === 'livekit' &&
typeof focus.livekit_service_url === 'string'
);
};
export const autoDiscovery = async (
@@ -0,0 +1,142 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
import type { IOpenIDToken, MatrixClient } from '$types/matrix-sdk';
const fetchMock = vi.hoisted(() => vi.fn<typeof globalThis.fetch>());
vi.mock('$utils/fetch', () => ({ fetch: fetchMock }));
import { getPreferredLivekitTransport, provisionLivekitToken } from './livekitProvisioning';
const openidToken: IOpenIDToken = {
access_token: 'openid-secret',
token_type: 'Bearer',
matrix_server_name: 'example.org',
expires_in: 3600,
};
const response = (status: number, body: unknown): Response =>
new Response(JSON.stringify(body), { status });
type TestClient = Pick<MatrixClient, 'getOpenIdToken' | '_unstable_getRTCTransports'>;
const client = (overrides: Partial<TestClient> = {}): TestClient => ({
getOpenIdToken: vi.fn<MatrixClient['getOpenIdToken']>().mockResolvedValue(openidToken),
_unstable_getRTCTransports: vi
.fn<MatrixClient['_unstable_getRTCTransports']>()
.mockResolvedValue([]),
...overrides,
});
describe('getPreferredLivekitTransport', () => {
it('prefers the SDK LiveKit transport over discovery', async () => {
const mx = client({
_unstable_getRTCTransports: vi
.fn<MatrixClient['_unstable_getRTCTransports']>()
.mockResolvedValue([{ type: 'livekit', livekit_service_url: 'https://sdk.example' }]),
});
await expect(
getPreferredLivekitTransport(mx, {
'org.matrix.msc4143.rtc_foci': [
{ type: 'livekit', livekit_service_url: 'https://discovery.example' },
],
})
).resolves.toEqual({ type: 'livekit', livekit_service_url: 'https://sdk.example' });
});
it('falls back to discovery when SDK transport discovery fails', async () => {
const mx = client({
_unstable_getRTCTransports: vi
.fn<MatrixClient['_unstable_getRTCTransports']>()
.mockRejectedValue(new Error('unsupported')),
});
await expect(
getPreferredLivekitTransport(mx, {
'org.matrix.msc4143.rtc_foci': [
{ type: 'livekit', livekit_service_url: 'https://discovery.example' },
],
})
).resolves.toEqual({ type: 'livekit', livekit_service_url: 'https://discovery.example' });
});
});
describe('provisionLivekitToken', () => {
beforeEach(() => {
fetchMock.mockReset();
});
const options = {
mx: client(),
roomId: '!room:example.org',
deviceId: 'DEVICE',
serviceUrl: 'https://sfu.example///',
memberId: 'member-id',
userId: '@alice:example.org',
};
it('provisions through the modern endpoint with the MatrixRTC request body', async () => {
fetchMock.mockResolvedValueOnce(
response(200, { url: 'wss://livekit.example', jwt: 'jwt-secret' })
);
await expect(provisionLivekitToken(options)).resolves.toEqual({
url: 'wss://livekit.example',
jwt: 'jwt-secret',
});
expect(fetchMock).toHaveBeenCalledOnce();
const [url, request] = fetchMock.mock.calls[0] as [string, RequestInit];
expect(url).toBe('https://sfu.example/get_token');
expect(JSON.parse(request.body as string)).toEqual({
room_id: '!room:example.org',
slot_id: 'm.call#!room:example.org',
openid_token: openidToken,
member: {
id: 'member-id',
claimed_user_id: '@alice:example.org',
claimed_device_id: 'DEVICE',
},
});
});
it('falls back to the legacy endpoint after a modern request failure', async () => {
fetchMock
.mockResolvedValueOnce(response(404, { error: 'not found' }))
.mockResolvedValueOnce(response(200, { url: 'wss://legacy.example', jwt: 'legacy-jwt' }));
await expect(provisionLivekitToken(options)).resolves.toEqual({
url: 'wss://legacy.example',
jwt: 'legacy-jwt',
});
expect(fetchMock).toHaveBeenCalledTimes(2);
const [url, request] = fetchMock.mock.calls[1] as [string, RequestInit];
expect(url).toBe('https://sfu.example/sfu/get');
expect(JSON.parse(request.body as string)).toEqual({
room: '!room:example.org',
openid_token: openidToken,
device_id: 'DEVICE',
});
});
it('rejects invalid responses after trying both endpoints', async () => {
fetchMock
.mockResolvedValueOnce(response(200, { url: 'wss://livekit.example' }))
.mockResolvedValueOnce(response(200, { jwt: 'jwt-secret' }));
await expect(provisionLivekitToken(options)).rejects.toThrow(
'LiveKit token provisioning failed'
);
expect(fetchMock).toHaveBeenCalledTimes(2);
});
it('does not expose token values in errors', async () => {
fetchMock.mockRejectedValue(new Error('request failed: jwt-secret openid-secret'));
const provisioning = provisionLivekitToken(options);
await expect(provisioning).rejects.toThrow('LiveKit token provisioning failed');
await expect(provisioning).rejects.not.toThrow('openid-secret');
await expect(provisioning).rejects.not.toThrow('jwt-secret');
});
});
@@ -0,0 +1,135 @@
import type { AutoDiscoveryInfo } from '../../cs-api';
import { getLivekitTransports } from '../../cs-api';
import { fetch as appFetch } from '$utils/fetch';
import { trimTrailingSlash } from '$utils/common';
import type {
IOpenIDToken,
LivekitTransportConfig,
MatrixClient,
Transport,
} from '$types/matrix-sdk';
export type LivekitProvisioningOptions = {
mx: Pick<MatrixClient, 'getOpenIdToken'>;
roomId: string;
deviceId: string;
serviceUrl: string;
memberId?: string;
userId?: string;
};
export type LivekitProvisioningResult = {
url: string;
jwt: string;
};
const isLivekitTransportConfig = (transport: Transport): transport is LivekitTransportConfig =>
transport.type === 'livekit' && typeof transport.livekit_service_url === 'string';
const isProvisioningResult = (value: unknown): value is LivekitProvisioningResult =>
typeof value === 'object' &&
value !== null &&
'url' in value &&
typeof value.url === 'string' &&
value.url.length > 0 &&
'jwt' in value &&
typeof value.jwt === 'string' &&
value.jwt.length > 0;
export const getPreferredLivekitTransport = async (
mx: Pick<MatrixClient, '_unstable_getRTCTransports'>,
discovery?: Pick<AutoDiscoveryInfo, 'org.matrix.msc4143.rtc_foci'>
): Promise<LivekitTransportConfig | undefined> => {
const transports = await mx['_unstable_getRTCTransports']().catch(() => undefined);
const livekitTransport = transports?.find(isLivekitTransportConfig);
if (livekitTransport) return livekitTransport;
return getLivekitTransports(discovery)[0];
};
type ModernProvisioningRequest = {
room_id: string;
slot_id: string;
openid_token: IOpenIDToken;
member?: {
id: string;
claimed_user_id: string;
claimed_device_id: string;
};
};
type LegacyProvisioningRequest = {
room: string;
openid_token: IOpenIDToken;
device_id: string;
};
const requestLivekitToken = async (
endpoint: string,
body: ModernProvisioningRequest | LegacyProvisioningRequest
): Promise<LivekitProvisioningResult> => {
const response = await appFetch(endpoint, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
});
if (response.status < 200 || response.status >= 300) {
throw new Error('LiveKit provisioning request failed');
}
const data = (await response.json()) as unknown;
if (!isProvisioningResult(data)) {
throw new Error('LiveKit provisioning response was invalid');
}
return { url: data.url, jwt: data.jwt };
};
export const provisionLivekitToken = async ({
mx,
roomId,
deviceId,
serviceUrl,
memberId,
userId,
}: LivekitProvisioningOptions): Promise<LivekitProvisioningResult> => {
let openidToken: IOpenIDToken;
try {
openidToken = await mx.getOpenIdToken();
} catch {
throw new Error('Unable to obtain an OpenID token for LiveKit provisioning');
}
const endpoint = trimTrailingSlash(serviceUrl);
const modernRequest: ModernProvisioningRequest = {
room_id: roomId,
slot_id: `m.call#${roomId}`,
openid_token: openidToken,
};
if (memberId && userId && deviceId) {
modernRequest.member = {
id: memberId,
claimed_user_id: userId,
claimed_device_id: deviceId,
};
}
try {
return await requestLivekitToken(`${endpoint}/get_token`, modernRequest);
} catch {
const legacyRequest: LegacyProvisioningRequest = {
room: roomId,
openid_token: openidToken,
device_id: deviceId,
};
try {
return await requestLivekitToken(`${endpoint}/sfu/get`, legacyRequest);
} catch {
throw new Error('LiveKit token provisioning failed');
}
}
};
+100
View File
@@ -0,0 +1,100 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
const pluginConnect = vi.hoisted(() => vi.fn<(request: unknown) => Promise<unknown>>());
const pluginDisconnect = vi.hoisted(() => vi.fn<(request: unknown) => Promise<unknown>>());
const pluginGetState = vi.hoisted(() => vi.fn<() => Promise<unknown>>());
const listen = vi.hoisted(() => vi.fn<(...args: unknown[]) => Promise<unknown>>());
vi.mock('tauri-plugin-call-lifecycle-api', () => ({
connect: pluginConnect,
disconnect: pluginDisconnect,
getState: pluginGetState,
}));
vi.mock('@tauri-apps/api/event', () => ({ listen }));
import {
connect,
disconnect,
getState,
onError,
onState,
type CallLifecycleError,
type CallState,
} from './callLifecycle';
describe('call lifecycle wrapper', () => {
beforeEach(() => {
pluginConnect.mockReset();
pluginDisconnect.mockReset();
pluginGetState.mockReset();
listen.mockReset();
listen.mockResolvedValue(vi.fn());
});
it('delegates lifecycle commands to the guest API', async () => {
const state = {
revision: 1,
state: 'connecting',
connectionId: 'connection-id',
} satisfies CallState;
pluginConnect.mockResolvedValue(state);
pluginDisconnect.mockResolvedValue(state);
pluginGetState.mockResolvedValue(state);
const request = {
connectionId: 'connection-id',
serverUrl: 'wss://livekit.example',
participantToken: 'token',
};
await expect(connect(request)).resolves.toEqual(state);
await expect(disconnect({ connectionId: 'connection-id' })).resolves.toEqual(state);
await expect(getState()).resolves.toEqual(state);
expect(pluginConnect).toHaveBeenCalledWith(request);
expect(pluginDisconnect).toHaveBeenCalledWith({
connectionId: 'connection-id',
});
expect(pluginGetState).toHaveBeenCalledWith();
});
it('registers typed state and error listeners', async () => {
const state = {
revision: 2,
state: 'connected',
connectionId: 'connection-id',
} satisfies CallState;
const error = {
revision: 3,
code: 'connect_failed',
message: 'call connection failed',
connectionId: 'connection-id',
} satisfies CallLifecycleError;
const onStateEvent = vi.fn<(value: CallState) => void>();
const onErrorEvent = vi.fn<(value: CallLifecycleError) => void>();
const stateUnlisten = await onState(onStateEvent);
const stateListener = listen.mock.calls[0]?.[1] as (event: { payload: CallState }) => void;
stateListener({ payload: state });
const errorUnlisten = await onError(onErrorEvent);
const errorListener = listen.mock.calls[1]?.[1] as (event: {
payload: CallLifecycleError;
}) => void;
errorListener({ payload: error });
expect(listen).toHaveBeenNthCalledWith(
1,
'plugin:call-lifecycle://state',
expect.any(Function)
);
expect(listen).toHaveBeenNthCalledWith(
2,
'plugin:call-lifecycle://error',
expect.any(Function)
);
expect(onStateEvent).toHaveBeenCalledWith(state);
expect(onErrorEvent).toHaveBeenCalledWith(error);
expect(stateUnlisten).toBeTypeOf('function');
expect(errorUnlisten).toBeTypeOf('function');
});
});
+28
View File
@@ -0,0 +1,28 @@
import {
connect as pluginConnect,
disconnect as pluginDisconnect,
getState as pluginGetState,
type CallLifecycleError,
type CallState,
type ConnectRequest,
type ConnectionState,
type DisconnectRequest,
} from 'tauri-plugin-call-lifecycle-api';
import { listen, type UnlistenFn } from '@tauri-apps/api/event';
const STATE_EVENT = 'plugin:call-lifecycle://state';
const ERROR_EVENT = 'plugin:call-lifecycle://error';
export type { CallLifecycleError, CallState, ConnectRequest, ConnectionState, DisconnectRequest };
export const connect = pluginConnect;
export const disconnect = pluginDisconnect;
export const getState = pluginGetState;
export function onState(handler: (state: CallState) => void): Promise<UnlistenFn> {
return listen<CallState>(STATE_EVENT, (event) => handler(event.payload));
}
export function onError(handler: (error: CallLifecycleError) => void): Promise<UnlistenFn> {
return listen<CallLifecycleError>(ERROR_EVENT, (event) => handler(event.payload));
}
+1
View File
@@ -1,3 +1,4 @@
export * from './CallEmbed';
export * from './callLifecycle';
export * from './hooks';
export * from './types';
+6
View File
@@ -55,5 +55,11 @@ export * from 'matrix-js-sdk/lib/common-crypto/CryptoBackend';
export * from 'matrix-js-sdk/lib/matrixrtc/CallMembership';
export * from 'matrix-js-sdk/lib/matrixrtc/MatrixRTCSession';
export * from 'matrix-js-sdk/lib/matrixrtc/MatrixRTCSessionManager';
export { type CallMembershipIdentityParts } from 'matrix-js-sdk/lib/matrixrtc/EncryptionManager';
export {
type LivekitTransport,
type LivekitTransportConfig,
} from 'matrix-js-sdk/lib/matrixrtc/LivekitTransport';
export { type Transport } from 'matrix-js-sdk/lib/matrixrtc/types';
export * from 'matrix-js-sdk/lib/models/thread';