Websocket Support (#159)

This commit is contained in:
Gregory Schier
2025-01-31 09:00:11 -08:00
committed by GitHub
parent d411713502
commit c8be8082c5
122 changed files with 5090 additions and 616 deletions

257
src-tauri/Cargo.lock generated
View File

@@ -43,7 +43,7 @@ dependencies = [
"cfg-if",
"once_cell",
"version_check 0.9.5",
"zerocopy",
"zerocopy 0.7.35",
]
[[package]]
@@ -1236,7 +1236,16 @@ version = "5.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "44c45a9d03d6676652bcb5e724c7e988de1acad23a711b5217ab9cbecbec2225"
dependencies = [
"dirs-sys",
"dirs-sys 0.4.1",
]
[[package]]
name = "dirs"
version = "6.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c3e8aa94d75141228480295a7d0e7feb620b1a5ad9f12bc40be62411e38cce4e"
dependencies = [
"dirs-sys 0.5.0",
]
[[package]]
@@ -1247,10 +1256,22 @@ checksum = "520f05a5cbd335fae5a99ff7a6ab8627577660ee5cfd6a94a6a929b52ff0321c"
dependencies = [
"libc",
"option-ext",
"redox_users",
"redox_users 0.4.5",
"windows-sys 0.48.0",
]
[[package]]
name = "dirs-sys"
version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e01a3366d27ee9890022452ee61b2b63a67e6f13f58900b651ff5665f0bb1fab"
dependencies = [
"libc",
"option-ext",
"redox_users 0.5.0",
"windows-sys 0.59.0",
]
[[package]]
name = "dispatch"
version = "0.2.0"
@@ -1670,9 +1691,9 @@ dependencies = [
[[package]]
name = "futures-core"
version = "0.3.30"
version = "0.3.31"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dfc6580bb841c5a68e9ef15c77ccc837b40a7504914d52e47b8b0e9bbda25a1d"
checksum = "05f29059c0c2090612e8d742178b0580d2dc940c837851ad723096f87af6663e"
[[package]]
name = "futures-executor"
@@ -1698,9 +1719,9 @@ dependencies = [
[[package]]
name = "futures-io"
version = "0.3.30"
version = "0.3.31"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a44623e20b9681a318efdd71c299b6b222ed6f231972bfe2f224ebad6311f0c1"
checksum = "9e5c1b78ca4aae1ac06c48a526a655760685149f0d465d21f37abfe57ce075c6"
[[package]]
name = "futures-lite"
@@ -1717,9 +1738,9 @@ dependencies = [
[[package]]
name = "futures-macro"
version = "0.3.30"
version = "0.3.31"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "87750cf4b7a4c0625b1529e4c543c2182106e4dedc60a2a6455e00d212c489ac"
checksum = "162ee34ebcb7c64a8abebc059ce0fee27c2262618d7b60ed8faf72fef13c3650"
dependencies = [
"proc-macro2",
"quote",
@@ -1728,21 +1749,21 @@ dependencies = [
[[package]]
name = "futures-sink"
version = "0.3.30"
version = "0.3.31"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9fb8e00e87438d937621c1c6269e53f536c14d3fbd6a042bb24879e57d474fb5"
checksum = "e575fab7d1e0dcb8d0c7bcf9a63ee213816ab51902e6d244a95819acacf1d4f7"
[[package]]
name = "futures-task"
version = "0.3.30"
version = "0.3.31"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "38d84fa142264698cdce1a9f9172cf383a0c82de1bddcf3092901442c4097004"
checksum = "f90f7dce0722e95104fcb095585910c0977252f286e354b5e3bd38902cd99988"
[[package]]
name = "futures-util"
version = "0.3.30"
version = "0.3.31"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3d6401deb83407ab3da39eba7e33987a73c3df0c82b4bb5813ee871c19c41d48"
checksum = "9fa08315bb612088cc391249efdc3bc77536f16c91f6cf495e6fbe85b20a4a81"
dependencies = [
"futures-core",
"futures-io",
@@ -1915,6 +1936,18 @@ dependencies = [
"wasi 0.11.0+wasi-snapshot-preview1",
]
[[package]]
name = "getrandom"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "43a49c392881ce6d5c3b8cb70f98717b7c07aabbdff06687b9030dbfbe2725f8"
dependencies = [
"cfg-if",
"libc",
"wasi 0.13.3+wasi-0.2.2",
"windows-targets 0.52.6",
]
[[package]]
name = "gimli"
version = "0.29.0"
@@ -2281,7 +2314,6 @@ dependencies = [
"hyper-util",
"rustls",
"rustls-pki-types",
"rustls-platform-verifier",
"tokio",
"tokio-rustls",
"tower-service",
@@ -2695,9 +2727,9 @@ dependencies = [
[[package]]
name = "libc"
version = "0.2.155"
version = "0.2.169"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "97b3888a4aecf77e811145cadf6eef5901f4782c53886191b2f693f24761847c"
checksum = "b5aba8db14291edd000dfcc4d620c7ebfb122c613afb886ca8803fa4e128a20a"
[[package]]
name = "libloading"
@@ -3864,7 +3896,7 @@ version = "0.2.20"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "77957b295656769bb8ad2b6a6b09d897d94f05c41b069aede1fcdaa675eaea04"
dependencies = [
"zerocopy",
"zerocopy 0.7.35",
]
[[package]]
@@ -4162,6 +4194,17 @@ dependencies = [
"rand_core 0.6.4",
]
[[package]]
name = "rand"
version = "0.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3779b94aeb87e8bd4e834cee3650289ee9e0d5677f976ecdb6d219e5f4f6cd94"
dependencies = [
"rand_chacha 0.9.0",
"rand_core 0.9.0",
"zerocopy 0.8.14",
]
[[package]]
name = "rand_chacha"
version = "0.2.2"
@@ -4182,6 +4225,16 @@ dependencies = [
"rand_core 0.6.4",
]
[[package]]
name = "rand_chacha"
version = "0.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb"
dependencies = [
"ppv-lite86",
"rand_core 0.9.0",
]
[[package]]
name = "rand_core"
version = "0.5.1"
@@ -4200,6 +4253,16 @@ dependencies = [
"getrandom 0.2.15",
]
[[package]]
name = "rand_core"
version = "0.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b08f3c9802962f7e1b25113931d94f43ed9725bebc59db9d0c3e9a23b67e15ff"
dependencies = [
"getrandom 0.3.1",
"zerocopy 0.8.14",
]
[[package]]
name = "rand_hc"
version = "0.2.0"
@@ -4259,6 +4322,17 @@ dependencies = [
"thiserror 1.0.63",
]
[[package]]
name = "redox_users"
version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dd6f9d3d47bdd2ad6945c5015a226ec6155d0bcdfd8f7cd29f86b71f8de99d2b"
dependencies = [
"getrandom 0.2.15",
"libredox",
"thiserror 2.0.11",
]
[[package]]
name = "regex"
version = "1.11.0"
@@ -4518,9 +4592,9 @@ dependencies = [
[[package]]
name = "rustls"
version = "0.23.21"
version = "0.23.22"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8f287924602bf649d949c63dc8ac8b235fa5387d394020705b80c4eb597ce5b8"
checksum = "9fb9263ab4eb695e42321db096e3b8fbd715a59b154d5c88d82db2175b681ba7"
dependencies = [
"once_cell",
"ring",
@@ -4783,9 +4857,9 @@ dependencies = [
[[package]]
name = "serde"
version = "1.0.215"
version = "1.0.217"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6513c1ad0b11a9376da888e3e0baa0077f1aed55c17f50e7b2397136129fb88f"
checksum = "02fc4265df13d6fa1d00ecff087228cc0a2b5f3c0e87e258d8b94a156e984c70"
dependencies = [
"serde_derive",
]
@@ -4813,9 +4887,9 @@ dependencies = [
[[package]]
name = "serde_derive"
version = "1.0.215"
version = "1.0.217"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ad1e866f866923f252f05c889987993144fb74e722403468a4ebd70c3cd756c0"
checksum = "5a9bf7cf98d04a2b28aead066b7496853d4779c9cc183c440dbac457641e19a0"
dependencies = [
"proc-macro2",
"quote",
@@ -5553,13 +5627,13 @@ checksum = "61c41af27dd6d1e27b1b16b489db798443478cef1f06a660c96db617ba5de3b1"
[[package]]
name = "tauri"
version = "2.2.3"
version = "2.2.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "78f6efc261c7905839b4914889a5b25df07f0ff89c63fb4afd6ff8c96af15e4d"
checksum = "58a998b6be84104ca05c7e9a21f2180ddec020c8b84ea59a8fc8530a2a19588d"
dependencies = [
"anyhow",
"bytes",
"dirs",
"dirs 6.0.0",
"dunce",
"embed_plist",
"futures-util",
@@ -5610,7 +5684,7 @@ checksum = "8e950124f6779c6cf98e3260c7a6c8488a74aa6350dd54c6950fdaa349bca2df"
dependencies = [
"anyhow",
"cargo_toml",
"dirs",
"dirs 5.0.1",
"glob",
"heck 0.5.0",
"json-patch",
@@ -5667,9 +5741,9 @@ dependencies = [
[[package]]
name = "tauri-plugin"
version = "2.0.3"
version = "2.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e753f2a30933a9bbf0a202fa47d7cc4a3401f06e8d6dcc53b79aa62954828c79"
checksum = "5841b9a0200e954ef7457f8d327091424328891e267a97b641dc246cc54d0dec"
dependencies = [
"anyhow",
"glob",
@@ -5684,9 +5758,9 @@ dependencies = [
[[package]]
name = "tauri-plugin-clipboard-manager"
version = "2.2.0"
version = "2.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5be2c6f5d82396c1a86d5b16052cc97976a82e92244bf074dd6e2f6272d8619d"
checksum = "54de1e3a2ea008687954d5d72952800e87b09f6fbea6d0960d99e58050537642"
dependencies = [
"arboard",
"log",
@@ -5740,16 +5814,16 @@ dependencies = [
[[package]]
name = "tauri-plugin-log"
version = "2.2.0"
version = "2.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "eddd784c138c08a43954bc3e735402e6b2b2ee8d8c254a7391f4e77c01273dd5"
checksum = "367a28a5e0ca39eac98005699466e8906edc4a2a8f8e13a5f1a71dc0bea6c677"
dependencies = [
"android_logger",
"byte-unit",
"cocoa 0.26.0",
"fern",
"log",
"objc",
"objc2",
"objc2-foundation",
"serde",
"serde_json",
"serde_repr",
@@ -5762,9 +5836,9 @@ dependencies = [
[[package]]
name = "tauri-plugin-opener"
version = "2.2.4"
version = "2.2.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1270bd2f3aabffc2becc05b6aafab3d24fe5679db91bec369fb44865afd7de13"
checksum = "635ed7c580dc3cdc61c94097d38ef517d749ffc0141c806d904e68e4b0cf1c2a"
dependencies = [
"dunce",
"glob",
@@ -5838,12 +5912,12 @@ dependencies = [
[[package]]
name = "tauri-plugin-updater"
version = "2.3.1"
version = "2.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ce2d39224390c41ba544f02b4f1721f42256320b3fb8c371e9425cbddeb4a68c"
checksum = "ad3de2b9203bb00b9765e637a9878aaace34df40ae484878b8cea7a5bd5f9188"
dependencies = [
"base64 0.22.1",
"dirs",
"dirs 5.0.1",
"flate2",
"futures-util",
"http",
@@ -5868,9 +5942,9 @@ dependencies = [
[[package]]
name = "tauri-plugin-window-state"
version = "2.2.0"
version = "2.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "234dd891cc7960fa28f93ea911f3e0d9ce8375ebf9ff303831bdd7a3443d5714"
checksum = "35e344b512b0d99d9d06225f235d87d6c66d89496a3bf323d9b578d940596e6c"
dependencies = [
"bitflags 2.6.0",
"log",
@@ -6113,9 +6187,9 @@ checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20"
[[package]]
name = "tokio"
version = "1.42.0"
version = "1.43.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5cec9b21b0450273377fc97bd4c33a8acffc8c996c987a7c5b319a0083707551"
checksum = "3d61fa4ffa3de412bfea335c6ecff681de2b609ba3c77ef3e00e521813a9ed9e"
dependencies = [
"backtrace",
"bytes",
@@ -6131,9 +6205,9 @@ dependencies = [
[[package]]
name = "tokio-macros"
version = "2.4.0"
version = "2.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "693d596312e88961bc67d7f1f97af8a70227d9f90c31bba5806eec004978d752"
checksum = "6e06d43f1345a3bcd39f6a56dbb7dcab2ba47e68e8ac134855e7e2bdbaf8cab8"
dependencies = [
"proc-macro2",
"quote",
@@ -6163,9 +6237,9 @@ dependencies = [
[[package]]
name = "tokio-stream"
version = "0.1.16"
version = "0.1.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4f4e6ce100d0eb49a2734f8c0812bcd324cf357d21810932c5df6b96ef2b86f1"
checksum = "eca58d7bba4a75707817a2c44174253f9236b2d5fbd055602e9d5c07c139a047"
dependencies = [
"futures-core",
"pin-project-lite",
@@ -6180,7 +6254,11 @@ checksum = "be4bf6fecd69fcdede0ec680aaf474cdab988f9de6bc73d3758f0160e3b7025a"
dependencies = [
"futures-util",
"log",
"rustls",
"rustls-native-certs",
"rustls-pki-types",
"tokio",
"tokio-rustls",
"tungstenite",
]
@@ -6397,7 +6475,7 @@ checksum = "533fc2d4105e0e3d96ce1c71f2d308c9fbbe2ef9c587cab63dd627ab5bde218f"
dependencies = [
"core-graphics 0.24.0",
"crossbeam-channel",
"dirs",
"dirs 5.0.1",
"libappindicator",
"muda",
"objc2",
@@ -6454,6 +6532,8 @@ dependencies = [
"httparse",
"log",
"rand 0.8.5",
"rustls",
"rustls-pki-types",
"sha1",
"thiserror 2.0.11",
"utf-8",
@@ -6633,9 +6713,9 @@ checksum = "86bd8d4e895da8537e5315b8254664e6b769c4ff3db18321b297a1e7004392e3"
[[package]]
name = "uuid"
version = "1.10.0"
version = "1.12.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "81dfa00651efa65069b0b6b651f4aaa31ba9e3c3ce0137aaad053604ee7e0314"
checksum = "b3758f5e68192bb96cc8f9b7e2c2cfdabb435499a28499a42f8f984092adad4b"
dependencies = [
"getrandom 0.2.15",
"rand 0.8.5",
@@ -6723,6 +6803,15 @@ version = "0.11.0+wasi-snapshot-preview1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423"
[[package]]
name = "wasi"
version = "0.13.3+wasi-0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "26816d2e1a4a36a2940b96c5296ce403917633dff8f3440e9b236ed6f6bacad2"
dependencies = [
"wit-bindgen-rt",
]
[[package]]
name = "wasite"
version = "0.1.0"
@@ -7371,6 +7460,15 @@ dependencies = [
"windows-sys 0.48.0",
]
[[package]]
name = "wit-bindgen-rt"
version = "0.33.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3268f3d866458b787f390cf61f4bbb563b922d091359f9608842999eaee3943c"
dependencies = [
"bitflags 2.6.0",
]
[[package]]
name = "wry"
version = "0.48.0"
@@ -7498,7 +7596,7 @@ dependencies = [
"mime_guess",
"objc",
"openssl-sys",
"rand 0.8.5",
"rand 0.9.0",
"regex",
"reqwest",
"reqwest_cookie_store",
@@ -7530,6 +7628,7 @@ dependencies = [
"yaak-sse",
"yaak-sync",
"yaak-templates",
"yaak-ws",
]
[[package]]
@@ -7547,6 +7646,8 @@ dependencies = [
"prost",
"prost-reflect",
"prost-types",
"rustls",
"rustls-platform-verifier",
"serde",
"serde_json",
"tauri",
@@ -7603,7 +7704,7 @@ dependencies = [
"log",
"md5",
"path-slash",
"rand 0.8.5",
"rand 0.9.0",
"regex",
"serde",
"serde_json",
@@ -7614,6 +7715,7 @@ dependencies = [
"tokio-tungstenite",
"ts-rs",
"yaak-models",
"yaak-templates",
]
[[package]]
@@ -7650,10 +7752,33 @@ version = "0.1.0"
dependencies = [
"log",
"serde",
"serde_json",
"tokio",
"ts-rs",
]
[[package]]
name = "yaak-ws"
version = "0.1.0"
dependencies = [
"chrono",
"futures-util",
"log",
"md5",
"rustls",
"rustls-platform-verifier",
"serde",
"serde_json",
"tauri",
"tauri-plugin",
"thiserror 2.0.11",
"tokio",
"tokio-tungstenite",
"yaak-models",
"yaak-plugins",
"yaak-templates",
]
[[package]]
name = "zbus"
version = "4.0.1"
@@ -7783,7 +7908,16 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1b9b4fd18abc82b8136838da5d50bae7bdea537c574d8dc1a34ed098d6c166f0"
dependencies = [
"byteorder",
"zerocopy-derive",
"zerocopy-derive 0.7.35",
]
[[package]]
name = "zerocopy"
version = "0.8.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a367f292d93d4eab890745e75a778da40909cab4d6ff8173693812f79c4a2468"
dependencies = [
"zerocopy-derive 0.8.14",
]
[[package]]
@@ -7797,6 +7931,17 @@ dependencies = [
"syn 2.0.87",
]
[[package]]
name = "zerocopy-derive"
version = "0.8.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d3931cb58c62c13adec22e38686b559c86a30565e16ad6e8510a337cedc611e1"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.87",
]
[[package]]
name = "zeroize"
version = "1.8.1"

View File

@@ -7,6 +7,7 @@ members = [
"yaak-sse",
"yaak-sync",
"yaak-templates",
"yaak-ws",
]
[package]
@@ -40,53 +41,56 @@ openssl-sys = { version = "0.9", features = ["vendored"] } # For Ubuntu installa
[dependencies]
chrono = { version = "0.4.31", features = ["serde"] }
datetime = "0.5.2"
encoding_rs = "0.8.35"
eventsource-client = { git = "https://github.com/yaakapp/rust-eventsource-client", version = "0.14.0" }
hex_color = "3.0.0"
http = { version = "1.2.0", default-features = false }
log = "0.4.21"
md5 = "0.7.0"
rand = "0.8.5"
mime_guess = "2.0.5"
rand = "0.9.0"
regex = "1.10.2"
reqwest = { workspace = true, features = ["multipart", "cookies", "gzip", "brotli", "deflate", "json", "rustls-tls-manual-roots-no-provider"] }
reqwest_cookie_store = "0.8.0"
rustls = { version = "0.23.21", default-features = false }
rustls = { version = "0.23.22", default-features = false, features = ["custom-provider", "ring"] }
rustls-platform-verifier = "0.5.0"
serde = { workspace = true, features = ["derive"] }
serde_json = { workspace = true, features = ["raw_value"] }
tauri = { workspace = true, features = ["devtools", "protocol-asset"] }
tauri-plugin-clipboard-manager = "2.2.0"
tauri-plugin-clipboard-manager = "2.2.1"
tauri-plugin-dialog = "2.2.0"
tauri-plugin-fs = "2.2.0"
tauri-plugin-log = { version = "2.2.0", features = ["colored"] }
tauri-plugin-opener = "2.2.4"
tauri-plugin-log = { version = "2.2.1", features = ["colored"] }
tauri-plugin-opener = "2.2.5"
tauri-plugin-os = "2.2.0"
tauri-plugin-shell = { workspace = true }
tauri-plugin-single-instance = "2.2.1"
tauri-plugin-updater = "2.3.1"
tauri-plugin-window-state = "2.2.0"
tokio = { version = "1.36.0", features = ["sync"] }
tokio-stream = "0.1.15"
tauri-plugin-updater = "2.4.0"
tauri-plugin-window-state = "2.2.1"
tokio = { version = "1.43.0", features = ["sync"] }
tokio-stream = "0.1.17"
ts-rs = { workspace = true }
mime_guess = "2.0.5"
urlencoding = "2.1.3"
uuid = "1.7.0"
uuid = "1.12.1"
yaak-grpc = { path = "yaak-grpc" }
yaak-license = { path = "yaak-license" }
yaak-models = { workspace = true }
yaak-plugins = { workspace = true }
yaak-sse = { workspace = true }
yaak-sync = { path = "yaak-sync" }
yaak-templates = { path = "yaak-templates" }
encoding_rs = "0.8.35"
yaak-templates = { workspace = true }
yaak-ws = { path = "yaak-ws" }
[workspace.dependencies]
yaak-models = { path = "yaak-models" }
yaak-sse = { path = "yaak-sse" }
yaak-plugins = { path = "yaak-plugins" }
reqwest = "0.12.12"
serde = "1.0.215"
serde_json = "1.0.132"
tauri = "2.2.5"
tauri-plugin = "2.0.4"
tauri-plugin-shell = "2.2.0"
tauri = "2.2.3"
thiserror = "2.0.3"
ts-rs = "10.0.0"
reqwest = "0.12.12"
yaak-models = { path = "yaak-models" }
yaak-plugins = { path = "yaak-plugins" }
yaak-sse = { path = "yaak-sse" }
yaak-templates = { path = "yaak-templates" }

View File

@@ -2,4 +2,4 @@
export type AnalyticsAction = "cancel" | "click" | "commit" | "create" | "delete" | "delete_many" | "duplicate" | "error" | "export" | "hide" | "import" | "launch" | "launch_first" | "launch_update" | "send" | "show" | "toggle" | "update" | "upsert";
export type AnalyticsResource = "app" | "appearance" | "button" | "checkbox" | "cookie_jar" | "dialog" | "environment" | "folder" | "grpc_connection" | "grpc_event" | "grpc_request" | "http_request" | "http_response" | "key_value" | "link" | "mutation" | "plugin" | "select" | "setting" | "sidebar" | "tab" | "theme" | "workspace";
export type AnalyticsResource = "app" | "appearance" | "button" | "checkbox" | "cookie_jar" | "dialog" | "environment" | "folder" | "grpc_connection" | "grpc_event" | "grpc_request" | "http_request" | "http_response" | "key_value" | "link" | "mutation" | "plugin" | "select" | "setting" | "sidebar" | "tab" | "theme" | "websocket_connection" | "websocket_event" | "websocket_request" | "workspace";

View File

@@ -51,6 +51,7 @@
"opener:allow-reveal-item-in-dir",
"shell:allow-open",
"yaak-license:default",
"yaak-sync:default"
"yaak-sync:default",
"yaak-ws:default"
]
}

File diff suppressed because one or more lines are too long

View File

@@ -1 +1 @@
{"main":{"identifier":"main","description":"Main permissions","local":true,"windows":["*"],"permissions":["core:event:allow-emit","core:event:allow-listen","core:event:allow-unlisten","os:allow-os-type","clipboard-manager:allow-clear","clipboard-manager:allow-write-text","clipboard-manager:allow-read-text","dialog:allow-open","dialog:allow-save","fs:allow-read-dir","fs:allow-read-file","fs:allow-read-text-file",{"identifier":"fs:scope","allow":[{"path":"$APPDATA"},{"path":"$APPDATA/**"}]},"clipboard-manager:allow-read-text","clipboard-manager:allow-write-text","core:webview:allow-set-webview-zoom","core:window:allow-close","core:window:allow-internal-toggle-maximize","core:window:allow-is-fullscreen","core:window:allow-is-maximized","core:window:allow-maximize","core:window:allow-minimize","core:window:allow-set-decorations","core:window:allow-set-title","core:window:allow-show","core:window:allow-start-dragging","core:window:allow-theme","core:window:allow-unmaximize","opener:allow-default-urls","opener:allow-open-path","opener:allow-open-url","opener:allow-reveal-item-in-dir","shell:allow-open","yaak-license:default","yaak-sync:default"]}}
{"main":{"identifier":"main","description":"Main permissions","local":true,"windows":["*"],"permissions":["core:event:allow-emit","core:event:allow-listen","core:event:allow-unlisten","os:allow-os-type","clipboard-manager:allow-clear","clipboard-manager:allow-write-text","clipboard-manager:allow-read-text","dialog:allow-open","dialog:allow-save","fs:allow-read-dir","fs:allow-read-file","fs:allow-read-text-file",{"identifier":"fs:scope","allow":[{"path":"$APPDATA"},{"path":"$APPDATA/**"}]},"clipboard-manager:allow-read-text","clipboard-manager:allow-write-text","core:webview:allow-set-webview-zoom","core:window:allow-close","core:window:allow-internal-toggle-maximize","core:window:allow-is-fullscreen","core:window:allow-is-maximized","core:window:allow-maximize","core:window:allow-minimize","core:window:allow-set-decorations","core:window:allow-set-title","core:window:allow-show","core:window:allow-start-dragging","core:window:allow-theme","core:window:allow-unmaximize","opener:allow-default-urls","opener:allow-open-path","opener:allow-open-url","opener:allow-reveal-item-in-dir","shell:allow-open","yaak-license:default","yaak-sync:default","yaak-ws:default"]}}

View File

@@ -5481,6 +5481,151 @@
"description": "Denies the watch command without any pre-configured scope.",
"type": "string",
"const": "yaak-sync:deny-watch"
},
{
"description": "Default permissions for the plugin",
"type": "string",
"const": "yaak-ws:default"
},
{
"description": "Enables the cancel command without any pre-configured scope.",
"type": "string",
"const": "yaak-ws:allow-cancel"
},
{
"description": "Enables the close command without any pre-configured scope.",
"type": "string",
"const": "yaak-ws:allow-close"
},
{
"description": "Enables the connect command without any pre-configured scope.",
"type": "string",
"const": "yaak-ws:allow-connect"
},
{
"description": "Enables the delete_connection command without any pre-configured scope.",
"type": "string",
"const": "yaak-ws:allow-delete-connection"
},
{
"description": "Enables the delete_connections command without any pre-configured scope.",
"type": "string",
"const": "yaak-ws:allow-delete-connections"
},
{
"description": "Enables the delete_request command without any pre-configured scope.",
"type": "string",
"const": "yaak-ws:allow-delete-request"
},
{
"description": "Enables the list_connections command without any pre-configured scope.",
"type": "string",
"const": "yaak-ws:allow-list-connections"
},
{
"description": "Enables the list_events command without any pre-configured scope.",
"type": "string",
"const": "yaak-ws:allow-list-events"
},
{
"description": "Enables the list_requests command without any pre-configured scope.",
"type": "string",
"const": "yaak-ws:allow-list-requests"
},
{
"description": "Enables the list_websocket_connections command without any pre-configured scope.",
"type": "string",
"const": "yaak-ws:allow-list-websocket-connections"
},
{
"description": "Enables the list_websocket_requests command without any pre-configured scope.",
"type": "string",
"const": "yaak-ws:allow-list-websocket-requests"
},
{
"description": "Enables the send command without any pre-configured scope.",
"type": "string",
"const": "yaak-ws:allow-send"
},
{
"description": "Enables the upsert_request command without any pre-configured scope.",
"type": "string",
"const": "yaak-ws:allow-upsert-request"
},
{
"description": "Enables the upsert_websocket_request command without any pre-configured scope.",
"type": "string",
"const": "yaak-ws:allow-upsert-websocket-request"
},
{
"description": "Denies the cancel command without any pre-configured scope.",
"type": "string",
"const": "yaak-ws:deny-cancel"
},
{
"description": "Denies the close command without any pre-configured scope.",
"type": "string",
"const": "yaak-ws:deny-close"
},
{
"description": "Denies the connect command without any pre-configured scope.",
"type": "string",
"const": "yaak-ws:deny-connect"
},
{
"description": "Denies the delete_connection command without any pre-configured scope.",
"type": "string",
"const": "yaak-ws:deny-delete-connection"
},
{
"description": "Denies the delete_connections command without any pre-configured scope.",
"type": "string",
"const": "yaak-ws:deny-delete-connections"
},
{
"description": "Denies the delete_request command without any pre-configured scope.",
"type": "string",
"const": "yaak-ws:deny-delete-request"
},
{
"description": "Denies the list_connections command without any pre-configured scope.",
"type": "string",
"const": "yaak-ws:deny-list-connections"
},
{
"description": "Denies the list_events command without any pre-configured scope.",
"type": "string",
"const": "yaak-ws:deny-list-events"
},
{
"description": "Denies the list_requests command without any pre-configured scope.",
"type": "string",
"const": "yaak-ws:deny-list-requests"
},
{
"description": "Denies the list_websocket_connections command without any pre-configured scope.",
"type": "string",
"const": "yaak-ws:deny-list-websocket-connections"
},
{
"description": "Denies the list_websocket_requests command without any pre-configured scope.",
"type": "string",
"const": "yaak-ws:deny-list-websocket-requests"
},
{
"description": "Denies the send command without any pre-configured scope.",
"type": "string",
"const": "yaak-ws:deny-send"
},
{
"description": "Denies the upsert_request command without any pre-configured scope.",
"type": "string",
"const": "yaak-ws:deny-upsert-request"
},
{
"description": "Denies the upsert_websocket_request command without any pre-configured scope.",
"type": "string",
"const": "yaak-ws:deny-upsert-websocket-request"
}
]
},

View File

@@ -5481,6 +5481,151 @@
"description": "Denies the watch command without any pre-configured scope.",
"type": "string",
"const": "yaak-sync:deny-watch"
},
{
"description": "Default permissions for the plugin",
"type": "string",
"const": "yaak-ws:default"
},
{
"description": "Enables the cancel command without any pre-configured scope.",
"type": "string",
"const": "yaak-ws:allow-cancel"
},
{
"description": "Enables the close command without any pre-configured scope.",
"type": "string",
"const": "yaak-ws:allow-close"
},
{
"description": "Enables the connect command without any pre-configured scope.",
"type": "string",
"const": "yaak-ws:allow-connect"
},
{
"description": "Enables the delete_connection command without any pre-configured scope.",
"type": "string",
"const": "yaak-ws:allow-delete-connection"
},
{
"description": "Enables the delete_connections command without any pre-configured scope.",
"type": "string",
"const": "yaak-ws:allow-delete-connections"
},
{
"description": "Enables the delete_request command without any pre-configured scope.",
"type": "string",
"const": "yaak-ws:allow-delete-request"
},
{
"description": "Enables the list_connections command without any pre-configured scope.",
"type": "string",
"const": "yaak-ws:allow-list-connections"
},
{
"description": "Enables the list_events command without any pre-configured scope.",
"type": "string",
"const": "yaak-ws:allow-list-events"
},
{
"description": "Enables the list_requests command without any pre-configured scope.",
"type": "string",
"const": "yaak-ws:allow-list-requests"
},
{
"description": "Enables the list_websocket_connections command without any pre-configured scope.",
"type": "string",
"const": "yaak-ws:allow-list-websocket-connections"
},
{
"description": "Enables the list_websocket_requests command without any pre-configured scope.",
"type": "string",
"const": "yaak-ws:allow-list-websocket-requests"
},
{
"description": "Enables the send command without any pre-configured scope.",
"type": "string",
"const": "yaak-ws:allow-send"
},
{
"description": "Enables the upsert_request command without any pre-configured scope.",
"type": "string",
"const": "yaak-ws:allow-upsert-request"
},
{
"description": "Enables the upsert_websocket_request command without any pre-configured scope.",
"type": "string",
"const": "yaak-ws:allow-upsert-websocket-request"
},
{
"description": "Denies the cancel command without any pre-configured scope.",
"type": "string",
"const": "yaak-ws:deny-cancel"
},
{
"description": "Denies the close command without any pre-configured scope.",
"type": "string",
"const": "yaak-ws:deny-close"
},
{
"description": "Denies the connect command without any pre-configured scope.",
"type": "string",
"const": "yaak-ws:deny-connect"
},
{
"description": "Denies the delete_connection command without any pre-configured scope.",
"type": "string",
"const": "yaak-ws:deny-delete-connection"
},
{
"description": "Denies the delete_connections command without any pre-configured scope.",
"type": "string",
"const": "yaak-ws:deny-delete-connections"
},
{
"description": "Denies the delete_request command without any pre-configured scope.",
"type": "string",
"const": "yaak-ws:deny-delete-request"
},
{
"description": "Denies the list_connections command without any pre-configured scope.",
"type": "string",
"const": "yaak-ws:deny-list-connections"
},
{
"description": "Denies the list_events command without any pre-configured scope.",
"type": "string",
"const": "yaak-ws:deny-list-events"
},
{
"description": "Denies the list_requests command without any pre-configured scope.",
"type": "string",
"const": "yaak-ws:deny-list-requests"
},
{
"description": "Denies the list_websocket_connections command without any pre-configured scope.",
"type": "string",
"const": "yaak-ws:deny-list-websocket-connections"
},
{
"description": "Denies the list_websocket_requests command without any pre-configured scope.",
"type": "string",
"const": "yaak-ws:deny-list-websocket-requests"
},
{
"description": "Denies the send command without any pre-configured scope.",
"type": "string",
"const": "yaak-ws:deny-send"
},
{
"description": "Denies the upsert_request command without any pre-configured scope.",
"type": "string",
"const": "yaak-ws:deny-upsert-request"
},
{
"description": "Denies the upsert_websocket_request command without any pre-configured scope.",
"type": "string",
"const": "yaak-ws:deny-upsert-websocket-request"
}
]
},

View File

@@ -0,0 +1,66 @@
CREATE TABLE websocket_requests
(
id TEXT NOT NULL
PRIMARY KEY,
model TEXT DEFAULT 'websocket_request' NOT NULL,
workspace_id TEXT NOT NULL
REFERENCES workspaces
ON DELETE CASCADE,
folder_id TEXT
REFERENCES folders
ON DELETE CASCADE,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL,
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL,
deleted_at DATETIME,
authentication TEXT DEFAULT '{}' NOT NULL,
authentication_type TEXT,
description TEXT NOT NULL,
name TEXT NOT NULL,
url TEXT NOT NULL,
headers TEXT NOT NULL,
message TEXT NOT NULL,
sort_priority REAL NOT NULL,
url_parameters TEXT DEFAULT '[]' NOT NULL
);
CREATE TABLE websocket_connections
(
id TEXT NOT NULL
PRIMARY KEY,
model TEXT DEFAULT 'websocket_connection' NOT NULL,
workspace_id TEXT NOT NULL
REFERENCES workspaces
ON DELETE CASCADE,
request_id TEXT NOT NULL
REFERENCES websocket_requests
ON DELETE CASCADE,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL,
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL,
url TEXT NOT NULL,
state TEXT NOT NULL,
status INTEGER DEFAULT -1 NOT NULL,
error TEXT NULL,
elapsed INTEGER DEFAULT 0 NOT NULL,
headers TEXT DEFAULT '{}' NOT NULL
);
CREATE TABLE websocket_events
(
id TEXT NOT NULL
PRIMARY KEY,
model TEXT DEFAULT 'websocket_event' NOT NULL,
workspace_id TEXT NOT NULL
REFERENCES workspaces
ON DELETE CASCADE,
request_id TEXT NOT NULL
REFERENCES websocket_requests
ON DELETE CASCADE,
connection_id TEXT NOT NULL
REFERENCES websocket_connections
ON DELETE CASCADE,
created_at DATETIME DEFAULT (STRFTIME('%Y-%m-%d %H:%M:%f', 'NOW')) NOT NULL,
updated_at DATETIME DEFAULT (STRFTIME('%Y-%m-%d %H:%M:%f', 'NOW')) NOT NULL,
is_server BOOLEAN NOT NULL,
message_type TEXT NOT NULL,
message BLOB NOT NULL
);

View File

@@ -42,6 +42,9 @@ pub enum AnalyticsResource {
Sidebar,
Tab,
Theme,
WebsocketConnection,
WebsocketEvent,
WebsocketRequest,
Workspace,
}

View File

@@ -1,6 +1,5 @@
use crate::render::render_http_request;
use crate::response_err;
use crate::template_callback::PluginTemplateCallback;
use http::header::{ACCEPT, USER_AGENT};
use http::{HeaderMap, HeaderName, HeaderValue, Uri};
use log::{debug, error, warn};
@@ -8,8 +7,9 @@ use mime_guess::Mime;
use reqwest::redirect::Policy;
use reqwest::{multipart, Proxy, Url};
use reqwest::{Method, Response};
use rustls::crypto::ring;
use rustls::ClientConfig;
use rustls_platform_verifier::ConfigVerifierExt;
use rustls_platform_verifier::BuilderVerifierExt;
use serde_json::Value;
use std::collections::BTreeMap;
use std::path::PathBuf;
@@ -34,6 +34,7 @@ use yaak_plugins::events::{
CallHttpAuthenticationRequest, HttpHeader, RenderPurpose, WindowContext,
};
use yaak_plugins::manager::PluginManager;
use yaak_plugins::template_callback::PluginTemplateCallback;
pub async fn send_http_request<R: Runtime>(
window: &WebviewWindow<R>,
@@ -86,11 +87,15 @@ pub async fn send_http_request<R: Runtime>(
if workspace.setting_validate_certificates {
// Use platform-native verifier to validate certificates
client_builder =
client_builder.use_preconfigured_tls(ClientConfig::with_platform_verifier())
let arc_crypto_provider = Arc::new(ring::default_provider());
let config = ClientConfig::builder_with_provider(arc_crypto_provider)
.with_safe_default_protocol_versions()
.unwrap()
.with_platform_verifier()
.with_no_client_auth();
client_builder = client_builder.use_preconfigured_tls(config)
} else {
// Use rustls to skip validation because rustls_platform_verifier does not have this
// ability
// Use rustls to skip validation because rustls_platform_verifier does not have this ability
client_builder = client_builder
.use_rustls_tls()
.danger_accept_invalid_hostnames(true)
@@ -220,14 +225,14 @@ pub async fn send_http_request<R: Runtime>(
continue;
}
let header_name = match HeaderName::from_bytes(h.name.as_bytes()) {
let header_name = match HeaderName::from_str(&h.name) {
Ok(n) => n,
Err(e) => {
error!("Failed to create header name: {}", e);
continue;
}
};
let header_value = match HeaderValue::from_str(h.value.as_str()) {
let header_value = match HeaderValue::from_str(&h.value) {
Ok(n) => n,
Err(e) => {
error!("Failed to create header value: {}", e);

View File

@@ -7,7 +7,6 @@ use crate::grpc::metadata_to_map;
use crate::http_request::send_http_request;
use crate::notifications::YaakNotifier;
use crate::render::{render_grpc_request, render_template};
use crate::template_callback::PluginTemplateCallback;
use crate::updates::{UpdateMode, YaakUpdater};
use eventsource_client::{EventParser, SSE};
use log::{debug, error, warn};
@@ -31,29 +30,8 @@ use tokio::sync::Mutex;
use tokio::task::block_in_place;
use yaak_grpc::manager::{DynamicMessage, GrpcHandle};
use yaak_grpc::{deserialize_message, serialize_message, Code, ServiceDefinition};
use yaak_models::models::{
CookieJar, Environment, EnvironmentVariable, Folder, GrpcConnection, GrpcConnectionState,
GrpcEvent, GrpcEventType, GrpcRequest, HttpRequest, HttpResponse, HttpResponseState, KeyValue,
ModelType, Plugin, Settings, Workspace, WorkspaceMeta,
};
use yaak_models::queries::{
batch_upsert, cancel_pending_grpc_connections, cancel_pending_responses,
create_default_http_response, delete_all_grpc_connections,
delete_all_grpc_connections_for_workspace, delete_all_http_responses_for_request,
delete_all_http_responses_for_workspace, delete_cookie_jar, delete_environment, delete_folder,
delete_grpc_connection, delete_grpc_request, delete_http_request, delete_http_response,
delete_plugin, delete_workspace, duplicate_folder, duplicate_grpc_request,
duplicate_http_request, ensure_base_environment, generate_model_id, get_base_environment,
get_cookie_jar, get_environment, get_folder, get_grpc_connection, get_grpc_request,
get_http_request, get_http_response, get_key_value_raw, get_or_create_settings,
get_or_create_workspace_meta, get_plugin, get_workspace, get_workspace_export_resources,
list_cookie_jars, list_environments, list_folders, list_grpc_connections_for_workspace,
list_grpc_events, list_grpc_requests, list_http_requests, list_http_responses_for_workspace,
list_key_values_raw, list_plugins, list_workspaces, set_key_value_raw, update_response_if_id,
update_settings, upsert_cookie_jar, upsert_environment, upsert_folder, upsert_grpc_connection,
upsert_grpc_event, upsert_grpc_request, upsert_http_request, upsert_plugin, upsert_workspace,
upsert_workspace_meta, BatchUpsertResult, UpdateSource,
};
use yaak_models::models::{CookieJar, Environment, EnvironmentVariable, Folder, GrpcConnection, GrpcConnectionState, GrpcEvent, GrpcEventType, GrpcRequest, HttpRequest, HttpResponse, HttpResponseState, KeyValue, ModelType, Plugin, Settings, WebsocketRequest, Workspace, WorkspaceMeta};
use yaak_models::queries::{batch_upsert, cancel_pending_grpc_connections, cancel_pending_responses, create_default_http_response, delete_all_grpc_connections, delete_all_grpc_connections_for_workspace, delete_all_http_responses_for_request, delete_all_http_responses_for_workspace, delete_all_websocket_connections_for_workspace, delete_cookie_jar, delete_environment, delete_folder, delete_grpc_connection, delete_grpc_request, delete_http_request, delete_http_response, delete_plugin, delete_workspace, duplicate_folder, duplicate_grpc_request, duplicate_http_request, ensure_base_environment, generate_model_id, get_base_environment, get_cookie_jar, get_environment, get_folder, get_grpc_connection, get_grpc_request, get_http_request, get_http_response, get_key_value_raw, get_or_create_settings, get_or_create_workspace_meta, get_plugin, get_workspace, get_workspace_export_resources, list_cookie_jars, list_environments, list_folders, list_grpc_connections_for_workspace, list_grpc_events, list_grpc_requests, list_http_requests, list_http_responses_for_workspace, list_key_values_raw, list_plugins, list_workspaces, set_key_value_raw, update_response_if_id, update_settings, upsert_cookie_jar, upsert_environment, upsert_folder, upsert_grpc_connection, upsert_grpc_event, upsert_grpc_request, upsert_http_request, upsert_plugin, upsert_workspace, upsert_workspace_meta, BatchUpsertResult, UpdateSource};
use yaak_plugins::events::{
BootResponse, CallHttpAuthenticationRequest, CallHttpRequestActionRequest, FilterResponse,
GetHttpAuthenticationConfigResponse, GetHttpAuthenticationSummaryResponse,
@@ -61,6 +39,7 @@ use yaak_plugins::events::{
InternalEventPayload, JsonPrimitive, RenderPurpose, WindowContext,
};
use yaak_plugins::manager::PluginManager;
use yaak_plugins::template_callback::PluginTemplateCallback;
use yaak_sse::sse::ServerSentEvent;
use yaak_templates::format::format_json;
use yaak_templates::{Parser, Tokens};
@@ -74,7 +53,6 @@ mod plugin_events;
mod render;
#[cfg(target_os = "macos")]
mod tauri_plugin_mac_window;
mod template_callback;
mod updates;
mod window;
mod window_menu;
@@ -920,6 +898,18 @@ async fn cmd_import_data<R: Runtime>(
})
.collect();
let websocket_requests: Vec<WebsocketRequest> = resources
.websocket_requests
.into_iter()
.map(|mut v| {
v.id = maybe_gen_id(v.id.as_str(), ModelType::TypeWebsocketRequest, &mut id_map);
v.workspace_id =
maybe_gen_id(v.workspace_id.as_str(), ModelType::TypeWorkspace, &mut id_map);
v.folder_id = maybe_gen_id_opt(v.folder_id, ModelType::TypeFolder, &mut id_map);
v
})
.collect();
let upserted = batch_upsert(
&window,
workspaces,
@@ -927,6 +917,7 @@ async fn cmd_import_data<R: Runtime>(
folders,
http_requests,
grpc_requests,
websocket_requests,
&UpdateSource::Import,
)
.await
@@ -1611,6 +1602,9 @@ async fn cmd_delete_send_history(workspace_id: &str, window: WebviewWindow) -> R
delete_all_grpc_connections_for_workspace(&window, workspace_id, &UpdateSource::Window)
.await
.map_err(|e| e.to_string())?;
delete_all_websocket_connections_for_workspace(&window, workspace_id, &UpdateSource::Window)
.await
.map_err(|e| e.to_string())?;
Ok(())
}
@@ -1825,6 +1819,7 @@ pub fn run() {
.plugin(yaak_license::init())
.plugin(yaak_models::plugin::Builder::default().build())
.plugin(yaak_plugins::init())
.plugin(yaak_ws::init())
.plugin(yaak_sync::init());
#[cfg(target_os = "macos")]

View File

@@ -1,6 +1,5 @@
use crate::http_request::send_http_request;
use crate::render::{render_http_request, render_json_value};
use crate::template_callback::PluginTemplateCallback;
use crate::window::{create_window, CreateWindowConfig};
use crate::{
call_frontend, cookie_jar_from_window, environment_from_window, get_window_from_window_context,
@@ -24,6 +23,7 @@ use yaak_plugins::events::{
};
use yaak_plugins::manager::PluginManager;
use yaak_plugins::plugin_handle::PluginHandle;
use yaak_plugins::template_callback::PluginTemplateCallback;
pub(crate) async fn handle_plugin_event<R: Runtime>(
app_handle: &AppHandle<R>,

View File

@@ -1,11 +1,11 @@
use crate::template_callback::PluginTemplateCallback;
use serde_json::{json, Map, Value};
use serde_json::Value;
use std::collections::{BTreeMap, HashMap};
use yaak_models::models::{
Environment, EnvironmentVariable, GrpcMetadataEntry, GrpcRequest, HttpRequest,
Environment, GrpcMetadataEntry, GrpcRequest, HttpRequest,
HttpRequestHeader, HttpUrlParameter,
};
use yaak_templates::{parse_and_render, TemplateCallback};
use yaak_models::render::make_vars_hashmap;
use yaak_templates::{parse_and_render, render_json_value_raw, TemplateCallback};
pub async fn render_template<T: TemplateCallback>(
template: &str,
@@ -60,11 +60,11 @@ pub async fn render_grpc_request<T: TemplateCallback>(
}
}
pub async fn render_http_request(
pub async fn render_http_request<T: TemplateCallback>(
r: &HttpRequest,
base_environment: &Environment,
environment: Option<&Environment>,
cb: &PluginTemplateCallback,
cb: &T,
) -> HttpRequest {
let vars = &make_vars_hashmap(base_environment, environment);
@@ -112,20 +112,6 @@ pub async fn render_http_request(
apply_path_placeholders(req)
}
pub fn make_vars_hashmap(
base_environment: &Environment,
environment: Option<&Environment>,
) -> HashMap<String, String> {
let mut variables = HashMap::new();
variables = add_variable_to_map(variables, &base_environment.variables);
if let Some(e) = environment {
variables = add_variable_to_map(variables, &e.variables);
}
variables
}
pub async fn render<T: TemplateCallback>(
template: &str,
vars: &HashMap<String, String>,
@@ -134,126 +120,6 @@ pub async fn render<T: TemplateCallback>(
parse_and_render(template, vars, cb).await
}
fn add_variable_to_map(
m: HashMap<String, String>,
variables: &Vec<EnvironmentVariable>,
) -> HashMap<String, String> {
let mut map = m.clone();
for variable in variables {
if !variable.enabled || variable.value.is_empty() {
continue;
}
let name = variable.name.as_str();
let value = variable.value.as_str();
map.insert(name.into(), value.into());
}
map
}
async fn render_json_value_raw<T: TemplateCallback>(
v: Value,
vars: &HashMap<String, String>,
cb: &T,
) -> Value {
match v {
Value::String(s) => json!(render(s.as_str(), vars, cb).await),
Value::Array(a) => {
let mut new_a = Vec::new();
for v in a {
new_a.push(Box::pin(render_json_value_raw(v, vars, cb)).await)
}
json!(new_a)
}
Value::Object(o) => {
let mut new_o = Map::new();
for (k, v) in o {
let key = Box::pin(render(k.as_str(), vars, cb)).await;
let value = Box::pin(render_json_value_raw(v, vars, cb)).await;
new_o.insert(key, value);
}
json!(new_o)
}
v => v,
}
}
#[cfg(test)]
mod render_tests {
use serde_json::json;
use std::collections::HashMap;
use yaak_templates::TemplateCallback;
struct EmptyCB {}
impl TemplateCallback for EmptyCB {
async fn run(
&self,
_fn_name: &str,
_args: HashMap<String, String>,
) -> Result<String, String> {
todo!()
}
}
#[tokio::test]
async fn render_json_value_string() {
let v = json!("${[a]}");
let mut vars = HashMap::new();
vars.insert("a".to_string(), "aaa".to_string());
let result = super::render_json_value_raw(v, &vars, &EmptyCB {}).await;
assert_eq!(result, json!("aaa"))
}
#[tokio::test]
async fn render_json_value_array() {
let v = json!(["${[a]}", "${[a]}"]);
let mut vars = HashMap::new();
vars.insert("a".to_string(), "aaa".to_string());
let result = super::render_json_value_raw(v, &vars, &EmptyCB {}).await;
assert_eq!(result, json!(["aaa", "aaa"]))
}
#[tokio::test]
async fn render_json_value_object() {
let v = json!({"${[a]}": "${[a]}"});
let mut vars = HashMap::new();
vars.insert("a".to_string(), "aaa".to_string());
let result = super::render_json_value_raw(v, &vars, &EmptyCB {}).await;
assert_eq!(result, json!({"aaa": "aaa"}))
}
#[tokio::test]
async fn render_json_value_nested() {
let v = json!([
123,
{"${[a]}": "${[a]}"},
null,
"${[a]}",
false,
{"x": ["${[a]}"]}
]);
let mut vars = HashMap::new();
vars.insert("a".to_string(), "aaa".to_string());
let result = super::render_json_value_raw(v, &vars, &EmptyCB {}).await;
assert_eq!(
result,
json!([
123,
{"aaa": "aaa"},
null,
"aaa",
false,
{"x": ["aaa"]}
])
)
}
}
fn replace_path_placeholder(p: &HttpUrlParameter, url: &str) -> String {
if !p.enabled {
return url.to_string();

View File

@@ -2,7 +2,8 @@ use crate::MAIN_WINDOW_PREFIX;
use hex_color::HexColor;
use log::warn;
use objc::{msg_send, sel, sel_impl};
use rand::{distributions::Alphanumeric, Rng};
use rand::distr::Alphanumeric;
use rand::Rng;
use tauri::{
plugin::{Builder, TauriPlugin},
Emitter, Listener, Manager, Runtime, Window, WindowEvent,
@@ -420,7 +421,7 @@ pub fn setup_traffic_light_positioner<R: Runtime>(window: &Window<R>) {
};
let app_box = Box::into_raw(Box::new(app_state)) as *mut c_void;
let random_str: String =
rand::thread_rng().sample_iter(&Alphanumeric).take(20).map(char::from).collect();
rand::rng().sample_iter(&Alphanumeric).take(20).map(char::from).collect();
// We need to ensure we have a unique delegate name, otherwise we will panic while trying to create a duplicate
// delegate with the same name.

View File

@@ -9,8 +9,10 @@ anyhow = "1.0.79"
async-recursion = "1.1.1"
dunce = "1.0.4"
hyper = "1.5.2"
hyper-rustls = { version = "0.27.5", default-features = false, features = ["http2", "rustls-platform-verifier"] }
hyper-util = { version = "0.1.10", features = ["client-legacy", "client"] }
hyper-rustls = { version = "0.27.5", default-features = false, features = ["http2"] }
hyper-util = { version = "0.1.10", default-features = false, features = ["client-legacy"] }
rustls = { version = "0.23.21", default-features = false, features = ["custom-provider", "ring"] }
rustls-platform-verifier = "0.5.0"
log = "0.4.20"
md5 = "0.7.0"
prost = "0.13.4"

View File

@@ -2,17 +2,30 @@ use hyper_rustls::{HttpsConnector, HttpsConnectorBuilder};
use hyper_util::client::legacy::connect::HttpConnector;
use hyper_util::client::legacy::Client;
use hyper_util::rt::TokioExecutor;
use rustls::crypto::ring;
use rustls::ClientConfig;
use rustls_platform_verifier::BuilderVerifierExt;
use std::sync::Arc;
use tonic::body::BoxBody;
pub(crate) fn get_transport() -> Client<HttpsConnector<HttpConnector>, BoxBody> {
let connector = HttpsConnectorBuilder::new().with_platform_verifier();
let connector = connector.https_or_http().enable_http2().wrap_connector({
let mut http_connector = HttpConnector::new();
http_connector.enforce_http(false);
http_connector
});
Client::builder(TokioExecutor::new())
let arc_crypto_provider = Arc::new(ring::default_provider());
let config = ClientConfig::builder_with_provider(arc_crypto_provider)
.with_safe_default_protocol_versions()
.unwrap()
.with_platform_verifier()
.with_no_client_auth();
let mut http = HttpConnector::new();
http.enforce_http(false);
let connector =
HttpsConnectorBuilder::new().with_tls_config(config).https_or_http().enable_http2().build();
let client = Client::builder(TokioExecutor::new())
.pool_max_idle_per_host(0)
.http2_only(true)
.build(connector)
.build(connector);
client
}

View File

@@ -17,4 +17,4 @@ log = "0.4.22"
serde_json = "1.0.132"
[build-dependencies]
tauri-plugin = { version = "2.0.3", features = ["build"] }
tauri-plugin = { workspace = true, features = ["build"] }

View File

@@ -1,6 +1,6 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
export type AnyModel = CookieJar | Environment | Folder | GrpcConnection | GrpcEvent | GrpcRequest | HttpRequest | HttpResponse | Plugin | Settings | KeyValue | Workspace | WorkspaceMeta;
export type AnyModel = CookieJar | Environment | Folder | GrpcConnection | GrpcEvent | GrpcRequest | HttpRequest | HttpResponse | Plugin | Settings | KeyValue | Workspace | WorkspaceMeta | WebsocketConnection | WebsocketEvent | WebsocketRequest;
export type Cookie = { raw_cookie: string, domain: CookieDomain, expires: CookieExpires, path: [string, boolean], };
@@ -48,6 +48,8 @@ export type ModelPayload = { model: AnyModel, windowLabel: string, updateSource:
export type Plugin = { model: "plugin", id: string, createdAt: string, updatedAt: string, checkedAt: string | null, directory: string, enabled: boolean, url: string | null, };
export type PluginKeyValue = { model: "plugin_key_value", createdAt: string, updatedAt: string, pluginName: string, key: string, value: string, };
export type ProxySetting = { "type": "enabled", http: string, https: string, auth: ProxySettingAuth | null, } | { "type": "disabled" };
export type ProxySettingAuth = { user: string, password: string, };
@@ -60,6 +62,18 @@ export type SyncState = { model: "sync_state", id: string, workspaceId: string,
export type UpdateSource = "sync" | "window" | "plugin" | "background" | "import";
export type WebsocketConnection = { model: "websocket_connection", id: string, createdAt: string, updatedAt: string, workspaceId: string, requestId: string, elapsed: number, error: string | null, headers: Array<HttpResponseHeader>, state: WebsocketConnectionState, status: number, url: string, };
export type WebsocketConnectionState = "initialized" | "connected" | "closed";
export type WebsocketEvent = { model: "websocket_event", id: string, createdAt: string, updatedAt: string, workspaceId: string, requestId: string, connectionId: string, isServer: boolean, message: Array<number>, messageType: WebsocketEventType, };
export type WebsocketEventType = "binary" | "close" | "frame" | "ping" | "pong" | "text";
export type WebsocketMessageType = "text" | "binary";
export type WebsocketRequest = { model: "websocket_request", id: string, createdAt: string, updatedAt: string, workspaceId: string, folderId: string | null, authentication: Record<string, any>, authenticationType: string | null, description: string, headers: Array<HttpRequestHeader>, message: string, name: string, sortPriority: number, url: string, urlParameters: Array<HttpUrlParameter>, };
export type Workspace = { model: "workspace", id: string, createdAt: string, updatedAt: string, name: string, description: string, settingValidateCertificates: boolean, settingFollowRedirects: boolean, settingRequestTimeout: number, };
export type WorkspaceMeta = { model: "workspace_meta", id: string, workspaceId: string, createdAt: string, updatedAt: string, settingSyncDir: string | null, };

View File

@@ -3,3 +3,4 @@ pub mod models;
pub mod queries;
pub mod plugin;
pub mod render;

View File

@@ -125,7 +125,7 @@ impl<'s> TryFrom<&Row<'s>> for Settings {
fn try_from(r: &Row<'s>) -> Result<Self, Self::Error> {
let proxy: Option<String> = r.get("proxy")?;
let editor_keymap: String = r.get("editor_keymap")?;
Ok(Settings {
Ok(Self {
id: r.get("id")?,
model: r.get("model")?,
created_at: r.get("created_at")?,
@@ -187,7 +187,7 @@ impl<'s> TryFrom<&Row<'s>> for Workspace {
type Error = rusqlite::Error;
fn try_from(r: &Row<'s>) -> Result<Self, Self::Error> {
Ok(Workspace {
Ok(Self {
id: r.get("id")?,
model: r.get("model")?,
created_at: r.get("created_at")?,
@@ -243,7 +243,7 @@ impl<'s> TryFrom<&Row<'s>> for WorkspaceMeta {
type Error = rusqlite::Error;
fn try_from(r: &Row<'s>) -> Result<Self, Self::Error> {
Ok(WorkspaceMeta {
Ok(Self {
id: r.get("id")?,
workspace_id: r.get("workspace_id")?,
model: r.get("model")?,
@@ -313,7 +313,7 @@ impl<'s> TryFrom<&Row<'s>> for CookieJar {
fn try_from(r: &Row<'s>) -> Result<Self, Self::Error> {
let cookies: String = r.get("cookies")?;
Ok(CookieJar {
Ok(Self {
id: r.get("id")?,
model: r.get("model")?,
workspace_id: r.get("workspace_id")?,
@@ -361,7 +361,7 @@ impl<'s> TryFrom<&Row<'s>> for Environment {
fn try_from(r: &Row<'s>) -> Result<Self, Self::Error> {
let variables: String = r.get("variables")?;
Ok(Environment {
Ok(Self {
id: r.get("id")?,
model: r.get("model")?,
workspace_id: r.get("workspace_id")?,
@@ -424,7 +424,7 @@ impl<'s> TryFrom<&Row<'s>> for Folder {
type Error = rusqlite::Error;
fn try_from(r: &Row<'s>) -> Result<Self, Self::Error> {
Ok(Folder {
Ok(Self {
id: r.get("id")?,
model: r.get("model")?,
sort_priority: r.get("sort_priority")?,
@@ -484,7 +484,7 @@ pub struct HttpRequest {
pub body_type: Option<String>,
pub description: String,
pub headers: Vec<HttpRequestHeader>,
#[serde(default = "default_http_request_method")]
#[serde(default = "default_http_method")]
pub method: String,
pub name: String,
pub sort_priority: f32,
@@ -524,7 +524,7 @@ impl<'s> TryFrom<&Row<'s>> for HttpRequest {
let body: String = r.get("body")?;
let authentication: String = r.get("authentication")?;
let headers: String = r.get("headers")?;
Ok(HttpRequest {
Ok(Self {
id: r.get("id")?,
model: r.get("model")?,
sort_priority: r.get("sort_priority")?,
@@ -546,6 +546,243 @@ impl<'s> TryFrom<&Row<'s>> for HttpRequest {
}
}
#[derive(Debug, Clone, Serialize, Deserialize, TS)]
#[serde(rename_all = "snake_case")]
#[ts(export, export_to = "gen_models.ts")]
pub enum WebsocketConnectionState {
Initialized,
Connected,
Closed,
}
impl Default for WebsocketConnectionState {
fn default() -> Self {
Self::Initialized
}
}
#[derive(Debug, Clone, Serialize, Deserialize, Default, TS)]
#[serde(default, rename_all = "camelCase")]
#[ts(export, export_to = "gen_models.ts")]
pub struct WebsocketConnection {
#[ts(type = "\"websocket_connection\"")]
pub model: String,
pub id: String,
pub created_at: NaiveDateTime,
pub updated_at: NaiveDateTime,
pub workspace_id: String,
pub request_id: String,
pub elapsed: i32,
pub error: Option<String>,
pub headers: Vec<HttpResponseHeader>,
pub state: WebsocketConnectionState,
pub status: i32,
pub url: String,
}
#[derive(Iden)]
pub enum WebsocketConnectionIden {
#[iden = "websocket_connections"]
Table,
Id,
Model,
CreatedAt,
UpdatedAt,
WorkspaceId,
RequestId,
Elapsed,
Error,
Headers,
State,
Status,
Url,
}
impl<'s> TryFrom<&Row<'s>> for WebsocketConnection {
type Error = rusqlite::Error;
fn try_from(r: &Row<'s>) -> Result<Self, Self::Error> {
let headers: String = r.get("headers")?;
let state: String = r.get("state")?;
Ok(Self {
id: r.get("id")?,
model: r.get("model")?,
workspace_id: r.get("workspace_id")?,
request_id: r.get("request_id")?,
created_at: r.get("created_at")?,
updated_at: r.get("updated_at")?,
url: r.get("url")?,
headers: serde_json::from_str(headers.as_str()).unwrap_or_default(),
elapsed: r.get("elapsed")?,
error: r.get("error")?,
state: serde_json::from_str(format!(r#""{state}""#).as_str()).unwrap(),
status: r.get("status")?,
})
}
}
#[derive(Debug, Clone, Serialize, Deserialize, Eq, PartialEq, TS)]
#[serde(rename_all = "snake_case")]
#[ts(export, export_to = "gen_models.ts")]
pub enum WebsocketMessageType {
Text,
Binary,
}
impl Default for WebsocketMessageType {
fn default() -> Self {
Self::Text
}
}
#[derive(Debug, Clone, Serialize, Deserialize, Default, TS)]
#[serde(default, rename_all = "camelCase")]
#[ts(export, export_to = "gen_models.ts")]
pub struct WebsocketRequest {
#[ts(type = "\"websocket_request\"")]
pub model: String,
pub id: String,
pub created_at: NaiveDateTime,
pub updated_at: NaiveDateTime,
pub workspace_id: String,
pub folder_id: Option<String>,
#[ts(type = "Record<string, any>")]
pub authentication: BTreeMap<String, Value>,
pub authentication_type: Option<String>,
pub description: String,
pub headers: Vec<HttpRequestHeader>,
pub message: String,
pub name: String,
pub sort_priority: f32,
pub url: String,
pub url_parameters: Vec<HttpUrlParameter>,
}
#[derive(Iden)]
pub enum WebsocketRequestIden {
#[iden = "websocket_requests"]
Table,
Id,
Model,
CreatedAt,
UpdatedAt,
WorkspaceId,
FolderId,
Authentication,
AuthenticationType,
Message,
Description,
Headers,
Name,
SortPriority,
Url,
UrlParameters,
}
impl<'s> TryFrom<&Row<'s>> for WebsocketRequest {
type Error = rusqlite::Error;
fn try_from(r: &Row<'s>) -> Result<Self, Self::Error> {
let url_parameters: String = r.get("url_parameters")?;
let authentication: String = r.get("authentication")?;
let headers: String = r.get("headers")?;
Ok(Self {
id: r.get("id")?,
model: r.get("model")?,
sort_priority: r.get("sort_priority")?,
workspace_id: r.get("workspace_id")?,
created_at: r.get("created_at")?,
updated_at: r.get("updated_at")?,
url: r.get("url")?,
url_parameters: serde_json::from_str(url_parameters.as_str()).unwrap_or_default(),
message: r.get("message")?,
description: r.get("description")?,
authentication: serde_json::from_str(authentication.as_str()).unwrap_or_default(),
authentication_type: r.get("authentication_type")?,
headers: serde_json::from_str(headers.as_str()).unwrap_or_default(),
folder_id: r.get("folder_id")?,
name: r.get("name")?,
})
}
}
#[derive(Debug, Clone, Serialize, Deserialize, Eq, PartialEq, TS)]
#[serde(rename_all = "snake_case")]
#[ts(export, export_to = "gen_models.ts")]
pub enum WebsocketEventType {
Binary,
Close,
Frame,
Ping,
Pong,
Text,
}
impl Default for WebsocketEventType {
fn default() -> Self {
Self::Text
}
}
#[derive(Debug, Clone, Serialize, Deserialize, Default, TS)]
#[serde(default, rename_all = "camelCase")]
#[ts(export, export_to = "gen_models.ts")]
pub struct WebsocketEvent {
#[ts(type = "\"websocket_event\"")]
pub model: String,
pub id: String,
pub created_at: NaiveDateTime,
pub updated_at: NaiveDateTime,
pub workspace_id: String,
pub request_id: String,
pub connection_id: String,
pub is_server: bool,
pub message: Vec<u8>,
pub message_type: WebsocketEventType,
}
#[derive(Iden)]
pub enum WebsocketEventIden {
#[iden = "websocket_events"]
Table,
Model,
Id,
CreatedAt,
UpdatedAt,
WorkspaceId,
RequestId,
ConnectionId,
IsServer,
MessageType,
Message,
}
impl<'s> TryFrom<&Row<'s>> for WebsocketEvent {
type Error = rusqlite::Error;
fn try_from(r: &Row<'s>) -> Result<Self, Self::Error> {
let message_type: String = r.get("message_type")?;
Ok(Self {
id: r.get("id")?,
model: r.get("model")?,
workspace_id: r.get("workspace_id")?,
request_id: r.get("request_id")?,
connection_id: r.get("connection_id")?,
created_at: r.get("created_at")?,
updated_at: r.get("updated_at")?,
message: r.get("message")?,
is_server: r.get("is_server")?,
message_type: serde_json::from_str(message_type.as_str()).unwrap_or_default(),
})
}
}
#[derive(Debug, Clone, Serialize, Deserialize, Default, TS)]
#[serde(default, rename_all = "camelCase")]
#[ts(export, export_to = "gen_models.ts")]
@@ -626,7 +863,7 @@ impl<'s> TryFrom<&Row<'s>> for HttpResponse {
fn try_from(r: &Row<'s>) -> Result<Self, Self::Error> {
let headers: String = r.get("headers")?;
let state: String = r.get("state")?;
Ok(HttpResponse {
Ok(Self {
id: r.get("id")?,
model: r.get("model")?,
workspace_id: r.get("workspace_id")?,
@@ -725,7 +962,7 @@ impl<'s> TryFrom<&Row<'s>> for GrpcRequest {
fn try_from(r: &Row<'s>) -> Result<Self, Self::Error> {
let authentication: String = r.get("authentication")?;
let metadata: String = r.get("metadata")?;
Ok(GrpcRequest {
Ok(Self {
id: r.get("id")?,
model: r.get("model")?,
workspace_id: r.get("workspace_id")?,
@@ -810,7 +1047,7 @@ impl<'s> TryFrom<&Row<'s>> for GrpcConnection {
fn try_from(r: &Row<'s>) -> Result<Self, Self::Error> {
let trailers: String = r.get("trailers")?;
let state: String = r.get("state")?;
Ok(GrpcConnection {
Ok(Self {
id: r.get("id")?,
model: r.get("model")?,
workspace_id: r.get("workspace_id")?,
@@ -892,7 +1129,7 @@ impl<'s> TryFrom<&Row<'s>> for GrpcEvent {
fn try_from(r: &Row<'s>) -> Result<Self, Self::Error> {
let event_type: String = r.get("event_type")?;
let metadata: String = r.get("metadata")?;
Ok(GrpcEvent {
Ok(Self {
id: r.get("id")?,
model: r.get("model")?,
workspace_id: r.get("workspace_id")?,
@@ -944,7 +1181,7 @@ impl<'s> TryFrom<&Row<'s>> for Plugin {
type Error = rusqlite::Error;
fn try_from(r: &Row<'s>) -> Result<Self, Self::Error> {
Ok(Plugin {
Ok(Self {
id: r.get("id")?,
model: r.get("model")?,
created_at: r.get("created_at")?,
@@ -1012,7 +1249,7 @@ impl<'s> TryFrom<&Row<'s>> for SyncState {
type Error = rusqlite::Error;
fn try_from(r: &Row<'s>) -> Result<Self, Self::Error> {
Ok(SyncState {
Ok(Self {
id: r.get("id")?,
workspace_id: r.get("workspace_id")?,
model: r.get("model")?,
@@ -1058,7 +1295,7 @@ impl<'s> TryFrom<&Row<'s>> for KeyValue {
type Error = rusqlite::Error;
fn try_from(r: &Row<'s>) -> Result<Self, Self::Error> {
Ok(KeyValue {
Ok(Self {
model: r.get("model")?,
created_at: r.get("created_at")?,
updated_at: r.get("updated_at")?,
@@ -1100,7 +1337,7 @@ impl<'s> TryFrom<&Row<'s>> for PluginKeyValue {
type Error = rusqlite::Error;
fn try_from(r: &Row<'s>) -> Result<Self, Self::Error> {
Ok(PluginKeyValue {
Ok(Self {
model: r.get("model")?,
created_at: r.get("created_at")?,
updated_at: r.get("updated_at")?,
@@ -1115,7 +1352,7 @@ fn default_true() -> bool {
true
}
fn default_http_request_method() -> String {
fn default_http_method() -> String {
"GET".to_string()
}
@@ -1129,9 +1366,12 @@ pub enum ModelType {
TypeHttpRequest,
TypeHttpResponse,
TypePlugin,
TypeSyncState,
TypeWebSocketConnection,
TypeWebSocketEvent,
TypeWebsocketRequest,
TypeWorkspace,
TypeWorkspaceMeta,
TypeSyncState,
}
impl ModelType {
@@ -1149,6 +1389,9 @@ impl ModelType {
ModelType::TypeWorkspace => "wk",
ModelType::TypeWorkspaceMeta => "wm",
ModelType::TypeSyncState => "ss",
ModelType::TypeWebSocketConnection => "wc",
ModelType::TypeWebSocketEvent => "we",
ModelType::TypeWebsocketRequest => "wr",
}
.to_string()
}
@@ -1171,6 +1414,9 @@ pub enum AnyModel {
KeyValue(KeyValue),
Workspace(Workspace),
WorkspaceMeta(WorkspaceMeta),
WebsocketConnection(WebsocketConnection),
WebsocketEvent(WebsocketEvent),
WebsocketRequest(WebsocketRequest),
}
impl<'de> Deserialize<'de> for AnyModel {

View File

@@ -1,6 +1,15 @@
use crate::error::Error::ModelNotFound;
use crate::error::Result;
use crate::models::{AnyModel, CookieJar, CookieJarIden, Environment, EnvironmentIden, Folder, FolderIden, GrpcConnection, GrpcConnectionIden, GrpcConnectionState, GrpcEvent, GrpcEventIden, GrpcRequest, GrpcRequestIden, HttpRequest, HttpRequestIden, HttpResponse, HttpResponseHeader, HttpResponseIden, HttpResponseState, KeyValue, KeyValueIden, ModelType, Plugin, PluginIden, PluginKeyValue, PluginKeyValueIden, Settings, SettingsIden, SyncState, SyncStateIden, Workspace, WorkspaceIden, WorkspaceMeta, WorkspaceMetaIden};
use crate::models::{
AnyModel, CookieJar, CookieJarIden, Environment, EnvironmentIden, Folder, FolderIden,
GrpcConnection, GrpcConnectionIden, GrpcConnectionState, GrpcEvent, GrpcEventIden, GrpcRequest,
GrpcRequestIden, HttpRequest, HttpRequestIden, HttpResponse, HttpResponseHeader,
HttpResponseIden, HttpResponseState, KeyValue, KeyValueIden, ModelType, Plugin, PluginIden,
PluginKeyValue, PluginKeyValueIden, Settings, SettingsIden, SyncState, SyncStateIden,
WebsocketConnection, WebsocketConnectionIden, WebsocketEvent, WebsocketEventIden,
WebsocketRequest, WebsocketRequestIden, Workspace, WorkspaceIden, WorkspaceMeta,
WorkspaceMetaIden,
};
use crate::plugin::SqliteConnection;
use chrono::{NaiveDateTime, Utc};
use log::{debug, error, info, warn};
@@ -16,8 +25,7 @@ use std::path::Path;
use tauri::{AppHandle, Emitter, Listener, Manager, Runtime, WebviewWindow};
use ts_rs::TS;
const MAX_GRPC_CONNECTIONS_PER_REQUEST: usize = 20;
const MAX_HTTP_RESPONSES_PER_REQUEST: usize = MAX_GRPC_CONNECTIONS_PER_REQUEST;
const MAX_HISTORY_ITEMS: usize = 20;
pub async fn set_key_value_string<R: Runtime>(
mgr: &WebviewWindow<R>,
@@ -659,8 +667,8 @@ pub async fn upsert_grpc_connection<R: Runtime>(
update_source: &UpdateSource,
) -> Result<GrpcConnection> {
let connections =
list_http_responses_for_request(window, connection.request_id.as_str(), None).await?;
for c in connections.iter().skip(MAX_GRPC_CONNECTIONS_PER_REQUEST - 1) {
list_grpc_connections_for_request(window, connection.request_id.as_str()).await?;
for c in connections.iter().skip(MAX_HISTORY_ITEMS - 1) {
debug!("Deleting old grpc connection {}", c.id);
delete_grpc_connection(window, c.id.as_str(), update_source).await?;
}
@@ -911,6 +919,367 @@ pub async fn list_grpc_events<R: Runtime>(
Ok(items.map(|v| v.unwrap()).collect())
}
pub async fn delete_websocket_request<R: Runtime>(
window: &WebviewWindow<R>,
id: &str,
update_source: &UpdateSource,
) -> Result<WebsocketRequest> {
let request = match get_websocket_request(window, id).await? {
Some(r) => r,
None => {
return Err(ModelNotFound(id.to_string()));
}
};
let dbm = &*window.app_handle().state::<SqliteConnection>();
let db = dbm.0.lock().await.get().unwrap();
let (sql, params) = Query::delete()
.from_table(WebsocketRequestIden::Table)
.cond_where(Expr::col(WebsocketRequestIden::Id).eq(id))
.build_rusqlite(SqliteQueryBuilder);
db.execute(sql.as_str(), &*params.as_params())?;
emit_deleted_model(window, &AnyModel::WebsocketRequest(request.to_owned()), update_source);
Ok(request)
}
pub async fn delete_websocket_connection<R: Runtime>(
window: &WebviewWindow<R>,
id: &str,
update_source: &UpdateSource,
) -> Result<WebsocketConnection> {
let m = get_websocket_connection(window, id).await?;
let dbm = &*window.app_handle().state::<SqliteConnection>();
let db = dbm.0.lock().await.get().unwrap();
let (sql, params) = Query::delete()
.from_table(WebsocketConnectionIden::Table)
.cond_where(Expr::col(WebsocketConnectionIden::Id).eq(id))
.build_rusqlite(SqliteQueryBuilder);
db.execute(sql.as_str(), &*params.as_params())?;
emit_deleted_model(window, &AnyModel::WebsocketConnection(m.to_owned()), update_source);
Ok(m)
}
pub async fn delete_all_websocket_connections<R: Runtime>(
window: &WebviewWindow<R>,
request_id: &str,
update_source: &UpdateSource,
) -> Result<()> {
for c in list_websocket_connections_for_request(window, request_id).await? {
delete_websocket_connection(window, &c.id, update_source).await?;
}
Ok(())
}
pub async fn delete_all_websocket_connections_for_workspace<R: Runtime>(
window: &WebviewWindow<R>,
workspace_id: &str,
update_source: &UpdateSource,
) -> Result<()> {
for c in list_websocket_connections_for_workspace(window, workspace_id).await? {
delete_websocket_connection(window, &c.id, update_source).await?;
}
Ok(())
}
pub async fn get_websocket_connection<R: Runtime>(
mgr: &impl Manager<R>,
id: &str,
) -> Result<WebsocketConnection> {
let dbm = &*mgr.state::<SqliteConnection>();
let db = dbm.0.lock().await.get().unwrap();
let (sql, params) = Query::select()
.from(WebsocketConnectionIden::Table)
.column(Asterisk)
.cond_where(Expr::col(WebsocketConnectionIden::Id).eq(id))
.build_rusqlite(SqliteQueryBuilder);
let mut stmt = db.prepare(sql.as_str())?;
Ok(stmt.query_row(&*params.as_params(), |row| row.try_into())?)
}
pub async fn upsert_websocket_event<R: Runtime>(
window: &WebviewWindow<R>,
event: WebsocketEvent,
update_source: &UpdateSource,
) -> Result<WebsocketEvent> {
let id = match event.id.as_str() {
"" => generate_model_id(ModelType::TypeWebSocketEvent),
_ => event.id.to_string(),
};
let dbm = &*window.app_handle().state::<SqliteConnection>();
let db = dbm.0.lock().await.get().unwrap();
let (sql, params) = Query::insert()
.into_table(WebsocketEventIden::Table)
.columns([
WebsocketEventIden::Id,
WebsocketEventIden::CreatedAt,
WebsocketEventIden::UpdatedAt,
WebsocketEventIden::WorkspaceId,
WebsocketEventIden::ConnectionId,
WebsocketEventIden::RequestId,
WebsocketEventIden::MessageType,
WebsocketEventIden::IsServer,
WebsocketEventIden::Message,
])
.values_panic([
id.into(),
timestamp_for_upsert(update_source, event.created_at).into(),
timestamp_for_upsert(update_source, event.updated_at).into(),
event.workspace_id.into(),
event.connection_id.into(),
event.request_id.into(),
serde_json::to_string(&event.message_type)?.into(),
event.is_server.into(),
event.message.into(),
])
.on_conflict(
OnConflict::column(WebsocketEventIden::Id)
.update_columns([
WebsocketEventIden::UpdatedAt,
WebsocketEventIden::MessageType,
WebsocketEventIden::IsServer,
WebsocketEventIden::Message,
])
.to_owned(),
)
.returning_all()
.build_rusqlite(SqliteQueryBuilder);
let mut stmt = db.prepare(sql.as_str())?;
let m: WebsocketEvent = stmt.query_row(&*params.as_params(), |row| row.try_into())?;
emit_upserted_model(window, &AnyModel::WebsocketEvent(m.to_owned()), update_source);
Ok(m)
}
pub async fn upsert_websocket_request<R: Runtime>(
window: &WebviewWindow<R>,
request: WebsocketRequest,
update_source: &UpdateSource,
) -> Result<WebsocketRequest> {
let id = match request.id.as_str() {
"" => generate_model_id(ModelType::TypeWebsocketRequest),
_ => request.id.to_string(),
};
let trimmed_name = request.name.trim();
let dbm = &*window.app_handle().state::<SqliteConnection>();
let db = dbm.0.lock().await.get().unwrap();
let (sql, params) = Query::insert()
.into_table(WebsocketRequestIden::Table)
.columns([
WebsocketRequestIden::Id,
WebsocketRequestIden::CreatedAt,
WebsocketRequestIden::UpdatedAt,
WebsocketRequestIden::WorkspaceId,
WebsocketRequestIden::FolderId,
WebsocketRequestIden::Authentication,
WebsocketRequestIden::AuthenticationType,
WebsocketRequestIden::Description,
WebsocketRequestIden::Headers,
WebsocketRequestIden::Message,
WebsocketRequestIden::Name,
WebsocketRequestIden::SortPriority,
WebsocketRequestIden::Url,
WebsocketRequestIden::UrlParameters,
])
.values_panic([
id.into(),
timestamp_for_upsert(update_source, request.created_at).into(),
timestamp_for_upsert(update_source, request.updated_at).into(),
request.workspace_id.into(),
request.folder_id.as_ref().map(|s| s.as_str()).into(),
serde_json::to_string(&request.authentication)?.into(),
request.authentication_type.as_ref().map(|s| s.as_str()).into(),
request.description.into(),
serde_json::to_string(&request.headers)?.into(),
request.message.into(),
trimmed_name.into(),
request.sort_priority.into(),
request.url.into(),
serde_json::to_string(&request.url_parameters)?.into(),
])
.on_conflict(
OnConflict::column(WebsocketRequestIden::Id)
.update_columns([
WebsocketRequestIden::UpdatedAt,
WebsocketRequestIden::WorkspaceId,
WebsocketRequestIden::FolderId,
WebsocketRequestIden::Authentication,
WebsocketRequestIden::AuthenticationType,
WebsocketRequestIden::Description,
WebsocketRequestIden::Headers,
WebsocketRequestIden::Message,
WebsocketRequestIden::Name,
WebsocketRequestIden::SortPriority,
WebsocketRequestIden::Url,
WebsocketRequestIden::UrlParameters,
])
.to_owned(),
)
.returning_all()
.build_rusqlite(SqliteQueryBuilder);
let mut stmt = db.prepare(sql.as_str())?;
let m: WebsocketRequest = stmt.query_row(&*params.as_params(), |row| row.try_into())?;
emit_upserted_model(window, &AnyModel::WebsocketRequest(m.to_owned()), update_source);
Ok(m)
}
pub async fn list_websocket_connections_for_workspace<R: Runtime>(
mgr: &impl Manager<R>,
workspace_id: &str,
) -> Result<Vec<WebsocketConnection>> {
let dbm = &*mgr.state::<SqliteConnection>();
let db = dbm.0.lock().await.get().unwrap();
let (sql, params) = Query::select()
.from(WebsocketConnectionIden::Table)
.cond_where(Expr::col(WebsocketConnectionIden::WorkspaceId).eq(workspace_id))
.column(Asterisk)
.order_by(WebsocketConnectionIden::CreatedAt, Order::Desc)
.build_rusqlite(SqliteQueryBuilder);
let mut stmt = db.prepare(sql.as_str())?;
let items = stmt.query_map(&*params.as_params(), |row| row.try_into())?;
Ok(items.map(|v| v.unwrap()).collect())
}
pub async fn list_websocket_connections_for_request<R: Runtime>(
mgr: &impl Manager<R>,
request_id: &str,
) -> Result<Vec<WebsocketConnection>> {
let dbm = &*mgr.state::<SqliteConnection>();
let db = dbm.0.lock().await.get().unwrap();
let (sql, params) = Query::select()
.from(WebsocketConnectionIden::Table)
.cond_where(Expr::col(WebsocketConnectionIden::RequestId).eq(request_id))
.column(Asterisk)
.order_by(WebsocketConnectionIden::CreatedAt, Order::Desc)
.build_rusqlite(SqliteQueryBuilder);
let mut stmt = db.prepare(sql.as_str())?;
let items = stmt.query_map(&*params.as_params(), |row| row.try_into())?;
Ok(items.map(|v| v.unwrap()).collect())
}
pub async fn upsert_websocket_connection<R: Runtime>(
window: &WebviewWindow<R>,
connection: &WebsocketConnection,
update_source: &UpdateSource,
) -> Result<WebsocketConnection> {
let connections =
list_websocket_connections_for_request(window, connection.request_id.as_str()).await?;
for c in connections.iter().skip(MAX_HISTORY_ITEMS - 1) {
debug!("Deleting old websocket connection {}", c.id);
delete_websocket_connection(window, c.id.as_str(), update_source).await?;
}
let id = match connection.id.as_str() {
"" => generate_model_id(ModelType::TypeWebSocketConnection),
_ => connection.id.to_string(),
};
let dbm = &*window.app_handle().state::<SqliteConnection>();
let db = dbm.0.lock().await.get().unwrap();
let (sql, params) = Query::insert()
.into_table(WebsocketConnectionIden::Table)
.columns([
WebsocketConnectionIden::Id,
WebsocketConnectionIden::CreatedAt,
WebsocketConnectionIden::UpdatedAt,
WebsocketConnectionIden::WorkspaceId,
WebsocketConnectionIden::RequestId,
WebsocketConnectionIden::Elapsed,
WebsocketConnectionIden::Error,
WebsocketConnectionIden::Headers,
WebsocketConnectionIden::State,
WebsocketConnectionIden::Status,
WebsocketConnectionIden::Url,
])
.values_panic([
id.as_str().into(),
timestamp_for_upsert(update_source, connection.created_at).into(),
timestamp_for_upsert(update_source, connection.updated_at).into(),
connection.workspace_id.as_str().into(),
connection.request_id.as_str().into(),
connection.elapsed.into(),
connection.error.as_ref().map(|s| s.as_str()).into(),
serde_json::to_string(&connection.headers)?.into(),
serde_json::to_value(&connection.state)?.as_str().into(),
connection.status.into(),
connection.url.as_str().into(),
])
.on_conflict(
OnConflict::column(WebsocketConnectionIden::Id)
.update_columns([
WebsocketConnectionIden::UpdatedAt,
WebsocketConnectionIden::Elapsed,
WebsocketConnectionIden::Error,
WebsocketConnectionIden::Headers,
WebsocketConnectionIden::State,
WebsocketConnectionIden::Status,
WebsocketConnectionIden::Url,
])
.to_owned(),
)
.returning_all()
.build_rusqlite(SqliteQueryBuilder);
let mut stmt = db.prepare(sql.as_str())?;
let m: WebsocketConnection = stmt.query_row(&*params.as_params(), |row| row.try_into())?;
emit_upserted_model(window, &AnyModel::WebsocketConnection(m.to_owned()), update_source);
Ok(m)
}
pub async fn get_websocket_request<R: Runtime>(
mgr: &impl Manager<R>,
id: &str,
) -> Result<Option<WebsocketRequest>> {
let dbm = &*mgr.state::<SqliteConnection>();
let db = dbm.0.lock().await.get().unwrap();
let (sql, params) = Query::select()
.from(WebsocketRequestIden::Table)
.column(Asterisk)
.cond_where(Expr::col(WebsocketRequestIden::Id).eq(id))
.build_rusqlite(SqliteQueryBuilder);
let mut stmt = db.prepare(sql.as_str())?;
Ok(stmt.query_row(&*params.as_params(), |row| row.try_into()).optional()?)
}
pub async fn list_websocket_requests<R: Runtime>(
mgr: &impl Manager<R>,
workspace_id: &str,
) -> Result<Vec<WebsocketRequest>> {
let dbm = &*mgr.state::<SqliteConnection>();
let db = dbm.0.lock().await.get().unwrap();
let (sql, params) = Query::select()
.from(WebsocketRequestIden::Table)
.cond_where(Expr::col(WebsocketRequestIden::WorkspaceId).eq(workspace_id))
.column(Asterisk)
.build_rusqlite(SqliteQueryBuilder);
let mut stmt = db.prepare(sql.as_str())?;
let items = stmt.query_map(&*params.as_params(), |row| row.try_into())?;
Ok(items.map(|v| v.unwrap()).collect())
}
pub async fn list_websocket_events<R: Runtime>(
mgr: &impl Manager<R>,
connection_id: &str,
) -> Result<Vec<WebsocketEvent>> {
let dbm = &*mgr.state::<SqliteConnection>();
let db = dbm.0.lock().await.get().unwrap();
let (sql, params) = Query::select()
.from(WebsocketEventIden::Table)
.cond_where(Expr::col(WebsocketEventIden::ConnectionId).eq(connection_id))
.column(Asterisk)
.build_rusqlite(SqliteQueryBuilder);
let mut stmt = db.prepare(sql.as_str())?;
let items = stmt.query_map(&*params.as_params(), |row| row.try_into())?;
Ok(items.map(|v| v.unwrap()).collect())
}
pub async fn upsert_cookie_jar<R: Runtime>(
window: &WebviewWindow<R>,
cookie_jar: &CookieJar,
@@ -1676,7 +2045,7 @@ pub async fn create_http_response<R: Runtime>(
update_source: &UpdateSource,
) -> Result<HttpResponse> {
let responses = list_http_responses_for_request(window, request_id, None).await?;
for response in responses.iter().skip(MAX_HTTP_RESPONSES_PER_REQUEST - 1) {
for response in responses.iter().skip(MAX_HISTORY_ITEMS - 1) {
debug!("Deleting old response {}", response.id);
delete_http_response(window, response.id.as_str(), update_source).await?;
}
@@ -2170,6 +2539,7 @@ pub struct BatchUpsertResult {
pub folders: Vec<Folder>,
pub http_requests: Vec<HttpRequest>,
pub grpc_requests: Vec<GrpcRequest>,
pub websocket_requests: Vec<WebsocketRequest>,
}
pub async fn batch_upsert<R: Runtime>(
@@ -2179,6 +2549,7 @@ pub async fn batch_upsert<R: Runtime>(
folders: Vec<Folder>,
http_requests: Vec<HttpRequest>,
grpc_requests: Vec<GrpcRequest>,
websocket_requests: Vec<WebsocketRequest>,
update_source: &UpdateSource,
) -> Result<BatchUpsertResult> {
let mut imported_resources = BatchUpsertResult::default();
@@ -2246,6 +2617,14 @@ pub async fn batch_upsert<R: Runtime>(
info!("Imported {} grpc_requests", imported_resources.grpc_requests.len());
}
if websocket_requests.len() > 0 {
for v in websocket_requests {
let x = upsert_websocket_request(&window, v, update_source).await?;
imported_resources.websocket_requests.push(x.clone());
}
info!("Imported {} websocket_requests", imported_resources.websocket_requests.len());
}
Ok(imported_resources)
}
@@ -2264,6 +2643,7 @@ pub async fn get_workspace_export_resources<R: Runtime>(
folders: Vec::new(),
http_requests: Vec::new(),
grpc_requests: Vec::new(),
websocket_requests: Vec::new(),
},
};
@@ -2273,6 +2653,7 @@ pub async fn get_workspace_export_resources<R: Runtime>(
data.resources.folders.append(&mut list_folders(mgr, workspace_id).await?);
data.resources.http_requests.append(&mut list_http_requests(mgr, workspace_id).await?);
data.resources.grpc_requests.append(&mut list_grpc_requests(mgr, workspace_id).await?);
data.resources.websocket_requests.append(&mut list_websocket_requests(mgr, workspace_id).await?);
}
// Nuke environments if we don't want them

View File

@@ -0,0 +1,34 @@
use std::collections::HashMap;
use crate::models::{Environment, EnvironmentVariable};
pub fn make_vars_hashmap(
base_environment: &Environment,
environment: Option<&Environment>,
) -> HashMap<String, String> {
let mut variables = HashMap::new();
variables = add_variable_to_map(variables, &base_environment.variables);
if let Some(e) = environment {
variables = add_variable_to_map(variables, &e.variables);
}
variables
}
fn add_variable_to_map(
m: HashMap<String, String>,
variables: &Vec<EnvironmentVariable>,
) -> HashMap<String, String> {
let mut map = m.clone();
for variable in variables {
if !variable.enabled || variable.value.is_empty() {
continue;
}
let name = variable.name.as_str();
let value = variable.value.as_str();
map.insert(name.into(), value.into());
}
map
}

View File

@@ -10,7 +10,7 @@ futures-util = "0.3.30"
log = "0.4.21"
md5 = "0.7.0"
path-slash = "0.2.1"
rand = "0.8.5"
rand = "0.9.0"
regex = "1.10.6"
serde = { version = "1.0.198", features = ["derive"] }
serde_json = "1.0.113"
@@ -21,3 +21,4 @@ tokio = { version = "1.42.0", features = ["macros", "rt-multi-thread", "process"
tokio-tungstenite = "0.26.1"
ts-rs = { workspace = true, features = ["import-esm"] }
yaak-models = { workspace = true }
yaak-templates = { workspace = true }

View File

@@ -5,6 +5,7 @@ import type { GrpcRequest } from "./gen_models.js";
import type { HttpRequest } from "./gen_models.js";
import type { HttpResponse } from "./gen_models.js";
import type { JsonValue } from "./serde_json/JsonValue.js";
import type { WebsocketRequest } from "./gen_models.js";
import type { Workspace } from "./gen_models.js";
export type BootRequest = { dir: string, watch: boolean, };
@@ -339,7 +340,7 @@ export type Icon = "alert_triangle" | "check" | "check_circle" | "chevron_down"
export type ImportRequest = { content: string, };
export type ImportResources = { workspaces: Array<Workspace>, environments: Array<Environment>, folders: Array<Folder>, httpRequests: Array<HttpRequest>, grpcRequests: Array<GrpcRequest>, };
export type ImportResources = { workspaces: Array<Workspace>, environments: Array<Environment>, folders: Array<Folder>, httpRequests: Array<HttpRequest>, grpcRequests: Array<GrpcRequest>, websocketRequests: Array<WebsocketRequest>, };
export type ImportResponse = { resources: ImportResources, };

View File

@@ -22,4 +22,6 @@ export type HttpResponseState = "initialized" | "connected" | "closed";
export type HttpUrlParameter = { enabled?: boolean, name: string, value: string, id?: string, };
export type WebsocketRequest = { model: "websocket_request", id: string, createdAt: string, updatedAt: string, workspaceId: string, folderId: string | null, authentication: Record<string, any>, authenticationType: string | null, description: string, headers: Array<HttpRequestHeader>, message: string, name: string, sortPriority: number, url: string, urlParameters: Array<HttpUrlParameter>, };
export type Workspace = { model: "workspace", id: string, createdAt: string, updatedAt: string, name: string, description: string, settingValidateCertificates: boolean, settingFollowRedirects: boolean, settingRequestTimeout: number, };

View File

@@ -39,10 +39,4 @@ pub enum Error {
UnknownEventErr,
}
impl Into<String> for Error {
fn into(self) -> String {
todo!()
}
}
pub type Result<T> = std::result::Result<T, Error>;

View File

@@ -3,7 +3,7 @@ use std::collections::HashMap;
use tauri::{Runtime, WebviewWindow};
use ts_rs::TS;
use yaak_models::models::{Environment, Folder, GrpcRequest, HttpRequest, HttpResponse, Workspace};
use yaak_models::models::{Environment, Folder, GrpcRequest, HttpRequest, HttpResponse, WebsocketRequest, Workspace};
#[derive(Debug, Clone, Serialize, Deserialize, TS)]
#[serde(rename_all = "camelCase")]
@@ -873,6 +873,7 @@ pub struct ImportResources {
pub folders: Vec<Folder>,
pub http_requests: Vec<HttpRequest>,
pub grpc_requests: Vec<GrpcRequest>,
pub websocket_requests: Vec<WebsocketRequest>,
}
#[derive(Debug, Clone, Default, Serialize, Deserialize, TS)]

View File

@@ -7,8 +7,9 @@ use tauri::{Manager, RunEvent, Runtime, State};
pub mod error;
pub mod events;
pub mod manager;
mod nodejs;
pub mod plugin_handle;
pub mod template_callback;
mod nodejs;
mod server_ws;
mod util;

View File

@@ -53,8 +53,8 @@ impl PluginManager {
PluginRuntimeServerWebsocket::new(events_tx, client_disconnect_tx, client_connect_tx);
let plugin_manager = PluginManager {
plugins: Arc::new(Mutex::new(Vec::new())),
subscribers: Arc::new(Mutex::new(HashMap::new())),
plugins: Default::default(),
subscribers: Default::default(),
ws_service: Arc::new(ws_service.clone()),
kill_tx: kill_server_tx,
};

View File

@@ -1,7 +1,7 @@
use crate::events::{FormInput, RenderPurpose, WindowContext};
use crate::manager::PluginManager;
use std::collections::HashMap;
use tauri::{AppHandle, Manager, Runtime};
use yaak_plugins::events::{FormInput, RenderPurpose, WindowContext};
use yaak_plugins::manager::PluginManager;
use yaak_templates::TemplateCallback;
#[derive(Clone)]

View File

@@ -1,5 +1,6 @@
use rand::distributions::{Alphanumeric, DistString};
use rand::distr::Alphanumeric;
use rand::Rng;
pub fn gen_id() -> String {
Alphanumeric.sample_string(&mut rand::thread_rng(), 5)
rand::rng().sample_iter(&Alphanumeric).take(5).map(char::from).collect()
}

View File

@@ -21,4 +21,4 @@ tokio = { version = "1.42.0", features = ["fs", "sync", "macros"] }
notify = "7.0.0"
[build-dependencies]
tauri-plugin = { version = "2.0.3", features = ["build"] }
tauri-plugin = { workspace = true, features = ["build"] }

View File

@@ -16,8 +16,10 @@ export type HttpRequestHeader = { enabled?: boolean, name: string, value: string
export type HttpUrlParameter = { enabled?: boolean, name: string, value: string, id?: string, };
export type SyncModel = { "type": "workspace" } & Workspace | { "type": "environment" } & Environment | { "type": "folder" } & Folder | { "type": "http_request" } & HttpRequest | { "type": "grpc_request" } & GrpcRequest;
export type SyncModel = { "type": "workspace" } & Workspace | { "type": "environment" } & Environment | { "type": "folder" } & Folder | { "type": "http_request" } & HttpRequest | { "type": "grpc_request" } & GrpcRequest | { "type": "websocket_request" } & WebsocketRequest;
export type SyncState = { model: "sync_state", id: string, workspaceId: string, createdAt: string, updatedAt: string, flushedAt: string, modelId: string, checksum: string, relPath: string, syncDir: string, };
export type WebsocketRequest = { model: "websocket_request", id: string, createdAt: string, updatedAt: string, workspaceId: string, folderId: string | null, authentication: Record<string, any>, authenticationType: string | null, description: string, headers: Array<HttpRequestHeader>, message: string, name: string, sortPriority: number, url: string, urlParameters: Array<HttpUrlParameter>, };
export type Workspace = { model: "workspace", id: string, createdAt: string, updatedAt: string, name: string, description: string, settingValidateCertificates: boolean, settingFollowRedirects: boolean, settingRequestTimeout: number, };

View File

@@ -6,7 +6,9 @@ use sha1::{Digest, Sha1};
use std::path::Path;
use tokio::fs;
use ts_rs::TS;
use yaak_models::models::{AnyModel, Environment, Folder, GrpcRequest, HttpRequest, Workspace};
use yaak_models::models::{
AnyModel, Environment, Folder, GrpcRequest, HttpRequest, WebsocketRequest, Workspace,
};
#[derive(Debug, Clone, Serialize, Deserialize, TS)]
#[serde(rename_all = "snake_case", tag = "type")]
@@ -17,6 +19,7 @@ pub enum SyncModel {
Folder(Folder),
HttpRequest(HttpRequest),
GrpcRequest(GrpcRequest),
WebsocketRequest(WebsocketRequest),
}
impl SyncModel {
@@ -62,6 +65,7 @@ impl SyncModel {
SyncModel::Folder(m) => m.id,
SyncModel::HttpRequest(m) => m.id,
SyncModel::GrpcRequest(m) => m.id,
SyncModel::WebsocketRequest(m) => m.id,
}
}
@@ -72,6 +76,7 @@ impl SyncModel {
SyncModel::Folder(m) => m.workspace_id,
SyncModel::HttpRequest(m) => m.workspace_id,
SyncModel::GrpcRequest(m) => m.workspace_id,
SyncModel::WebsocketRequest(m) => m.workspace_id,
}
}
@@ -82,6 +87,7 @@ impl SyncModel {
SyncModel::Folder(m) => m.updated_at,
SyncModel::HttpRequest(m) => m.updated_at,
SyncModel::GrpcRequest(m) => m.updated_at,
SyncModel::WebsocketRequest(m) => m.updated_at,
}
}
}
@@ -95,15 +101,20 @@ impl TryFrom<AnyModel> for SyncModel {
AnyModel::Folder(m) => SyncModel::Folder(m),
AnyModel::GrpcRequest(m) => SyncModel::GrpcRequest(m),
AnyModel::HttpRequest(m) => SyncModel::HttpRequest(m),
AnyModel::WebsocketRequest(m) => SyncModel::WebsocketRequest(m),
AnyModel::Workspace(m) => SyncModel::Workspace(m),
AnyModel::WorkspaceMeta(m) => return Err(UnknownModel(m.model)),
// Non-sync models
AnyModel::CookieJar(m) => return Err(UnknownModel(m.model)),
AnyModel::GrpcConnection(m) => return Err(UnknownModel(m.model)),
AnyModel::GrpcEvent(m) => return Err(UnknownModel(m.model)),
AnyModel::HttpResponse(m) => return Err(UnknownModel(m.model)),
AnyModel::KeyValue(m) => return Err(UnknownModel(m.model)),
AnyModel::Plugin(m) => return Err(UnknownModel(m.model)),
AnyModel::Settings(m) => return Err(UnknownModel(m.model)),
AnyModel::KeyValue(m) => return Err(UnknownModel(m.model)),
AnyModel::WebsocketConnection(m) => return Err(UnknownModel(m.model)),
AnyModel::WebsocketEvent(m) => return Err(UnknownModel(m.model)),
AnyModel::WorkspaceMeta(m) => return Err(UnknownModel(m.model)),
};
Ok(m)
}

View File

@@ -15,8 +15,9 @@ use ts_rs::TS;
use yaak_models::models::{SyncState, WorkspaceMeta};
use yaak_models::queries::{
batch_upsert, delete_environment, delete_folder, delete_grpc_request, delete_http_request,
delete_sync_state, delete_workspace, get_workspace_export_resources, get_workspace_meta,
list_sync_states_for_workspace, upsert_sync_state, upsert_workspace_meta, UpdateSource,
delete_sync_state, delete_websocket_request, delete_workspace, get_workspace_export_resources,
get_workspace_meta, list_sync_states_for_workspace, upsert_sync_state, upsert_workspace_meta,
UpdateSource,
};
#[derive(Debug, Clone, Serialize, Deserialize, TS)]
@@ -296,6 +297,9 @@ async fn workspace_models<R: Runtime>(
for m in resources.grpc_requests {
sync_models.push(SyncModel::GrpcRequest(m));
}
for m in resources.websocket_requests {
sync_models.push(SyncModel::WebsocketRequest(m));
}
Ok(sync_models)
}
@@ -320,6 +324,7 @@ pub(crate) async fn apply_sync_ops<R: Runtime>(
let mut folders_to_upsert = Vec::new();
let mut http_requests_to_upsert = Vec::new();
let mut grpc_requests_to_upsert = Vec::new();
let mut websocket_requests_to_upsert = Vec::new();
for op in sync_ops {
// Only apply things if workspace ID matches
@@ -381,6 +386,7 @@ pub(crate) async fn apply_sync_ops<R: Runtime>(
SyncModel::Folder(m) => folders_to_upsert.push(m),
SyncModel::HttpRequest(m) => http_requests_to_upsert.push(m),
SyncModel::GrpcRequest(m) => grpc_requests_to_upsert.push(m),
SyncModel::WebsocketRequest(m) => websocket_requests_to_upsert.push(m),
};
SyncStateOp::Create {
model_id,
@@ -397,6 +403,7 @@ pub(crate) async fn apply_sync_ops<R: Runtime>(
SyncModel::Folder(m) => folders_to_upsert.push(m),
SyncModel::HttpRequest(m) => http_requests_to_upsert.push(m),
SyncModel::GrpcRequest(m) => grpc_requests_to_upsert.push(m),
SyncModel::WebsocketRequest(m) => websocket_requests_to_upsert.push(m),
}
SyncStateOp::Update {
state: state.to_owned(),
@@ -420,6 +427,7 @@ pub(crate) async fn apply_sync_ops<R: Runtime>(
folders_to_upsert,
http_requests_to_upsert,
grpc_requests_to_upsert,
websocket_requests_to_upsert,
&UpdateSource::Sync,
)
.await?;
@@ -543,6 +551,9 @@ async fn delete_model<R: Runtime>(window: &WebviewWindow<R>, model: &SyncModel)
SyncModel::GrpcRequest(m) => {
delete_grpc_request(window, m.id.as_str(), &UpdateSource::Sync).await?;
}
SyncModel::WebsocketRequest(m) => {
delete_websocket_request(window, m.id.as_str(), &UpdateSource::Sync).await?;
}
};
Ok(())
}

View File

@@ -9,3 +9,4 @@ log = "0.4.22"
serde = { version = "1.0.208", features = ["derive"] }
ts-rs = { version = "10.0.0" }
tokio = { version = "1.39.3", features = ["macros", "rt"] }
serde_json = "1.0.132"

View File

@@ -142,7 +142,7 @@ pub fn format_json(text: &str, tab: &str) -> String {
}
#[cfg(test)]
mod test {
mod tests {
use crate::format::format_json;
#[test]

View File

@@ -1,5 +1,6 @@
use crate::{FnArg, Parser, Token, Tokens, Val};
use log::warn;
use serde_json::json;
use std::collections::HashMap;
use std::future::Future;
@@ -11,6 +12,33 @@ pub trait TemplateCallback {
) -> impl Future<Output = Result<String, String>> + Send;
}
pub async fn render_json_value_raw<T: TemplateCallback>(
v: serde_json::Value,
vars: &HashMap<String, String>,
cb: &T,
) -> serde_json::Value {
match v {
serde_json::Value::String(s) => json!(parse_and_render(&s, vars, cb).await),
serde_json::Value::Array(a) => {
let mut new_a = Vec::new();
for v in a {
new_a.push(Box::pin(render_json_value_raw(v, vars, cb)).await)
}
json!(new_a)
}
serde_json::Value::Object(o) => {
let mut new_o = serde_json::Map::new();
for (k, v) in o {
let key = Box::pin(parse_and_render(&k, vars, cb)).await;
let value = Box::pin(render_json_value_raw(v, vars, cb)).await;
new_o.insert(key, value);
}
json!(new_o)
}
v => v,
}
}
pub async fn parse_and_render<T: TemplateCallback>(
template: &str,
vars: &HashMap<String, String>,
@@ -90,7 +118,7 @@ async fn render_tag<T: TemplateCallback>(
}
#[cfg(test)]
mod tests {
mod parse_and_render_tests {
use crate::renderer::TemplateCallback;
use crate::*;
use std::collections::HashMap;
@@ -218,3 +246,79 @@ mod tests {
assert_eq!(parse_and_render(template, &vars, &CB {}).await, result.to_string());
}
}
#[cfg(test)]
mod render_json_value_raw_tests {
use serde_json::json;
use std::collections::HashMap;
use crate::{render_json_value_raw, TemplateCallback};
struct EmptyCB {}
impl TemplateCallback for EmptyCB {
async fn run(
&self,
_fn_name: &str,
_args: HashMap<String, String>,
) -> Result<String, String> {
todo!()
}
}
#[tokio::test]
async fn render_json_value_string() {
let v = json!("${[a]}");
let mut vars = HashMap::new();
vars.insert("a".to_string(), "aaa".to_string());
let result = render_json_value_raw(v, &vars, &EmptyCB {}).await;
assert_eq!(result, json!("aaa"))
}
#[tokio::test]
async fn render_json_value_array() {
let v = json!(["${[a]}", "${[a]}"]);
let mut vars = HashMap::new();
vars.insert("a".to_string(), "aaa".to_string());
let result = render_json_value_raw(v, &vars, &EmptyCB {}).await;
assert_eq!(result, json!(["aaa", "aaa"]))
}
#[tokio::test]
async fn render_json_value_object() {
let v = json!({"${[a]}": "${[a]}"});
let mut vars = HashMap::new();
vars.insert("a".to_string(), "aaa".to_string());
let result = render_json_value_raw(v, &vars, &EmptyCB {}).await;
assert_eq!(result, json!({"aaa": "aaa"}))
}
#[tokio::test]
async fn render_json_value_nested() {
let v = json!([
123,
{"${[a]}": "${[a]}"},
null,
"${[a]}",
false,
{"x": ["${[a]}"]}
]);
let mut vars = HashMap::new();
vars.insert("a".to_string(), "aaa".to_string());
let result = render_json_value_raw(v, &vars, &EmptyCB {}).await;
assert_eq!(
result,
json!([
123,
{"aaa": "aaa"},
null,
"aaa",
false,
{"x": ["aaa"]}
])
)
}
}

View File

@@ -0,0 +1,26 @@
[package]
name = "yaak-ws"
links = "yaak-ws"
version = "0.1.0"
edition = "2021"
publish = false
[dependencies]
futures-util = "0.3.31"
log = "0.4.20"
md5 = "0.7.0"
rustls = { version = "0.23.21", default-features = false, features = ["custom-provider", "ring"] }
rustls-platform-verifier = "0.5.0"
serde = { version = "1.0.217", features = ["derive"] }
tauri = { workspace = true }
thiserror = "2.0.11"
tokio = { version = "1.0", default-features = false, features = ["macros", "time", "test-util"] }
tokio-tungstenite = { version = "0.26.1", default-features = false, features = ["rustls-tls-native-roots", "connect"] }
yaak-models = { workspace = true }
yaak-plugins = { workspace = true }
yaak-templates = { workspace = true }
serde_json = "1.0.132"
chrono = "0.4.38"
[build-dependencies]
tauri-plugin = { workspace = true, features = ["build"] }

View File

@@ -0,0 +1,17 @@
use tauri_plugin;
const COMMANDS: &[&str] = &[
"close",
"connect",
"delete_connection",
"delete_connections",
"delete_request",
"list_connections",
"list_events",
"list_requests",
"send",
"upsert_request",
];
fn main() {
tauri_plugin::Builder::new(COMMANDS).build();
}

View File

@@ -0,0 +1,77 @@
import { invoke } from '@tauri-apps/api/core';
import { WebsocketConnection, WebsocketEvent, WebsocketRequest } from '@yaakapp-internal/models';
export function upsertWebsocketRequest(
request: WebsocketRequest | Partial<Omit<WebsocketRequest, 'id'>>,
) {
return invoke('plugin:yaak-ws|upsert_request', {
request,
}) as Promise<WebsocketRequest>;
}
export function deleteWebsocketRequest(requestId: string) {
return invoke('plugin:yaak-ws|delete_request', {
requestId,
});
}
export function deleteWebsocketConnection(connectionId: string) {
return invoke('plugin:yaak-ws|delete_connection', {
connectionId,
});
}
export function deleteWebsocketConnections(requestId: string) {
return invoke('plugin:yaak-ws|delete_connections', {
requestId,
});
}
export function listWebsocketRequests({ workspaceId }: { workspaceId: string }) {
return invoke('plugin:yaak-ws|list_requests', { workspaceId }) as Promise<WebsocketRequest[]>;
}
export function listWebsocketEvents({ connectionId }: { connectionId: string }) {
return invoke('plugin:yaak-ws|list_events', { connectionId }) as Promise<WebsocketEvent[]>;
}
export function listWebsocketConnections({ workspaceId }: { workspaceId: string }) {
return invoke('plugin:yaak-ws|list_connections', { workspaceId }) as Promise<
WebsocketConnection[]
>;
}
export function connectWebsocket({
requestId,
environmentId,
cookieJarId,
}: {
requestId: string;
environmentId: string | null;
cookieJarId: string | null;
}) {
return invoke('plugin:yaak-ws|connect', {
requestId,
environmentId,
cookieJarId,
}) as Promise<WebsocketConnection>;
}
export function closeWebsocket({ connectionId }: { connectionId: string }) {
return invoke('plugin:yaak-ws|close', {
connectionId,
});
}
export function sendWebsocket({
connectionId,
environmentId,
}: {
connectionId: string;
environmentId: string | null;
}) {
return invoke('plugin:yaak-ws|send', {
connectionId,
environmentId,
});
}

View File

@@ -0,0 +1,6 @@
{
"name": "@yaakapp-internal/ws",
"private": true,
"version": "1.0.0",
"main": "index.ts"
}

View File

@@ -0,0 +1,13 @@
# Automatically generated - DO NOT EDIT!
"$schema" = "../../schemas/schema.json"
[[permission]]
identifier = "allow-cancel"
description = "Enables the cancel command without any pre-configured scope."
commands.allow = ["cancel"]
[[permission]]
identifier = "deny-cancel"
description = "Denies the cancel command without any pre-configured scope."
commands.deny = ["cancel"]

View File

@@ -0,0 +1,13 @@
# Automatically generated - DO NOT EDIT!
"$schema" = "../../schemas/schema.json"
[[permission]]
identifier = "allow-close"
description = "Enables the close command without any pre-configured scope."
commands.allow = ["close"]
[[permission]]
identifier = "deny-close"
description = "Denies the close command without any pre-configured scope."
commands.deny = ["close"]

View File

@@ -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"]

View File

@@ -0,0 +1,13 @@
# Automatically generated - DO NOT EDIT!
"$schema" = "../../schemas/schema.json"
[[permission]]
identifier = "allow-delete-connection"
description = "Enables the delete_connection command without any pre-configured scope."
commands.allow = ["delete_connection"]
[[permission]]
identifier = "deny-delete-connection"
description = "Denies the delete_connection command without any pre-configured scope."
commands.deny = ["delete_connection"]

View File

@@ -0,0 +1,13 @@
# Automatically generated - DO NOT EDIT!
"$schema" = "../../schemas/schema.json"
[[permission]]
identifier = "allow-delete-connections"
description = "Enables the delete_connections command without any pre-configured scope."
commands.allow = ["delete_connections"]
[[permission]]
identifier = "deny-delete-connections"
description = "Denies the delete_connections command without any pre-configured scope."
commands.deny = ["delete_connections"]

View File

@@ -0,0 +1,13 @@
# Automatically generated - DO NOT EDIT!
"$schema" = "../../schemas/schema.json"
[[permission]]
identifier = "allow-delete-request"
description = "Enables the delete_request command without any pre-configured scope."
commands.allow = ["delete_request"]
[[permission]]
identifier = "deny-delete-request"
description = "Denies the delete_request command without any pre-configured scope."
commands.deny = ["delete_request"]

View File

@@ -0,0 +1,13 @@
# Automatically generated - DO NOT EDIT!
"$schema" = "../../schemas/schema.json"
[[permission]]
identifier = "allow-list-connections"
description = "Enables the list_connections command without any pre-configured scope."
commands.allow = ["list_connections"]
[[permission]]
identifier = "deny-list-connections"
description = "Denies the list_connections command without any pre-configured scope."
commands.deny = ["list_connections"]

View File

@@ -0,0 +1,13 @@
# Automatically generated - DO NOT EDIT!
"$schema" = "../../schemas/schema.json"
[[permission]]
identifier = "allow-list-events"
description = "Enables the list_events command without any pre-configured scope."
commands.allow = ["list_events"]
[[permission]]
identifier = "deny-list-events"
description = "Denies the list_events command without any pre-configured scope."
commands.deny = ["list_events"]

View File

@@ -0,0 +1,13 @@
# Automatically generated - DO NOT EDIT!
"$schema" = "../../schemas/schema.json"
[[permission]]
identifier = "allow-list-requests"
description = "Enables the list_requests command without any pre-configured scope."
commands.allow = ["list_requests"]
[[permission]]
identifier = "deny-list-requests"
description = "Denies the list_requests command without any pre-configured scope."
commands.deny = ["list_requests"]

View File

@@ -0,0 +1,13 @@
# Automatically generated - DO NOT EDIT!
"$schema" = "../../schemas/schema.json"
[[permission]]
identifier = "allow-list-websocket-connections"
description = "Enables the list_websocket_connections command without any pre-configured scope."
commands.allow = ["list_websocket_connections"]
[[permission]]
identifier = "deny-list-websocket-connections"
description = "Denies the list_websocket_connections command without any pre-configured scope."
commands.deny = ["list_websocket_connections"]

View File

@@ -0,0 +1,13 @@
# Automatically generated - DO NOT EDIT!
"$schema" = "../../schemas/schema.json"
[[permission]]
identifier = "allow-list-websocket-requests"
description = "Enables the list_websocket_requests command without any pre-configured scope."
commands.allow = ["list_websocket_requests"]
[[permission]]
identifier = "deny-list-websocket-requests"
description = "Denies the list_websocket_requests command without any pre-configured scope."
commands.deny = ["list_websocket_requests"]

View File

@@ -0,0 +1,13 @@
# Automatically generated - DO NOT EDIT!
"$schema" = "../../schemas/schema.json"
[[permission]]
identifier = "allow-send"
description = "Enables the send command without any pre-configured scope."
commands.allow = ["send"]
[[permission]]
identifier = "deny-send"
description = "Denies the send command without any pre-configured scope."
commands.deny = ["send"]

View File

@@ -0,0 +1,13 @@
# Automatically generated - DO NOT EDIT!
"$schema" = "../../schemas/schema.json"
[[permission]]
identifier = "allow-upsert-request"
description = "Enables the upsert_request command without any pre-configured scope."
commands.allow = ["upsert_request"]
[[permission]]
identifier = "deny-upsert-request"
description = "Denies the upsert_request command without any pre-configured scope."
commands.deny = ["upsert_request"]

View File

@@ -0,0 +1,13 @@
# Automatically generated - DO NOT EDIT!
"$schema" = "../../schemas/schema.json"
[[permission]]
identifier = "allow-upsert-websocket-request"
description = "Enables the upsert_websocket_request command without any pre-configured scope."
commands.allow = ["upsert_websocket_request"]
[[permission]]
identifier = "deny-upsert-websocket-request"
description = "Denies the upsert_websocket_request command without any pre-configured scope."
commands.deny = ["upsert_websocket_request"]

View File

@@ -0,0 +1,388 @@
## Default Permission
Default permissions for the plugin
- `allow-close`
- `allow-connect`
- `allow-delete-connection`
- `allow-delete-connections`
- `allow-delete-request`
- `allow-list-connections`
- `allow-list-events`
- `allow-list-requests`
- `allow-send`
- `allow-upsert-request`
## Permission Table
<table>
<tr>
<th>Identifier</th>
<th>Description</th>
</tr>
<tr>
<td>
`yaak-ws:allow-cancel`
</td>
<td>
Enables the cancel command without any pre-configured scope.
</td>
</tr>
<tr>
<td>
`yaak-ws:deny-cancel`
</td>
<td>
Denies the cancel command without any pre-configured scope.
</td>
</tr>
<tr>
<td>
`yaak-ws:allow-close`
</td>
<td>
Enables the close command without any pre-configured scope.
</td>
</tr>
<tr>
<td>
`yaak-ws:deny-close`
</td>
<td>
Denies the close command without any pre-configured scope.
</td>
</tr>
<tr>
<td>
`yaak-ws:allow-connect`
</td>
<td>
Enables the connect command without any pre-configured scope.
</td>
</tr>
<tr>
<td>
`yaak-ws:deny-connect`
</td>
<td>
Denies the connect command without any pre-configured scope.
</td>
</tr>
<tr>
<td>
`yaak-ws:allow-delete-connection`
</td>
<td>
Enables the delete_connection command without any pre-configured scope.
</td>
</tr>
<tr>
<td>
`yaak-ws:deny-delete-connection`
</td>
<td>
Denies the delete_connection command without any pre-configured scope.
</td>
</tr>
<tr>
<td>
`yaak-ws:allow-delete-connections`
</td>
<td>
Enables the delete_connections command without any pre-configured scope.
</td>
</tr>
<tr>
<td>
`yaak-ws:deny-delete-connections`
</td>
<td>
Denies the delete_connections command without any pre-configured scope.
</td>
</tr>
<tr>
<td>
`yaak-ws:allow-delete-request`
</td>
<td>
Enables the delete_request command without any pre-configured scope.
</td>
</tr>
<tr>
<td>
`yaak-ws:deny-delete-request`
</td>
<td>
Denies the delete_request command without any pre-configured scope.
</td>
</tr>
<tr>
<td>
`yaak-ws:allow-list-connections`
</td>
<td>
Enables the list_connections command without any pre-configured scope.
</td>
</tr>
<tr>
<td>
`yaak-ws:deny-list-connections`
</td>
<td>
Denies the list_connections command without any pre-configured scope.
</td>
</tr>
<tr>
<td>
`yaak-ws:allow-list-events`
</td>
<td>
Enables the list_events command without any pre-configured scope.
</td>
</tr>
<tr>
<td>
`yaak-ws:deny-list-events`
</td>
<td>
Denies the list_events command without any pre-configured scope.
</td>
</tr>
<tr>
<td>
`yaak-ws:allow-list-requests`
</td>
<td>
Enables the list_requests command without any pre-configured scope.
</td>
</tr>
<tr>
<td>
`yaak-ws:deny-list-requests`
</td>
<td>
Denies the list_requests command without any pre-configured scope.
</td>
</tr>
<tr>
<td>
`yaak-ws:allow-list-websocket-connections`
</td>
<td>
Enables the list_websocket_connections command without any pre-configured scope.
</td>
</tr>
<tr>
<td>
`yaak-ws:deny-list-websocket-connections`
</td>
<td>
Denies the list_websocket_connections command without any pre-configured scope.
</td>
</tr>
<tr>
<td>
`yaak-ws:allow-list-websocket-requests`
</td>
<td>
Enables the list_websocket_requests command without any pre-configured scope.
</td>
</tr>
<tr>
<td>
`yaak-ws:deny-list-websocket-requests`
</td>
<td>
Denies the list_websocket_requests command without any pre-configured scope.
</td>
</tr>
<tr>
<td>
`yaak-ws:allow-send`
</td>
<td>
Enables the send command without any pre-configured scope.
</td>
</tr>
<tr>
<td>
`yaak-ws:deny-send`
</td>
<td>
Denies the send command without any pre-configured scope.
</td>
</tr>
<tr>
<td>
`yaak-ws:allow-upsert-request`
</td>
<td>
Enables the upsert_request command without any pre-configured scope.
</td>
</tr>
<tr>
<td>
`yaak-ws:deny-upsert-request`
</td>
<td>
Denies the upsert_request command without any pre-configured scope.
</td>
</tr>
<tr>
<td>
`yaak-ws:allow-upsert-websocket-request`
</td>
<td>
Enables the upsert_websocket_request command without any pre-configured scope.
</td>
</tr>
<tr>
<td>
`yaak-ws:deny-upsert-websocket-request`
</td>
<td>
Denies the upsert_websocket_request command without any pre-configured scope.
</td>
</tr>
</table>

View File

@@ -0,0 +1,14 @@
[default]
description = "Default permissions for the plugin"
permissions = [
"allow-close",
"allow-connect",
"allow-delete-connection",
"allow-delete-connections",
"allow-delete-request",
"allow-list-connections",
"allow-list-events",
"allow-list-requests",
"allow-send",
"allow-upsert-request",
]

View File

@@ -0,0 +1,445 @@
{
"$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 cancel command without any pre-configured scope.",
"type": "string",
"const": "allow-cancel"
},
{
"description": "Denies the cancel command without any pre-configured scope.",
"type": "string",
"const": "deny-cancel"
},
{
"description": "Enables the close command without any pre-configured scope.",
"type": "string",
"const": "allow-close"
},
{
"description": "Denies the close command without any pre-configured scope.",
"type": "string",
"const": "deny-close"
},
{
"description": "Enables the connect command without any pre-configured scope.",
"type": "string",
"const": "allow-connect"
},
{
"description": "Denies the connect command without any pre-configured scope.",
"type": "string",
"const": "deny-connect"
},
{
"description": "Enables the delete_connection command without any pre-configured scope.",
"type": "string",
"const": "allow-delete-connection"
},
{
"description": "Denies the delete_connection command without any pre-configured scope.",
"type": "string",
"const": "deny-delete-connection"
},
{
"description": "Enables the delete_connections command without any pre-configured scope.",
"type": "string",
"const": "allow-delete-connections"
},
{
"description": "Denies the delete_connections command without any pre-configured scope.",
"type": "string",
"const": "deny-delete-connections"
},
{
"description": "Enables the delete_request command without any pre-configured scope.",
"type": "string",
"const": "allow-delete-request"
},
{
"description": "Denies the delete_request command without any pre-configured scope.",
"type": "string",
"const": "deny-delete-request"
},
{
"description": "Enables the list_connections command without any pre-configured scope.",
"type": "string",
"const": "allow-list-connections"
},
{
"description": "Denies the list_connections command without any pre-configured scope.",
"type": "string",
"const": "deny-list-connections"
},
{
"description": "Enables the list_events command without any pre-configured scope.",
"type": "string",
"const": "allow-list-events"
},
{
"description": "Denies the list_events command without any pre-configured scope.",
"type": "string",
"const": "deny-list-events"
},
{
"description": "Enables the list_requests command without any pre-configured scope.",
"type": "string",
"const": "allow-list-requests"
},
{
"description": "Denies the list_requests command without any pre-configured scope.",
"type": "string",
"const": "deny-list-requests"
},
{
"description": "Enables the list_websocket_connections command without any pre-configured scope.",
"type": "string",
"const": "allow-list-websocket-connections"
},
{
"description": "Denies the list_websocket_connections command without any pre-configured scope.",
"type": "string",
"const": "deny-list-websocket-connections"
},
{
"description": "Enables the list_websocket_requests command without any pre-configured scope.",
"type": "string",
"const": "allow-list-websocket-requests"
},
{
"description": "Denies the list_websocket_requests command without any pre-configured scope.",
"type": "string",
"const": "deny-list-websocket-requests"
},
{
"description": "Enables the send command without any pre-configured scope.",
"type": "string",
"const": "allow-send"
},
{
"description": "Denies the send command without any pre-configured scope.",
"type": "string",
"const": "deny-send"
},
{
"description": "Enables the upsert_request command without any pre-configured scope.",
"type": "string",
"const": "allow-upsert-request"
},
{
"description": "Denies the upsert_request command without any pre-configured scope.",
"type": "string",
"const": "deny-upsert-request"
},
{
"description": "Enables the upsert_websocket_request command without any pre-configured scope.",
"type": "string",
"const": "allow-upsert-websocket-request"
},
{
"description": "Denies the upsert_websocket_request command without any pre-configured scope.",
"type": "string",
"const": "deny-upsert-websocket-request"
},
{
"description": "Default permissions for the plugin",
"type": "string",
"const": "default"
}
]
}
}
}

View File

@@ -0,0 +1,330 @@
use crate::error::Error::GenericError;
use crate::error::Result;
use crate::manager::WebsocketManager;
use crate::render::render_request;
use chrono::Utc;
use log::info;
use std::str::FromStr;
use tauri::http::{HeaderMap, HeaderName};
use tauri::{AppHandle, Manager, Runtime, State, WebviewWindow};
use tokio::sync::{mpsc, Mutex};
use tokio_tungstenite::tungstenite::http::HeaderValue;
use tokio_tungstenite::tungstenite::Message;
use yaak_models::models::{
HttpResponseHeader, WebsocketConnection, WebsocketConnectionState, WebsocketEvent,
WebsocketEventType, WebsocketRequest,
};
use yaak_models::queries;
use yaak_models::queries::{
get_base_environment, get_cookie_jar, get_environment, get_websocket_connection,
get_websocket_request, upsert_websocket_connection, upsert_websocket_event, UpdateSource,
};
use yaak_plugins::events::{
CallHttpAuthenticationRequest, HttpHeader, RenderPurpose, WindowContext,
};
use yaak_plugins::manager::PluginManager;
use yaak_plugins::template_callback::PluginTemplateCallback;
#[tauri::command]
pub(crate) async fn upsert_request<R: Runtime>(
request: WebsocketRequest,
w: WebviewWindow<R>,
) -> Result<WebsocketRequest> {
Ok(queries::upsert_websocket_request(&w, request, &UpdateSource::Window).await?)
}
#[tauri::command]
pub(crate) async fn delete_request<R: Runtime>(
request_id: &str,
w: WebviewWindow<R>,
) -> Result<WebsocketRequest> {
Ok(queries::delete_websocket_request(&w, request_id, &UpdateSource::Window).await?)
}
#[tauri::command]
pub(crate) async fn delete_connection<R: Runtime>(
connection_id: &str,
w: WebviewWindow<R>,
) -> Result<WebsocketConnection> {
Ok(queries::delete_websocket_connection(&w, connection_id, &UpdateSource::Window).await?)
}
#[tauri::command]
pub(crate) async fn delete_connections<R: Runtime>(
request_id: &str,
w: WebviewWindow<R>,
) -> Result<()> {
Ok(queries::delete_all_websocket_connections(&w, request_id, &UpdateSource::Window).await?)
}
#[tauri::command]
pub(crate) async fn list_events<R: Runtime>(
connection_id: &str,
app_handle: AppHandle<R>,
) -> Result<Vec<WebsocketEvent>> {
Ok(queries::list_websocket_events(&app_handle, connection_id).await?)
}
#[tauri::command]
pub(crate) async fn list_requests<R: Runtime>(
workspace_id: &str,
app_handle: AppHandle<R>,
) -> Result<Vec<WebsocketRequest>> {
Ok(queries::list_websocket_requests(&app_handle, workspace_id).await?)
}
#[tauri::command]
pub(crate) async fn list_connections<R: Runtime>(
workspace_id: &str,
app_handle: AppHandle<R>,
) -> Result<Vec<WebsocketConnection>> {
Ok(queries::list_websocket_connections_for_workspace(&app_handle, workspace_id).await?)
}
#[tauri::command]
pub(crate) async fn send<R: Runtime>(
connection_id: &str,
environment_id: Option<&str>,
window: WebviewWindow<R>,
ws_manager: State<'_, Mutex<WebsocketManager>>,
) -> Result<WebsocketConnection> {
let connection = get_websocket_connection(&window, connection_id).await?;
let unrendered_request = get_websocket_request(&window, &connection.request_id)
.await?
.ok_or(GenericError("WebSocket Request not found".to_string()))?;
let environment = match environment_id {
Some(id) => Some(get_environment(&window, id).await?),
None => None,
};
let base_environment = get_base_environment(&window, &unrendered_request.workspace_id).await?;
let request = render_request(
&unrendered_request,
&base_environment,
environment.as_ref(),
&PluginTemplateCallback::new(
window.app_handle(),
&WindowContext::from_window(&window),
RenderPurpose::Send,
),
)
.await;
let mut ws_manager = ws_manager.lock().await;
ws_manager.send(&connection.id, Message::Text(request.message.clone().into())).await?;
upsert_websocket_event(
&window,
WebsocketEvent {
connection_id: connection.id.clone(),
request_id: request.id.clone(),
workspace_id: connection.workspace_id.clone(),
is_server: false,
message_type: WebsocketEventType::Text,
message: request.message.into(),
..Default::default()
},
&UpdateSource::Window,
)
.await
.unwrap();
Ok(connection)
}
#[tauri::command]
pub(crate) async fn close<R: Runtime>(
connection_id: &str,
window: WebviewWindow<R>,
ws_manager: State<'_, Mutex<WebsocketManager>>,
) -> Result<WebsocketConnection> {
let connection = get_websocket_connection(&window, connection_id).await?;
let request = get_websocket_request(&window, &connection.request_id)
.await?
.ok_or(GenericError("WebSocket Request not found".to_string()))?;
let mut ws_manager = ws_manager.lock().await;
ws_manager.send(&connection.id, Message::Close(None)).await?;
upsert_websocket_event(
&window,
WebsocketEvent {
connection_id: connection.id.clone(),
request_id: request.id.clone(),
workspace_id: request.workspace_id.clone(),
is_server: false,
message_type: WebsocketEventType::Close,
..Default::default()
},
&UpdateSource::Window,
)
.await
.unwrap();
let connection = upsert_websocket_connection(
&window,
&WebsocketConnection {
state: WebsocketConnectionState::Closed,
elapsed: Utc::now()
.naive_utc()
.signed_duration_since(connection.created_at)
.num_milliseconds() as i32,
..connection.clone()
},
&UpdateSource::Window,
)
.await?;
Ok(connection)
}
#[tauri::command]
pub(crate) async fn connect<R: Runtime>(
request_id: &str,
environment_id: Option<&str>,
cookie_jar_id: Option<&str>,
window: WebviewWindow<R>,
plugin_manager: State<'_, PluginManager>,
ws_manager: State<'_, Mutex<WebsocketManager>>,
) -> Result<WebsocketConnection> {
let unrendered_request = get_websocket_request(&window, request_id)
.await?
.ok_or(GenericError("Failed to find GRPC request".to_string()))?;
let environment = match environment_id {
Some(id) => Some(get_environment(&window, id).await?),
None => None,
};
let base_environment = get_base_environment(&window, &unrendered_request.workspace_id).await?;
let request = render_request(
&unrendered_request,
&base_environment,
environment.as_ref(),
&PluginTemplateCallback::new(
window.app_handle(),
&WindowContext::from_window(&window),
RenderPurpose::Send,
),
)
.await;
let mut headers = HeaderMap::new();
if let Some(auth_name) = request.authentication_type.clone() {
let auth = request.authentication.clone();
let plugin_req = CallHttpAuthenticationRequest {
context_id: format!("{:x}", md5::compute(request_id.to_string())),
values: serde_json::from_value(serde_json::to_value(&auth).unwrap()).unwrap(),
method: "POST".to_string(),
url: request.url.clone(),
headers: request
.headers
.clone()
.into_iter()
.map(|h| HttpHeader {
name: h.name,
value: h.value,
})
.collect(),
};
let plugin_result =
plugin_manager.call_http_authentication(&window, &auth_name, plugin_req).await?;
for header in plugin_result.set_headers {
headers.insert(
HeaderName::from_str(&header.name).unwrap(),
HeaderValue::from_str(&header.value).unwrap(),
);
}
}
// TODO: Handle cookies
let _cookie_jar = match cookie_jar_id {
Some(id) => Some(get_cookie_jar(&window, id).await?),
None => None,
};
let connection = upsert_websocket_connection(
&window,
&WebsocketConnection {
workspace_id: request.workspace_id.clone(),
request_id: request_id.to_string(),
..Default::default()
},
&UpdateSource::Window,
)
.await?;
let (receive_tx, mut receive_rx) = mpsc::channel::<Message>(128);
let mut ws_manager = ws_manager.lock().await;
{
let connection_id = connection.id.clone();
let request_id = request.id.to_string();
let workspace_id = request.workspace_id.clone();
let window = window.clone();
tokio::spawn(async move {
while let Some(message) = receive_rx.recv().await {
upsert_websocket_event(
&window,
WebsocketEvent {
connection_id: connection_id.clone(),
request_id: request_id.clone(),
workspace_id: workspace_id.clone(),
is_server: true,
message_type: match message {
Message::Text(_) => WebsocketEventType::Text,
Message::Binary(_) => WebsocketEventType::Binary,
Message::Ping(_) => WebsocketEventType::Ping,
Message::Pong(_) => WebsocketEventType::Pong,
Message::Close(_) => WebsocketEventType::Close,
// Raw frame will never happen during a read
Message::Frame(_) => WebsocketEventType::Frame,
},
message: message.into_data().into(),
..Default::default()
},
&UpdateSource::Window,
)
.await
.unwrap();
}
info!("Websocket connection closed");
});
}
let response = match ws_manager.connect(&connection.id, &request.url, headers, receive_tx).await
{
Ok(r) => r,
Err(e) => {
return Ok(upsert_websocket_connection(
&window,
&WebsocketConnection {
error: Some(format!("{e:?}")),
..connection
},
&UpdateSource::Window,
)
.await?);
}
};
let response_headers = response
.headers()
.into_iter()
.map(|(name, value)| HttpResponseHeader {
name: name.to_string(),
value: value.to_str().unwrap().to_string(),
})
.collect::<Vec<HttpResponseHeader>>();
let connection = upsert_websocket_connection(
&window,
&WebsocketConnection {
state: WebsocketConnectionState::Connected,
headers: response_headers,
status: response.status().as_u16() as i32,
url: request.url.clone(),
..connection
},
&UpdateSource::Window,
)
.await?;
Ok(connection)
}

View File

@@ -0,0 +1,80 @@
use log::info;
use rustls::crypto::ring;
use rustls::ClientConfig;
use rustls_platform_verifier::BuilderVerifierExt;
use std::sync::Arc;
use tauri::http::HeaderMap;
use tokio::net::TcpStream;
use tokio_tungstenite::tungstenite::client::IntoClientRequest;
use tokio_tungstenite::tungstenite::handshake::client::Response;
use tokio_tungstenite::tungstenite::http::HeaderValue;
use tokio_tungstenite::tungstenite::protocol::WebSocketConfig;
use tokio_tungstenite::{
connect_async_tls_with_config, Connector, MaybeTlsStream, WebSocketStream,
};
pub(crate) async fn ws_connect(
url: &str,
headers: HeaderMap<HeaderValue>,
) -> crate::error::Result<(WebSocketStream<MaybeTlsStream<TcpStream>>, Response)> {
info!("Connecting to WS {url}");
let arc_crypto_provider = Arc::new(ring::default_provider());
let config = ClientConfig::builder_with_provider(arc_crypto_provider)
.with_safe_default_protocol_versions()
.unwrap()
.with_platform_verifier()
.with_no_client_auth();
let mut req = url.into_client_request()?;
let req_headers = req.headers_mut();
for (name, value) in headers {
if let Some(name) = name {
req_headers.insert(name, value);
}
}
let (stream, response) = connect_async_tls_with_config(
req,
Some(WebSocketConfig::default()),
false,
Some(Connector::Rustls(Arc::new(config))),
)
.await?;
Ok((stream, response))
}
#[cfg(test)]
mod tests {
use crate::connect::ws_connect;
use crate::error::Result;
use futures_util::{SinkExt, StreamExt};
use std::time::Duration;
use tokio::time::timeout;
use tokio_tungstenite::tungstenite::Message;
#[tokio::test]
async fn test_connection() -> Result<()> {
let (stream, response) = ws_connect("wss://echo.websocket.org/", Default::default()).await?;
assert_eq!(response.status(), 101);
let (mut write, mut read) = stream.split();
let task = tokio::spawn(async move {
while let Some(Ok(message)) = read.next().await {
if message.is_text() && message.to_text().unwrap() == "Hello" {
return message;
}
}
panic!("Didn't receive text message");
});
write.send(Message::Text("Hello".into())).await?;
let task = timeout(Duration::from_secs(3), task);
let message = task.await.unwrap().unwrap();
assert_eq!(message.into_text().unwrap(), "Hello");
Ok(())
}
}

View File

@@ -0,0 +1,29 @@
use serde::{Serialize, Serializer};
use thiserror::Error;
use tokio_tungstenite::tungstenite;
#[derive(Error, Debug)]
pub enum Error {
#[error("WebSocket error: {0}")]
WebSocketErr(#[from] tungstenite::Error),
#[error("Model error: {0}")]
ModelError(#[from] yaak_models::error::Error),
#[error("Plugin error: {0}")]
PluginError(#[from] yaak_plugins::error::Error),
#[error("WebSocket error: {0}")]
GenericError(String),
}
impl Serialize for Error {
fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_str(self.to_string().as_ref())
}
}
pub type Result<T> = std::result::Result<T, Error>;

View File

@@ -0,0 +1,37 @@
mod cmd;
mod connect;
mod error;
mod manager;
mod render;
use crate::cmd::{
close, connect, delete_connection, delete_connections, delete_request, list_connections,
list_events, list_requests, send, upsert_request,
};
use crate::manager::WebsocketManager;
use tauri::plugin::{Builder, TauriPlugin};
use tauri::{generate_handler, Manager, Runtime};
use tokio::sync::Mutex;
pub fn init<R: Runtime>() -> TauriPlugin<R> {
Builder::new("yaak-ws")
.invoke_handler(generate_handler![
close,
connect,
delete_connection,
delete_connections,
delete_request,
list_connections,
list_events,
list_requests,
send,
upsert_request,
])
.setup(|app, _api| {
let manager = WebsocketManager::new();
app.manage(Mutex::new(manager));
Ok(())
})
.build()
}

View File

@@ -0,0 +1,62 @@
use crate::connect::ws_connect;
use crate::error::Result;
use futures_util::stream::SplitSink;
use futures_util::{SinkExt, StreamExt};
use log::debug;
use std::collections::HashMap;
use std::sync::Arc;
use tokio::net::TcpStream;
use tokio::sync::{mpsc, Mutex};
use tokio_tungstenite::tungstenite::handshake::client::Response;
use tokio_tungstenite::tungstenite::http::{HeaderMap, HeaderValue};
use tokio_tungstenite::tungstenite::Message;
use tokio_tungstenite::{MaybeTlsStream, WebSocketStream};
#[derive(Clone)]
pub struct WebsocketManager {
connections:
Arc<Mutex<HashMap<String, SplitSink<WebSocketStream<MaybeTlsStream<TcpStream>>, Message>>>>,
}
impl WebsocketManager {
pub fn new() -> Self {
WebsocketManager {
connections: Default::default(),
}
}
pub async fn connect(
&mut self,
id: &str,
url: &str,
headers: HeaderMap<HeaderValue>,
receive_tx: mpsc::Sender<Message>,
) -> Result<Response> {
let (stream, response) = ws_connect(url, headers).await?;
let (write, mut read) = stream.split();
self.connections.lock().await.insert(id.to_string(), write);
let tx = receive_tx.clone();
tauri::async_runtime::spawn(async move {
while let Some(Ok(message)) = read.next().await {
debug!("Received websocket message {message:?}");
if message.is_close() {
return;
}
tx.send(message).await.unwrap();
}
});
Ok(response)
}
pub async fn send(&mut self, id: &str, msg: Message) -> Result<()> {
debug!("Send websocket message {msg:?}");
let mut connections = self.connections.lock().await;
let connection = match connections.get_mut(id) {
None => return Ok(()),
Some(c) => c,
};
connection.send(msg).await?;
Ok(())
}
}

View File

@@ -0,0 +1,40 @@
use std::collections::BTreeMap;
use yaak_models::models::{Environment, HttpRequestHeader, WebsocketRequest};
use yaak_models::render::make_vars_hashmap;
use yaak_templates::{parse_and_render, render_json_value_raw, TemplateCallback};
pub async fn render_request<T: TemplateCallback>(
r: &WebsocketRequest,
base_environment: &Environment,
environment: Option<&Environment>,
cb: &T,
) -> WebsocketRequest {
let vars = &make_vars_hashmap(base_environment, environment);
let mut headers = Vec::new();
for p in r.headers.clone() {
headers.push(HttpRequestHeader {
enabled: p.enabled,
name: parse_and_render(&p.name, vars, cb).await,
value: parse_and_render(&p.value, vars, cb).await,
id: p.id,
})
}
let mut authentication = BTreeMap::new();
for (k, v) in r.authentication.clone() {
authentication.insert(k, render_json_value_raw(v, vars, cb).await);
}
let url = parse_and_render(r.url.as_str(), vars, cb).await;
let message = parse_and_render(&r.message.clone(), vars, cb).await;
WebsocketRequest {
url,
headers,
authentication,
message,
..r.to_owned()
}
}