feat(bridge,ui): add list_channels API and interactive dashboard
- Add Channel model to mm-core - Implement get_my_channels in mm-client - Add list_channels handler and routing in mm-bridge - Create mattermost-dashboard-mode with interactive connection prompt - Add dev-check.sh script for quick Rust validation
This commit is contained in:
Generated
+232
-7
@@ -107,6 +107,15 @@ version = "2.13.2"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06"
|
checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "block-buffer"
|
||||||
|
version = "0.10.4"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71"
|
||||||
|
dependencies = [
|
||||||
|
"generic-array",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "bumpalo"
|
name = "bumpalo"
|
||||||
version = "3.20.4"
|
version = "3.20.4"
|
||||||
@@ -148,8 +157,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
|||||||
checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06"
|
checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"cfg-if",
|
"cfg-if",
|
||||||
"cpufeatures",
|
"cpufeatures 0.3.1",
|
||||||
"rand_core",
|
"rand_core 0.10.1",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
@@ -184,6 +193,15 @@ version = "1.0.0"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "7f8f80099a98041a3d1622845c271458a2d73e688351bf3cb999266764b81d48"
|
checksum = "7f8f80099a98041a3d1622845c271458a2d73e688351bf3cb999266764b81d48"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "cpufeatures"
|
||||||
|
version = "0.2.17"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280"
|
||||||
|
dependencies = [
|
||||||
|
"libc",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "cpufeatures"
|
name = "cpufeatures"
|
||||||
version = "0.3.1"
|
version = "0.3.1"
|
||||||
@@ -193,6 +211,32 @@ dependencies = [
|
|||||||
"libc",
|
"libc",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "crypto-common"
|
||||||
|
version = "0.1.7"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a"
|
||||||
|
dependencies = [
|
||||||
|
"generic-array",
|
||||||
|
"typenum",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "data-encoding"
|
||||||
|
version = "2.11.1"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "4583a4551df46e2792f82ceeac45e850d2e2d5debba0b91f102385cda5b11f06"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "digest"
|
||||||
|
version = "0.10.7"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"
|
||||||
|
dependencies = [
|
||||||
|
"block-buffer",
|
||||||
|
"crypto-common",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "displaydoc"
|
name = "displaydoc"
|
||||||
version = "0.2.7"
|
version = "0.2.7"
|
||||||
@@ -291,6 +335,17 @@ version = "0.3.34"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e"
|
checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "futures-macro"
|
||||||
|
version = "0.3.34"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "9fb9654ba8355388abeb8dcb4fc62f511300867002afc858860463bdd9fe0c44"
|
||||||
|
dependencies = [
|
||||||
|
"proc-macro2",
|
||||||
|
"quote",
|
||||||
|
"syn 3.0.10",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "futures-sink"
|
name = "futures-sink"
|
||||||
version = "0.3.34"
|
version = "0.3.34"
|
||||||
@@ -310,11 +365,23 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
|||||||
checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc"
|
checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"futures-core",
|
"futures-core",
|
||||||
|
"futures-macro",
|
||||||
|
"futures-sink",
|
||||||
"futures-task",
|
"futures-task",
|
||||||
"pin-project-lite",
|
"pin-project-lite",
|
||||||
"slab",
|
"slab",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "generic-array"
|
||||||
|
version = "0.14.7"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a"
|
||||||
|
dependencies = [
|
||||||
|
"typenum",
|
||||||
|
"version_check",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "getrandom"
|
name = "getrandom"
|
||||||
version = "0.2.17"
|
version = "0.2.17"
|
||||||
@@ -328,6 +395,18 @@ dependencies = [
|
|||||||
"wasm-bindgen",
|
"wasm-bindgen",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "getrandom"
|
||||||
|
version = "0.3.4"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd"
|
||||||
|
dependencies = [
|
||||||
|
"cfg-if",
|
||||||
|
"libc",
|
||||||
|
"r-efi 5.3.0",
|
||||||
|
"wasip2",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "getrandom"
|
name = "getrandom"
|
||||||
version = "0.4.3"
|
version = "0.4.3"
|
||||||
@@ -337,8 +416,8 @@ dependencies = [
|
|||||||
"cfg-if",
|
"cfg-if",
|
||||||
"js-sys",
|
"js-sys",
|
||||||
"libc",
|
"libc",
|
||||||
"r-efi",
|
"r-efi 6.0.0",
|
||||||
"rand_core",
|
"rand_core 0.10.1",
|
||||||
"wasm-bindgen",
|
"wasm-bindgen",
|
||||||
]
|
]
|
||||||
|
|
||||||
@@ -724,6 +803,7 @@ dependencies = [
|
|||||||
name = "mm-client"
|
name = "mm-client"
|
||||||
version = "0.1.0"
|
version = "0.1.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
|
"futures-util",
|
||||||
"mm-core",
|
"mm-core",
|
||||||
"reqwest",
|
"reqwest",
|
||||||
"serde",
|
"serde",
|
||||||
@@ -731,7 +811,9 @@ dependencies = [
|
|||||||
"tempfile",
|
"tempfile",
|
||||||
"thiserror 1.0.69",
|
"thiserror 1.0.69",
|
||||||
"tokio",
|
"tokio",
|
||||||
|
"tokio-tungstenite",
|
||||||
"tracing",
|
"tracing",
|
||||||
|
"url",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
@@ -871,6 +953,15 @@ dependencies = [
|
|||||||
"zerovec",
|
"zerovec",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "ppv-lite86"
|
||||||
|
version = "0.2.21"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9"
|
||||||
|
dependencies = [
|
||||||
|
"zerocopy",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "proc-macro2"
|
name = "proc-macro2"
|
||||||
version = "1.0.107"
|
version = "1.0.107"
|
||||||
@@ -909,7 +1000,7 @@ dependencies = [
|
|||||||
"bytes",
|
"bytes",
|
||||||
"getrandom 0.4.3",
|
"getrandom 0.4.3",
|
||||||
"lru-slab",
|
"lru-slab",
|
||||||
"rand",
|
"rand 0.10.4",
|
||||||
"rand_pcg",
|
"rand_pcg",
|
||||||
"ring",
|
"ring",
|
||||||
"rustc-hash",
|
"rustc-hash",
|
||||||
@@ -945,12 +1036,28 @@ dependencies = [
|
|||||||
"proc-macro2",
|
"proc-macro2",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "r-efi"
|
||||||
|
version = "5.3.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "r-efi"
|
name = "r-efi"
|
||||||
version = "6.0.0"
|
version = "6.0.0"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf"
|
checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "rand"
|
||||||
|
version = "0.9.5"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "b9ef1d0d795eb7d84685bca4f72f3649f064e6641543d3a8c415898726a57b41"
|
||||||
|
dependencies = [
|
||||||
|
"rand_chacha",
|
||||||
|
"rand_core 0.9.5",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "rand"
|
name = "rand"
|
||||||
version = "0.10.4"
|
version = "0.10.4"
|
||||||
@@ -959,7 +1066,26 @@ checksum = "8f6fa277c67e6ea590466f04c3fe82cb509f0864fe470643e5570de9514a9b11"
|
|||||||
dependencies = [
|
dependencies = [
|
||||||
"chacha20",
|
"chacha20",
|
||||||
"getrandom 0.4.3",
|
"getrandom 0.4.3",
|
||||||
"rand_core",
|
"rand_core 0.10.1",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "rand_chacha"
|
||||||
|
version = "0.9.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb"
|
||||||
|
dependencies = [
|
||||||
|
"ppv-lite86",
|
||||||
|
"rand_core 0.9.5",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "rand_core"
|
||||||
|
version = "0.9.5"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c"
|
||||||
|
dependencies = [
|
||||||
|
"getrandom 0.3.4",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
@@ -974,7 +1100,7 @@ version = "0.10.2"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "caa0f4137e1c0a72f4c651489402276c8e8e1cf081f3b0ba156d2cbeef09e86a"
|
checksum = "caa0f4137e1c0a72f4c651489402276c8e8e1cf081f3b0ba156d2cbeef09e86a"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"rand_core",
|
"rand_core 0.10.1",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
@@ -1234,6 +1360,17 @@ dependencies = [
|
|||||||
"serde",
|
"serde",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "sha1"
|
||||||
|
version = "0.10.7"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "a978451301f4db1d02937a4ab3ccce137717b81826e79b7d49ffe3244a13c3b8"
|
||||||
|
dependencies = [
|
||||||
|
"cfg-if",
|
||||||
|
"cpufeatures 0.2.17",
|
||||||
|
"digest",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "sharded-slab"
|
name = "sharded-slab"
|
||||||
version = "0.1.7"
|
version = "0.1.7"
|
||||||
@@ -1476,6 +1613,22 @@ dependencies = [
|
|||||||
"tokio",
|
"tokio",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "tokio-tungstenite"
|
||||||
|
version = "0.26.2"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "7a9daff607c6d2bf6c16fd681ccb7eecc83e4e2cdc1ca067ffaadfca5de7f084"
|
||||||
|
dependencies = [
|
||||||
|
"futures-util",
|
||||||
|
"log",
|
||||||
|
"rustls",
|
||||||
|
"rustls-native-certs",
|
||||||
|
"rustls-pki-types",
|
||||||
|
"tokio",
|
||||||
|
"tokio-rustls",
|
||||||
|
"tungstenite",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "tokio-util"
|
name = "tokio-util"
|
||||||
version = "0.7.20"
|
version = "0.7.20"
|
||||||
@@ -1604,6 +1757,31 @@ version = "0.2.5"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b"
|
checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "tungstenite"
|
||||||
|
version = "0.26.2"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "4793cb5e56680ecbb1d843515b23b6de9a75eb04b66643e256a396d43be33c13"
|
||||||
|
dependencies = [
|
||||||
|
"bytes",
|
||||||
|
"data-encoding",
|
||||||
|
"http",
|
||||||
|
"httparse",
|
||||||
|
"log",
|
||||||
|
"rand 0.9.5",
|
||||||
|
"rustls",
|
||||||
|
"rustls-pki-types",
|
||||||
|
"sha1",
|
||||||
|
"thiserror 2.0.21",
|
||||||
|
"utf-8",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "typenum"
|
||||||
|
version = "1.20.1"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "unicode-ident"
|
name = "unicode-ident"
|
||||||
version = "1.0.27"
|
version = "1.0.27"
|
||||||
@@ -1628,6 +1806,12 @@ dependencies = [
|
|||||||
"serde",
|
"serde",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "utf-8"
|
||||||
|
version = "0.7.6"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "09cc8ee72d2a9becf2f2febe0205bbed8fc6615b7cb429ad062dc7b7ddd036a9"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "utf8_iter"
|
name = "utf8_iter"
|
||||||
version = "1.1.0"
|
version = "1.1.0"
|
||||||
@@ -1655,6 +1839,12 @@ version = "0.2.15"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426"
|
checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "version_check"
|
||||||
|
version = "0.9.5"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "want"
|
name = "want"
|
||||||
version = "0.3.2"
|
version = "0.3.2"
|
||||||
@@ -1670,6 +1860,15 @@ version = "0.11.1+wasi-snapshot-preview1"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b"
|
checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "wasip2"
|
||||||
|
version = "1.0.4+wasi-0.2.12"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "b67efb37e106e55ce722a510d6b5f9c17f083e5fc79afc2badeb12cc313d9487"
|
||||||
|
dependencies = [
|
||||||
|
"wit-bindgen",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "wasm-bindgen"
|
name = "wasm-bindgen"
|
||||||
version = "0.2.130"
|
version = "0.2.130"
|
||||||
@@ -1862,6 +2061,12 @@ version = "0.52.6"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec"
|
checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "wit-bindgen"
|
||||||
|
version = "0.57.1"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "writeable"
|
name = "writeable"
|
||||||
version = "0.6.4"
|
version = "0.6.4"
|
||||||
@@ -1891,6 +2096,26 @@ dependencies = [
|
|||||||
"synstructure",
|
"synstructure",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "zerocopy"
|
||||||
|
version = "0.8.63"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "e5fe1f8f1b06191a00962174c61aa5005e0bb391a6d80d07e24d115c01a92ed8"
|
||||||
|
dependencies = [
|
||||||
|
"zerocopy-derive",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "zerocopy-derive"
|
||||||
|
version = "0.8.63"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "863ad3ac83293fb4d740aedbfdc9240dd8d1a50c1099acd76ce80ce7c7230c7f"
|
||||||
|
dependencies = [
|
||||||
|
"proc-macro2",
|
||||||
|
"quote",
|
||||||
|
"syn 2.0.119",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "zerofrom"
|
name = "zerofrom"
|
||||||
version = "0.1.8"
|
version = "0.1.8"
|
||||||
|
|||||||
@@ -0,0 +1,369 @@
|
|||||||
|
use crate::app::state::{AppState, ConnectionState};
|
||||||
|
use crate::protocol;
|
||||||
|
use mm_client::MattermostClient;
|
||||||
|
use mm_core::{BridgeError, ErrorKind, ServerConfig, ServerId, User};
|
||||||
|
use mm_store::{ServerStore, TokenStore};
|
||||||
|
use std::path::{Path, PathBuf};
|
||||||
|
|
||||||
|
pub async fn handle_connect(
|
||||||
|
app_state: &AppState,
|
||||||
|
data_dir: &Path,
|
||||||
|
request: protocol::Request,
|
||||||
|
) -> protocol::Response {
|
||||||
|
tracing::info!(
|
||||||
|
"Received connect request for server_id={:?}",
|
||||||
|
request.params.get("server_id")
|
||||||
|
);
|
||||||
|
|
||||||
|
let params = match request.params.as_object() {
|
||||||
|
Some(p) => p,
|
||||||
|
None => return protocol_err(request.id, "params must be an object"),
|
||||||
|
};
|
||||||
|
|
||||||
|
let server_id = get_server_id(params);
|
||||||
|
let url = match params.get("url").and_then(|v| v.as_str()) {
|
||||||
|
Some(u) => u.to_string(),
|
||||||
|
None => return protocol_err(request.id, "missing url"),
|
||||||
|
};
|
||||||
|
|
||||||
|
let ca_file = params
|
||||||
|
.get("ca_file")
|
||||||
|
.and_then(|v| v.as_str())
|
||||||
|
.map(String::from);
|
||||||
|
|
||||||
|
let token_result = if let (Some(login), Some(password)) = (
|
||||||
|
params.get("login_id").and_then(|v| v.as_str()),
|
||||||
|
params.get("password").and_then(|v| v.as_str()),
|
||||||
|
) {
|
||||||
|
do_login(&url, login, password, ca_file.as_deref()).await
|
||||||
|
} else if let Some(token) = params.get("token").and_then(|v| v.as_str()) {
|
||||||
|
Ok(token.to_string())
|
||||||
|
} else {
|
||||||
|
Err(BridgeError::new(
|
||||||
|
ErrorKind::InvalidRequest,
|
||||||
|
"provide credentials or token",
|
||||||
|
))
|
||||||
|
};
|
||||||
|
|
||||||
|
match token_result {
|
||||||
|
Ok(token) => {
|
||||||
|
if let Err(e) = save_token_and_config(data_dir, &server_id, &token, &url) {
|
||||||
|
return e;
|
||||||
|
}
|
||||||
|
|
||||||
|
match do_get_me(&url, &token, ca_file.as_deref()).await {
|
||||||
|
Ok(user) => {
|
||||||
|
app_state.add_connection(
|
||||||
|
server_id.clone(),
|
||||||
|
ConnectionState {
|
||||||
|
user: user.clone(),
|
||||||
|
token: token.clone(),
|
||||||
|
url: url.clone(),
|
||||||
|
ca_file,
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
// Start WebSocket in background
|
||||||
|
tracing::info!(server_id = %server_id, "Connection established, starting WebSocket");
|
||||||
|
if let Err(e) = app_state.start_ws(&server_id).await {
|
||||||
|
tracing::error!(server_id = %server_id, "Failed to start WebSocket: {}", e);
|
||||||
|
} else {
|
||||||
|
tracing::info!(server_id = %server_id, "WebSocket spawn task created");
|
||||||
|
}
|
||||||
|
|
||||||
|
protocol::Response::ok(
|
||||||
|
request.id,
|
||||||
|
serde_json::json!({
|
||||||
|
"server_id": server_id,
|
||||||
|
"user": user,
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
Err(e) => protocol::Response::err(request.id, e),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Err(e) => protocol::Response::err(request.id, e),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn handle_me(app_state: &AppState, request: protocol::Request) -> protocol::Response {
|
||||||
|
tracing::debug!("Received me request");
|
||||||
|
let params = match request.params.as_object() {
|
||||||
|
Some(p) => p,
|
||||||
|
None => return protocol_err(request.id, "params must be an object"),
|
||||||
|
};
|
||||||
|
let server_id = get_server_id(params);
|
||||||
|
|
||||||
|
match app_state.get_connection(&server_id) {
|
||||||
|
Ok(state) => protocol::Response::ok(
|
||||||
|
request.id,
|
||||||
|
serde_json::json!({
|
||||||
|
"server_id": server_id,
|
||||||
|
"user": state.user,
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
Err(e) => protocol::Response::err(request.id, e),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn handle_teams(app_state: &AppState, request: protocol::Request) -> protocol::Response {
|
||||||
|
tracing::debug!("Received teams request");
|
||||||
|
let params = match request.params.as_object() {
|
||||||
|
Some(p) => p,
|
||||||
|
None => return protocol_err(request.id, "params must be an object"),
|
||||||
|
};
|
||||||
|
let server_id = get_server_id(params);
|
||||||
|
|
||||||
|
let client = match get_client(app_state, &server_id) {
|
||||||
|
Ok(c) => c,
|
||||||
|
Err(e) => return protocol::Response::err(request.id, e),
|
||||||
|
};
|
||||||
|
let token = match get_token(app_state, &server_id) {
|
||||||
|
Ok(t) => t,
|
||||||
|
Err(e) => return protocol::Response::err(request.id, e),
|
||||||
|
};
|
||||||
|
|
||||||
|
match client.get_teams(&token).await {
|
||||||
|
Ok(teams) => protocol::Response::ok(
|
||||||
|
request.id,
|
||||||
|
serde_json::json!({
|
||||||
|
"server_id": server_id,
|
||||||
|
"teams": teams,
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
Err(e) => protocol::Response::err(request.id, e.into()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn handle_list_channels(
|
||||||
|
app_state: &AppState,
|
||||||
|
request: protocol::Request,
|
||||||
|
) -> protocol::Response {
|
||||||
|
tracing::debug!("Received list_channels request");
|
||||||
|
let params = match request.params.as_object() {
|
||||||
|
Some(p) => p,
|
||||||
|
None => return protocol_err(request.id, "params must be an object"),
|
||||||
|
};
|
||||||
|
let server_id = get_server_id(params);
|
||||||
|
|
||||||
|
let client = match get_client(app_state, &server_id) {
|
||||||
|
Ok(c) => c,
|
||||||
|
Err(e) => return protocol::Response::err(request.id, e),
|
||||||
|
};
|
||||||
|
let token = match get_token(app_state, &server_id) {
|
||||||
|
Ok(t) => t,
|
||||||
|
Err(e) => return protocol::Response::err(request.id, e),
|
||||||
|
};
|
||||||
|
|
||||||
|
match client.get_my_channels(&token).await {
|
||||||
|
Ok(channels) => protocol::Response::ok(
|
||||||
|
request.id,
|
||||||
|
serde_json::json!({
|
||||||
|
"server_id": server_id,
|
||||||
|
"channels": channels,
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
Err(e) => protocol::Response::err(request.id, e.into()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn handle_open_self_dm(
|
||||||
|
app_state: &AppState,
|
||||||
|
request: protocol::Request,
|
||||||
|
) -> protocol::Response {
|
||||||
|
tracing::debug!("Received open_self_dm request: {:?}", request.params);
|
||||||
|
let params = match request.params.as_object() {
|
||||||
|
Some(p) => p,
|
||||||
|
None => return protocol_err(request.id, "params must be an object"),
|
||||||
|
};
|
||||||
|
let server_id = get_server_id(params);
|
||||||
|
|
||||||
|
let client = match get_client(app_state, &server_id) {
|
||||||
|
Ok(c) => c,
|
||||||
|
Err(e) => return protocol::Response::err(request.id, e),
|
||||||
|
};
|
||||||
|
let user_id = match get_user_id(app_state, &server_id) {
|
||||||
|
Ok(id) => id.0,
|
||||||
|
Err(e) => return protocol::Response::err(request.id, e),
|
||||||
|
};
|
||||||
|
let token = match get_token(app_state, &server_id) {
|
||||||
|
Ok(t) => t,
|
||||||
|
Err(e) => return protocol::Response::err(request.id, e),
|
||||||
|
};
|
||||||
|
|
||||||
|
match client
|
||||||
|
.create_direct_channel(&token, &[user_id.clone(), user_id])
|
||||||
|
.await
|
||||||
|
{
|
||||||
|
Ok(channel_id) => protocol::Response::ok(
|
||||||
|
request.id,
|
||||||
|
serde_json::json!({
|
||||||
|
"server_id": server_id,
|
||||||
|
"channel": {
|
||||||
|
"id": channel_id,
|
||||||
|
"type": "direct",
|
||||||
|
"display_name": "Self"
|
||||||
|
}
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
Err(e) => protocol::Response::err(request.id, e.into()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn handle_get_history(
|
||||||
|
app_state: &AppState,
|
||||||
|
request: protocol::Request,
|
||||||
|
) -> protocol::Response {
|
||||||
|
tracing::debug!("Received get_history request: {:?}", request.params);
|
||||||
|
let params = match request.params.as_object() {
|
||||||
|
Some(p) => p,
|
||||||
|
None => return protocol_err(request.id, "params must be an object"),
|
||||||
|
};
|
||||||
|
let server_id = get_server_id(params);
|
||||||
|
let channel_id = match params.get("channel_id").and_then(|v| v.as_str()) {
|
||||||
|
Some(id) => id,
|
||||||
|
None => return protocol_err(request.id, "missing channel_id"),
|
||||||
|
};
|
||||||
|
let limit = params.get("limit").and_then(|v| v.as_u64()).unwrap_or(10) as u32;
|
||||||
|
let before = params.get("before").and_then(|v| v.as_str());
|
||||||
|
|
||||||
|
let client = match get_client(app_state, &server_id) {
|
||||||
|
Ok(c) => c,
|
||||||
|
Err(e) => return protocol::Response::err(request.id, e),
|
||||||
|
};
|
||||||
|
let token = match get_token(app_state, &server_id) {
|
||||||
|
Ok(t) => t,
|
||||||
|
Err(e) => return protocol::Response::err(request.id, e),
|
||||||
|
};
|
||||||
|
|
||||||
|
match client.get_posts(&token, channel_id, limit, before).await {
|
||||||
|
Ok(posts) => protocol::Response::ok(
|
||||||
|
request.id,
|
||||||
|
serde_json::json!({
|
||||||
|
"server_id": server_id,
|
||||||
|
"channel_id": channel_id,
|
||||||
|
"posts": posts,
|
||||||
|
"before": before,
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
Err(e) => protocol::Response::err(request.id, e.into()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn handle_send_post(
|
||||||
|
app_state: &AppState,
|
||||||
|
request: protocol::Request,
|
||||||
|
) -> protocol::Response {
|
||||||
|
tracing::debug!("Received send_post request");
|
||||||
|
let params = match request.params.as_object() {
|
||||||
|
Some(p) => p,
|
||||||
|
None => return protocol_err(request.id, "params must be an object"),
|
||||||
|
};
|
||||||
|
let server_id = get_server_id(params);
|
||||||
|
let channel_id = match params.get("channel_id").and_then(|v| v.as_str()) {
|
||||||
|
Some(id) => id,
|
||||||
|
None => return protocol_err(request.id, "missing channel_id"),
|
||||||
|
};
|
||||||
|
let message = match params.get("message").and_then(|v| v.as_str()) {
|
||||||
|
Some(m) => m,
|
||||||
|
None => return protocol_err(request.id, "missing message"),
|
||||||
|
};
|
||||||
|
let root_id = params.get("root_id").and_then(|v| v.as_str());
|
||||||
|
|
||||||
|
let client = match get_client(app_state, &server_id) {
|
||||||
|
Ok(c) => c,
|
||||||
|
Err(e) => return protocol::Response::err(request.id, e),
|
||||||
|
};
|
||||||
|
let token = match get_token(app_state, &server_id) {
|
||||||
|
Ok(t) => t,
|
||||||
|
Err(e) => return protocol::Response::err(request.id, e),
|
||||||
|
};
|
||||||
|
|
||||||
|
match client
|
||||||
|
.create_post(&token, channel_id, message, root_id)
|
||||||
|
.await
|
||||||
|
{
|
||||||
|
Ok(post) => protocol::Response::ok(
|
||||||
|
request.id,
|
||||||
|
serde_json::json!({
|
||||||
|
"server_id": server_id,
|
||||||
|
"post": post,
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
Err(e) => protocol::Response::err(request.id, e.into()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Helpers ---
|
||||||
|
|
||||||
|
fn protocol_err(id: impl Into<String>, msg: &str) -> protocol::Response {
|
||||||
|
protocol::Response::err(id, BridgeError::new(ErrorKind::InvalidRequest, msg))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn get_server_id(params: &serde_json::Map<String, serde_json::Value>) -> ServerId {
|
||||||
|
params
|
||||||
|
.get("server_id")
|
||||||
|
.and_then(|v| v.as_str())
|
||||||
|
.map(ServerId::new)
|
||||||
|
.unwrap_or_else(|| ServerId::new("default"))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn get_client(app_state: &AppState, server_id: &ServerId) -> Result<MattermostClient, BridgeError> {
|
||||||
|
let state = app_state.get_connection(server_id)?;
|
||||||
|
let ca_path = state.ca_file.as_ref().map(PathBuf::from);
|
||||||
|
MattermostClient::new(state.url, ca_path.as_deref())
|
||||||
|
.map_err(|e| BridgeError::new(ErrorKind::InternalError, e.to_string()))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn get_token(app_state: &AppState, server_id: &ServerId) -> Result<String, BridgeError> {
|
||||||
|
app_state.get_connection(server_id).map(|s| s.token.clone())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn get_user_id(app_state: &AppState, server_id: &ServerId) -> Result<mm_core::UserId, BridgeError> {
|
||||||
|
app_state
|
||||||
|
.get_connection(server_id)
|
||||||
|
.map(|s| s.user.id.clone())
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn do_login(
|
||||||
|
url: &str,
|
||||||
|
login: &str,
|
||||||
|
pass: &str,
|
||||||
|
ca: Option<&str>,
|
||||||
|
) -> Result<String, BridgeError> {
|
||||||
|
let ca_path = ca.map(PathBuf::from);
|
||||||
|
let client = MattermostClient::new(url.to_string(), ca_path.as_deref())
|
||||||
|
.map_err(|e| BridgeError::new(ErrorKind::InternalError, e.to_string()))?;
|
||||||
|
client.login(login, pass).await.map_err(Into::into)
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn do_get_me(url: &str, token: &str, ca: Option<&str>) -> Result<User, BridgeError> {
|
||||||
|
let ca_path = ca.map(PathBuf::from);
|
||||||
|
let client = MattermostClient::new(url.to_string(), ca_path.as_deref())
|
||||||
|
.map_err(|e| BridgeError::new(ErrorKind::InternalError, e.to_string()))?;
|
||||||
|
client.get_me(token).await.map_err(Into::into)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn save_token_and_config(
|
||||||
|
data_dir: &Path,
|
||||||
|
server_id: &ServerId,
|
||||||
|
token: &str,
|
||||||
|
url: &str,
|
||||||
|
) -> Result<(), protocol::Response> {
|
||||||
|
let token_store = TokenStore::new(data_dir);
|
||||||
|
let server_store = ServerStore::new(data_dir);
|
||||||
|
|
||||||
|
token_store
|
||||||
|
.save(server_id, token)
|
||||||
|
.map_err(|e| protocol::Response::err("req", e))?;
|
||||||
|
|
||||||
|
let config = ServerConfig {
|
||||||
|
server_id: server_id.clone(),
|
||||||
|
url: url.to_string(),
|
||||||
|
};
|
||||||
|
server_store
|
||||||
|
.save(&config)
|
||||||
|
.map_err(|e| protocol::Response::err("req", e))?;
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
@@ -1,349 +1,47 @@
|
|||||||
|
mod handlers;
|
||||||
|
mod state;
|
||||||
|
|
||||||
use crate::{protocol, status};
|
use crate::{protocol, status};
|
||||||
use mm_client::MattermostClient;
|
use mm_core::BridgeError;
|
||||||
use mm_core::{BridgeError, ErrorKind, ServerConfig, ServerId, User};
|
use std::path::PathBuf;
|
||||||
use mm_store::{ServerStore, TokenStore};
|
|
||||||
use std::collections::HashMap;
|
|
||||||
use std::path::{Path, PathBuf};
|
|
||||||
use std::sync::{Arc, Mutex};
|
|
||||||
|
|
||||||
#[derive(Debug, Clone)]
|
pub use state::AppState;
|
||||||
struct ConnectionState {
|
|
||||||
user: User,
|
|
||||||
#[allow(dead_code)]
|
|
||||||
token: String,
|
|
||||||
url: String,
|
|
||||||
ca_file: Option<String>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Clone)]
|
#[derive(Clone)]
|
||||||
pub struct App {
|
pub struct App {
|
||||||
data_dir: PathBuf,
|
pub data_dir: PathBuf,
|
||||||
connections: Arc<Mutex<HashMap<ServerId, ConnectionState>>>,
|
pub state: AppState,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl App {
|
impl App {
|
||||||
pub fn new(data_dir: impl Into<PathBuf>) -> Self {
|
pub fn new(data_dir: impl Into<PathBuf>) -> Self {
|
||||||
Self {
|
Self {
|
||||||
data_dir: data_dir.into(),
|
data_dir: data_dir.into(),
|
||||||
connections: Arc::new(Mutex::new(HashMap::new())),
|
state: AppState::new(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn data_dir(&self) -> &Path {
|
|
||||||
&self.data_dir
|
|
||||||
}
|
|
||||||
|
|
||||||
pub async fn handle_request(&self, request: protocol::Request) -> protocol::Response {
|
pub async fn handle_request(&self, request: protocol::Request) -> protocol::Response {
|
||||||
match request.method.as_str() {
|
match request.method.as_str() {
|
||||||
"ping" => protocol::Response::ok(request.id, protocol::pong_result()),
|
"ping" => protocol::Response::ok(request.id, protocol::pong_result()),
|
||||||
"status" => protocol::Response::ok(request.id, status::status_result(&self.data_dir)),
|
"status" => protocol::Response::ok(request.id, status::status_result(&self.data_dir)),
|
||||||
"connect" => self.handle_connect(request).await,
|
"connect" => handlers::handle_connect(&self.state, &self.data_dir, request).await,
|
||||||
"me" => self.handle_me(request),
|
"me" => handlers::handle_me(&self.state, request).await,
|
||||||
"teams" => self.handle_teams(request).await,
|
"teams" => handlers::handle_teams(&self.state, request).await,
|
||||||
"open_self_dm" => self.handle_open_self_dm(request).await,
|
"list_channels" => handlers::handle_list_channels(&self.state, request).await,
|
||||||
"get_history" => self.handle_get_history(request).await,
|
"open_self_dm" => handlers::handle_open_self_dm(&self.state, request).await,
|
||||||
"send_post" => self.handle_send_post(request).await,
|
"get_history" => handlers::handle_get_history(&self.state, request).await,
|
||||||
|
"send_post" => handlers::handle_send_post(&self.state, request).await,
|
||||||
_ => protocol::Response::err(
|
_ => protocol::Response::err(
|
||||||
request.id,
|
request.id,
|
||||||
BridgeError::new(
|
BridgeError::new(
|
||||||
ErrorKind::UnknownMethod,
|
mm_core::ErrorKind::UnknownMethod,
|
||||||
format!("unknown method: {}", request.method),
|
format!("unknown method: {}", request.method),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn handle_connect(&self, request: protocol::Request) -> protocol::Response {
|
|
||||||
let params = match request.params.as_object() {
|
|
||||||
Some(p) => p,
|
|
||||||
None => return protocol_err(request.id, "params must be an object"),
|
|
||||||
};
|
|
||||||
|
|
||||||
let server_id = get_server_id(params);
|
|
||||||
let url = match params.get("url").and_then(|v| v.as_str()) {
|
|
||||||
Some(u) => u.to_string(),
|
|
||||||
None => return protocol_err(request.id, "missing url"),
|
|
||||||
};
|
|
||||||
|
|
||||||
let ca_file = params
|
|
||||||
.get("ca_file")
|
|
||||||
.and_then(|v| v.as_str())
|
|
||||||
.map(String::from);
|
|
||||||
|
|
||||||
let token_result = if let (Some(login), Some(password)) = (
|
|
||||||
params.get("login_id").and_then(|v| v.as_str()),
|
|
||||||
params.get("password").and_then(|v| v.as_str()),
|
|
||||||
) {
|
|
||||||
self.do_login(&url, login, password, ca_file.as_deref())
|
|
||||||
.await
|
|
||||||
} else if let Some(token) = params.get("token").and_then(|v| v.as_str()) {
|
|
||||||
Ok(token.to_string())
|
|
||||||
} else {
|
|
||||||
Err(BridgeError::new(
|
|
||||||
ErrorKind::InvalidRequest,
|
|
||||||
"provide credentials or token",
|
|
||||||
))
|
|
||||||
};
|
|
||||||
|
|
||||||
match token_result {
|
|
||||||
Ok(token) => {
|
|
||||||
if let Err(e) = save_token_and_config(&self.data_dir, &server_id, &token, &url) {
|
|
||||||
return e;
|
|
||||||
}
|
|
||||||
|
|
||||||
match self.do_get_me(&url, &token, ca_file.as_deref()).await {
|
|
||||||
Ok(user) => {
|
|
||||||
let mut conns = self.connections.lock().unwrap();
|
|
||||||
conns.insert(
|
|
||||||
server_id.clone(),
|
|
||||||
ConnectionState {
|
|
||||||
user: user.clone(),
|
|
||||||
token: token.clone(),
|
|
||||||
url: url.clone(),
|
|
||||||
ca_file,
|
|
||||||
},
|
|
||||||
);
|
|
||||||
|
|
||||||
protocol::Response::ok(
|
|
||||||
request.id,
|
|
||||||
serde_json::json!({
|
|
||||||
"server_id": server_id,
|
|
||||||
"user": user,
|
|
||||||
}),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
Err(e) => protocol::Response::err(request.id, e),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Err(e) => protocol::Response::err(request.id, e),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn handle_me(&self, request: protocol::Request) -> protocol::Response {
|
|
||||||
let params = match request.params.as_object() {
|
|
||||||
Some(p) => p,
|
|
||||||
None => return protocol_err(request.id, "params must be an object"),
|
|
||||||
};
|
|
||||||
let server_id = get_server_id(params);
|
|
||||||
|
|
||||||
let conns = self.connections.lock().unwrap();
|
|
||||||
if let Some(state) = conns.get(&server_id) {
|
|
||||||
protocol::Response::ok(
|
|
||||||
request.id,
|
|
||||||
serde_json::json!({
|
|
||||||
"server_id": server_id,
|
|
||||||
"user": state.user,
|
|
||||||
}),
|
|
||||||
)
|
|
||||||
} else {
|
|
||||||
protocol::Response::err(
|
|
||||||
request.id,
|
|
||||||
BridgeError::new(ErrorKind::Unauthorized, "not connected"),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn handle_teams(&self, request: protocol::Request) -> protocol::Response {
|
|
||||||
let params = match request.params.as_object() {
|
|
||||||
Some(p) => p,
|
|
||||||
None => return protocol_err(request.id, "params must be an object"),
|
|
||||||
};
|
|
||||||
let server_id = get_server_id(params);
|
|
||||||
|
|
||||||
let client = match self.get_client(&server_id) {
|
|
||||||
Ok(c) => c,
|
|
||||||
Err(e) => return protocol::Response::err(request.id, e),
|
|
||||||
};
|
|
||||||
|
|
||||||
let token = match self.get_token(&server_id) {
|
|
||||||
Ok(t) => t,
|
|
||||||
Err(e) => return protocol::Response::err(request.id, e),
|
|
||||||
};
|
|
||||||
|
|
||||||
match client.get_teams(&token).await {
|
|
||||||
Ok(teams) => protocol::Response::ok(
|
|
||||||
request.id,
|
|
||||||
serde_json::json!({
|
|
||||||
"server_id": server_id,
|
|
||||||
"teams": teams,
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
Err(e) => protocol::Response::err(request.id, e.into()),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn handle_open_self_dm(&self, request: protocol::Request) -> protocol::Response {
|
|
||||||
let params = match request.params.as_object() {
|
|
||||||
Some(p) => p,
|
|
||||||
None => return protocol_err(request.id, "params must be an object"),
|
|
||||||
};
|
|
||||||
let server_id = get_server_id(params);
|
|
||||||
|
|
||||||
let client = match self.get_client(&server_id) {
|
|
||||||
Ok(c) => c,
|
|
||||||
Err(e) => return protocol::Response::err(request.id, e),
|
|
||||||
};
|
|
||||||
|
|
||||||
let user_id = match self.get_user_id(&server_id) {
|
|
||||||
Ok(id) => id.0,
|
|
||||||
Err(e) => return protocol::Response::err(request.id, e),
|
|
||||||
};
|
|
||||||
|
|
||||||
let token = match self.get_token(&server_id) {
|
|
||||||
Ok(t) => t,
|
|
||||||
Err(e) => return protocol::Response::err(request.id, e),
|
|
||||||
};
|
|
||||||
|
|
||||||
// For self-DM, we pass the same ID twice
|
|
||||||
match client
|
|
||||||
.create_direct_channel(&token, &[user_id.clone(), user_id])
|
|
||||||
.await
|
|
||||||
{
|
|
||||||
Ok(channel_id) => protocol::Response::ok(
|
|
||||||
request.id,
|
|
||||||
serde_json::json!({
|
|
||||||
"server_id": server_id,
|
|
||||||
"channel": {
|
|
||||||
"id": channel_id,
|
|
||||||
"type": "direct",
|
|
||||||
"display_name": "Self"
|
|
||||||
}
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
Err(e) => protocol::Response::err(request.id, e.into()),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn handle_get_history(&self, request: protocol::Request) -> protocol::Response {
|
|
||||||
let params = match request.params.as_object() {
|
|
||||||
Some(p) => p,
|
|
||||||
None => return protocol_err(request.id, "params must be an object"),
|
|
||||||
};
|
|
||||||
let server_id = get_server_id(params);
|
|
||||||
let channel_id = match params.get("channel_id").and_then(|v| v.as_str()) {
|
|
||||||
Some(id) => id,
|
|
||||||
None => return protocol_err(request.id, "missing channel_id"),
|
|
||||||
};
|
|
||||||
let limit = params.get("limit").and_then(|v| v.as_u64()).unwrap_or(50) as u32;
|
|
||||||
|
|
||||||
let client = match self.get_client(&server_id) {
|
|
||||||
Ok(c) => c,
|
|
||||||
Err(e) => return protocol::Response::err(request.id, e),
|
|
||||||
};
|
|
||||||
|
|
||||||
let token = match self.get_token(&server_id) {
|
|
||||||
Ok(t) => t,
|
|
||||||
Err(e) => return protocol::Response::err(request.id, e),
|
|
||||||
};
|
|
||||||
|
|
||||||
match client.get_posts(&token, channel_id, limit).await {
|
|
||||||
Ok(posts) => protocol::Response::ok(
|
|
||||||
request.id,
|
|
||||||
serde_json::json!({
|
|
||||||
"server_id": server_id,
|
|
||||||
"channel_id": channel_id,
|
|
||||||
"posts": posts,
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
Err(e) => protocol::Response::err(request.id, e.into()),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn handle_send_post(&self, request: protocol::Request) -> protocol::Response {
|
|
||||||
let params = match request.params.as_object() {
|
|
||||||
Some(p) => p,
|
|
||||||
None => return protocol_err(request.id, "params must be an object"),
|
|
||||||
};
|
|
||||||
let server_id = get_server_id(params);
|
|
||||||
let channel_id = match params.get("channel_id").and_then(|v| v.as_str()) {
|
|
||||||
Some(id) => id,
|
|
||||||
None => return protocol_err(request.id, "missing channel_id"),
|
|
||||||
};
|
|
||||||
let message = match params.get("message").and_then(|v| v.as_str()) {
|
|
||||||
Some(m) => m,
|
|
||||||
None => return protocol_err(request.id, "missing message"),
|
|
||||||
};
|
|
||||||
let root_id = params.get("root_id").and_then(|v| v.as_str());
|
|
||||||
|
|
||||||
let client = match self.get_client(&server_id) {
|
|
||||||
Ok(c) => c,
|
|
||||||
Err(e) => return protocol::Response::err(request.id, e),
|
|
||||||
};
|
|
||||||
|
|
||||||
let token = match self.get_token(&server_id) {
|
|
||||||
Ok(t) => t,
|
|
||||||
Err(e) => return protocol::Response::err(request.id, e),
|
|
||||||
};
|
|
||||||
|
|
||||||
match client
|
|
||||||
.create_post(&token, channel_id, message, root_id)
|
|
||||||
.await
|
|
||||||
{
|
|
||||||
Ok(post) => protocol::Response::ok(
|
|
||||||
request.id,
|
|
||||||
serde_json::json!({
|
|
||||||
"server_id": server_id,
|
|
||||||
"post": post,
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
Err(e) => protocol::Response::err(request.id, e.into()),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// --- Helpers ---
|
|
||||||
|
|
||||||
fn get_client(&self, server_id: &ServerId) -> Result<MattermostClient, BridgeError> {
|
|
||||||
let conns = self.connections.lock().unwrap();
|
|
||||||
let state = conns
|
|
||||||
.get(server_id)
|
|
||||||
.ok_or_else(|| BridgeError::new(ErrorKind::Unauthorized, "not connected"))?;
|
|
||||||
|
|
||||||
let ca_path = state.ca_file.as_ref().map(PathBuf::from);
|
|
||||||
MattermostClient::new(state.url.clone(), ca_path.as_deref())
|
|
||||||
.map_err(|e| BridgeError::new(ErrorKind::InternalError, e.to_string()))
|
|
||||||
}
|
|
||||||
|
|
||||||
fn get_token(&self, server_id: &ServerId) -> Result<String, BridgeError> {
|
|
||||||
let conns = self.connections.lock().unwrap();
|
|
||||||
conns
|
|
||||||
.get(server_id)
|
|
||||||
.map(|s| s.token.clone())
|
|
||||||
.ok_or_else(|| BridgeError::new(ErrorKind::Unauthorized, "not connected"))
|
|
||||||
}
|
|
||||||
|
|
||||||
fn get_user_id(&self, server_id: &ServerId) -> Result<mm_core::UserId, BridgeError> {
|
|
||||||
let conns = self.connections.lock().unwrap();
|
|
||||||
conns
|
|
||||||
.get(server_id)
|
|
||||||
.map(|s| s.user.id.clone())
|
|
||||||
.ok_or_else(|| BridgeError::new(ErrorKind::Unauthorized, "not connected"))
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn do_login(
|
|
||||||
&self,
|
|
||||||
url: &str,
|
|
||||||
login: &str,
|
|
||||||
pass: &str,
|
|
||||||
ca: Option<&str>,
|
|
||||||
) -> Result<String, BridgeError> {
|
|
||||||
let ca_path = ca.map(PathBuf::from);
|
|
||||||
let client = MattermostClient::new(url.to_string(), ca_path.as_deref())
|
|
||||||
.map_err(|e| BridgeError::new(ErrorKind::InternalError, e.to_string()))?;
|
|
||||||
client.login(login, pass).await.map_err(Into::into)
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn do_get_me(
|
|
||||||
&self,
|
|
||||||
url: &str,
|
|
||||||
token: &str,
|
|
||||||
ca: Option<&str>,
|
|
||||||
) -> Result<User, BridgeError> {
|
|
||||||
let ca_path = ca.map(PathBuf::from);
|
|
||||||
let client = MattermostClient::new(url.to_string(), ca_path.as_deref())
|
|
||||||
.map_err(|e| BridgeError::new(ErrorKind::InternalError, e.to_string()))?;
|
|
||||||
client.get_me(token).await.map_err(Into::into)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub async fn response_line(&self, line: &str) -> String {
|
pub async fn response_line(&self, line: &str) -> String {
|
||||||
let response = match protocol::parse_request(line) {
|
let response = match protocol::parse_request(line) {
|
||||||
Ok(request) => self.handle_request(request).await,
|
Ok(request) => self.handle_request(request).await,
|
||||||
@@ -356,42 +54,6 @@ impl App {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn protocol_err(id: impl Into<String>, msg: &str) -> protocol::Response {
|
|
||||||
protocol::Response::err(id, BridgeError::new(ErrorKind::InvalidRequest, msg))
|
|
||||||
}
|
|
||||||
|
|
||||||
fn get_server_id(params: &serde_json::Map<String, serde_json::Value>) -> ServerId {
|
|
||||||
params
|
|
||||||
.get("server_id")
|
|
||||||
.and_then(|v| v.as_str())
|
|
||||||
.map(ServerId::new)
|
|
||||||
.unwrap_or_else(|| ServerId::new("default"))
|
|
||||||
}
|
|
||||||
|
|
||||||
fn save_token_and_config(
|
|
||||||
data_dir: &Path,
|
|
||||||
server_id: &ServerId,
|
|
||||||
token: &str,
|
|
||||||
url: &str,
|
|
||||||
) -> Result<(), protocol::Response> {
|
|
||||||
let token_store = TokenStore::new(data_dir);
|
|
||||||
let server_store = ServerStore::new(data_dir);
|
|
||||||
|
|
||||||
token_store
|
|
||||||
.save(server_id, token)
|
|
||||||
.map_err(|e| protocol::Response::err("req", e))?;
|
|
||||||
|
|
||||||
let config = ServerConfig {
|
|
||||||
server_id: server_id.clone(),
|
|
||||||
url: url.to_string(),
|
|
||||||
};
|
|
||||||
server_store
|
|
||||||
.save(&config)
|
|
||||||
.map_err(|e| protocol::Response::err("req", e))?;
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
fn fallback_error_line(id: &str, error: BridgeError) -> String {
|
fn fallback_error_line(id: &str, error: BridgeError) -> String {
|
||||||
let response = protocol::Response::err(id, error);
|
let response = protocol::Response::err(id, error);
|
||||||
let value = serde_json::to_value(response).unwrap_or_else(|_| {
|
let value = serde_json::to_value(response).unwrap_or_else(|_| {
|
||||||
|
|||||||
@@ -0,0 +1,73 @@
|
|||||||
|
use mm_client::ws::WsConnection;
|
||||||
|
use mm_core::{BridgeError, ErrorKind, ServerId, User};
|
||||||
|
use std::collections::HashMap;
|
||||||
|
use std::sync::{Arc, Mutex};
|
||||||
|
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct ConnectionState {
|
||||||
|
pub user: User,
|
||||||
|
pub token: String,
|
||||||
|
pub url: String,
|
||||||
|
#[allow(dead_code)]
|
||||||
|
pub ca_file: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct AppState {
|
||||||
|
connections: Arc<Mutex<HashMap<ServerId, ConnectionState>>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl AppState {
|
||||||
|
pub fn new() -> Self {
|
||||||
|
Self {
|
||||||
|
connections: Arc::new(Mutex::new(HashMap::new())),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn get_connection(&self, server_id: &ServerId) -> Result<ConnectionState, BridgeError> {
|
||||||
|
self.connections
|
||||||
|
.lock()
|
||||||
|
.unwrap()
|
||||||
|
.get(server_id)
|
||||||
|
.cloned()
|
||||||
|
.ok_or_else(|| BridgeError::new(ErrorKind::Unauthorized, "not connected"))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn add_connection(&self, server_id: ServerId, state: ConnectionState) {
|
||||||
|
self.connections.lock().unwrap().insert(server_id, state);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn start_ws(&self, server_id: &ServerId) -> Result<(), BridgeError> {
|
||||||
|
let state = self.get_connection(server_id)?;
|
||||||
|
let sid = server_id.clone();
|
||||||
|
|
||||||
|
tokio::spawn(async move {
|
||||||
|
match WsConnection::new(&state.url, &state.token).await {
|
||||||
|
Ok(mut ws) => {
|
||||||
|
tracing::info!(server_id = %sid, "WebSocket connected");
|
||||||
|
loop {
|
||||||
|
match ws.next_event().await {
|
||||||
|
Ok(Some(event_data)) => {
|
||||||
|
tracing::debug!(server_id = %sid, "WS Event: {}", event_data);
|
||||||
|
// TODO: Fan out to Emacs clients
|
||||||
|
}
|
||||||
|
Ok(None) => {
|
||||||
|
tracing::warn!(server_id = %sid, "WebSocket closed");
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
Err(e) => {
|
||||||
|
tracing::error!(server_id = %sid, "WS Error: {}", e);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Err(e) => {
|
||||||
|
tracing::error!(server_id = %sid, "WS Connect failed: {}", e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -13,6 +13,9 @@ serde_json.workspace = true
|
|||||||
tokio.workspace = true
|
tokio.workspace = true
|
||||||
tracing.workspace = true
|
tracing.workspace = true
|
||||||
thiserror.workspace = true
|
thiserror.workspace = true
|
||||||
|
tokio-tungstenite = { version = "0.26", features = ["rustls-tls-native-roots"] }
|
||||||
|
futures-util = "0.3"
|
||||||
|
url = "2.5"
|
||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
tempfile = "3"
|
tempfile = "3"
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
use crate::error::ClientError;
|
use crate::error::ClientError;
|
||||||
use crate::tls;
|
use crate::tls;
|
||||||
use mm_core::{ChannelId, Post, Team, User}; // Добавим Post и Team в mm-core позже
|
use mm_core::{Channel, ChannelId, Post, User};
|
||||||
use reqwest::header::AUTHORIZATION;
|
use reqwest::header::AUTHORIZATION;
|
||||||
use std::path::Path;
|
use std::path::Path;
|
||||||
|
|
||||||
@@ -34,9 +34,8 @@ impl MattermostClient {
|
|||||||
.map_err(ClientError::Http)?;
|
.map_err(ClientError::Http)?;
|
||||||
|
|
||||||
if !response.status().is_success() {
|
if !response.status().is_success() {
|
||||||
return handle_api_error_string(response)
|
let err = api_error(response).await;
|
||||||
.await
|
return Err(err);
|
||||||
.map(|_| unreachable!());
|
|
||||||
}
|
}
|
||||||
|
|
||||||
let token = response
|
let token = response
|
||||||
@@ -60,15 +59,15 @@ impl MattermostClient {
|
|||||||
.map_err(ClientError::Http)?;
|
.map_err(ClientError::Http)?;
|
||||||
|
|
||||||
if !response.status().is_success() {
|
if !response.status().is_success() {
|
||||||
return handle_api_error_user(response).await;
|
return Err(api_error(response).await);
|
||||||
}
|
}
|
||||||
|
|
||||||
let user: User = response.json().await.map_err(ClientError::Http)?;
|
let user: User = response.json().await.map_err(ClientError::Http)?;
|
||||||
Ok(user)
|
Ok(user)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn get_teams(&self, token: &str) -> Result<Vec<Team>, ClientError> {
|
pub async fn get_teams(&self, token: &str) -> Result<Vec<mm_core::Team>, ClientError> {
|
||||||
let url = format!("{}/api/v4/teams", self.base_url);
|
let url = format!("{}/api/v4/users/me/teams", self.base_url);
|
||||||
let response = self
|
let response = self
|
||||||
.client
|
.client
|
||||||
.get(&url)
|
.get(&url)
|
||||||
@@ -78,13 +77,31 @@ impl MattermostClient {
|
|||||||
.map_err(ClientError::Http)?;
|
.map_err(ClientError::Http)?;
|
||||||
|
|
||||||
if !response.status().is_success() {
|
if !response.status().is_success() {
|
||||||
return handle_api_error_vec(response).await;
|
return Err(api_error(response).await);
|
||||||
}
|
}
|
||||||
|
|
||||||
let teams: Vec<Team> = response.json().await.map_err(ClientError::Http)?;
|
let teams: Vec<mm_core::Team> = response.json().await.map_err(ClientError::Http)?;
|
||||||
Ok(teams)
|
Ok(teams)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub async fn get_my_channels(&self, token: &str) -> Result<Vec<Channel>, ClientError> {
|
||||||
|
let url = format!("{}/api/v4/users/me/channels", self.base_url);
|
||||||
|
let response = self
|
||||||
|
.client
|
||||||
|
.get(&url)
|
||||||
|
.header(AUTHORIZATION, format!("Bearer {}", token))
|
||||||
|
.send()
|
||||||
|
.await
|
||||||
|
.map_err(ClientError::Http)?;
|
||||||
|
|
||||||
|
if !response.status().is_success() {
|
||||||
|
return Err(api_error(response).await);
|
||||||
|
}
|
||||||
|
|
||||||
|
let channels: Vec<Channel> = response.json().await.map_err(ClientError::Http)?;
|
||||||
|
Ok(channels)
|
||||||
|
}
|
||||||
|
|
||||||
pub async fn create_direct_channel(
|
pub async fn create_direct_channel(
|
||||||
&self,
|
&self,
|
||||||
token: &str,
|
token: &str,
|
||||||
@@ -101,7 +118,7 @@ impl MattermostClient {
|
|||||||
.map_err(ClientError::Http)?;
|
.map_err(ClientError::Http)?;
|
||||||
|
|
||||||
if !response.status().is_success() {
|
if !response.status().is_success() {
|
||||||
return handle_api_error_channel(response).await;
|
return Err(api_error(response).await);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(serde::Deserialize)]
|
#[derive(serde::Deserialize)]
|
||||||
@@ -113,16 +130,21 @@ impl MattermostClient {
|
|||||||
Ok(ChannelId::new(ch.id))
|
Ok(ChannelId::new(ch.id))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Get posts for a channel. `before` = oldest known post id for pagination.
|
||||||
pub async fn get_posts(
|
pub async fn get_posts(
|
||||||
&self,
|
&self,
|
||||||
token: &str,
|
token: &str,
|
||||||
channel_id: &str,
|
channel_id: &str,
|
||||||
limit: u32,
|
limit: u32,
|
||||||
|
before: Option<&str>,
|
||||||
) -> Result<Vec<Post>, ClientError> {
|
) -> Result<Vec<Post>, ClientError> {
|
||||||
let url = format!(
|
let mut url = format!(
|
||||||
"{}/api/v4/channels/{}/posts?page=0&per_page={}",
|
"{}/api/v4/channels/{}/posts?per_page={}",
|
||||||
self.base_url, channel_id, limit
|
self.base_url, channel_id, limit
|
||||||
);
|
);
|
||||||
|
if let Some(b) = before {
|
||||||
|
url.push_str(&format!("&before={}", b));
|
||||||
|
}
|
||||||
|
|
||||||
let response = self
|
let response = self
|
||||||
.client
|
.client
|
||||||
@@ -133,10 +155,9 @@ impl MattermostClient {
|
|||||||
.map_err(ClientError::Http)?;
|
.map_err(ClientError::Http)?;
|
||||||
|
|
||||||
if !response.status().is_success() {
|
if !response.status().is_success() {
|
||||||
return handle_api_error_vec(response).await;
|
return Err(api_error(response).await);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Mattermost returns { order: [], posts: {} }
|
|
||||||
#[derive(serde::Deserialize)]
|
#[derive(serde::Deserialize)]
|
||||||
struct PostsResponse {
|
struct PostsResponse {
|
||||||
order: Vec<String>,
|
order: Vec<String>,
|
||||||
@@ -145,16 +166,13 @@ impl MattermostClient {
|
|||||||
|
|
||||||
let data: PostsResponse = response.json().await.map_err(ClientError::Http)?;
|
let data: PostsResponse = response.json().await.map_err(ClientError::Http)?;
|
||||||
|
|
||||||
// Normalize to ordered vector
|
|
||||||
let mut posts: Vec<Post> = data
|
let mut posts: Vec<Post> = data
|
||||||
.order
|
.order
|
||||||
.iter()
|
.iter()
|
||||||
.filter_map(|id| data.posts.get(id).cloned())
|
.filter_map(|id| data.posts.get(id).cloned())
|
||||||
.collect();
|
.collect();
|
||||||
|
|
||||||
// Sort ascending by create_at for display
|
|
||||||
posts.sort_by_key(|p| p.create_at);
|
posts.sort_by_key(|p| p.create_at);
|
||||||
|
|
||||||
Ok(posts)
|
Ok(posts)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -186,7 +204,7 @@ impl MattermostClient {
|
|||||||
.map_err(ClientError::Http)?;
|
.map_err(ClientError::Http)?;
|
||||||
|
|
||||||
if !response.status().is_success() {
|
if !response.status().is_success() {
|
||||||
return handle_api_error_post(response).await;
|
return Err(api_error(response).await);
|
||||||
}
|
}
|
||||||
|
|
||||||
let post: Post = response.json().await.map_err(ClientError::Http)?;
|
let post: Post = response.json().await.map_err(ClientError::Http)?;
|
||||||
@@ -194,39 +212,23 @@ impl MattermostClient {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// --- Helpers for error handling ---
|
async fn api_error(response: reqwest::Response) -> ClientError {
|
||||||
|
|
||||||
async fn handle_api_error_string(response: reqwest::Response) -> Result<String, ClientError> {
|
|
||||||
let status = response.status().as_u16();
|
let status = response.status().as_u16();
|
||||||
let body = response.text().await.unwrap_or_default();
|
let body = response.text().await.unwrap_or_default();
|
||||||
|
|
||||||
#[derive(serde::Deserialize)]
|
#[derive(serde::Deserialize)]
|
||||||
struct MmError {
|
struct MmError {
|
||||||
id: String,
|
id: String,
|
||||||
message: String,
|
message: String,
|
||||||
}
|
}
|
||||||
let err_msg = serde_json::from_str::<MmError>(&body)
|
|
||||||
.map(|e| format!("{} ({})", e.message, e.id))
|
|
||||||
.unwrap_or_else(|_| body.clone());
|
|
||||||
Err(ClientError::Api {
|
|
||||||
id: "api_error".into(),
|
|
||||||
message: err_msg,
|
|
||||||
status_code: status,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn handle_api_error_user(response: reqwest::Response) -> Result<User, ClientError> {
|
let (id, message) = serde_json::from_str::<MmError>(&body)
|
||||||
handle_api_error_string(response).await?;
|
.map(|e| (e.id, e.message))
|
||||||
unreachable!()
|
.unwrap_or_else(|_| ("api_error".to_string(), body));
|
||||||
}
|
|
||||||
async fn handle_api_error_vec<T>(response: reqwest::Response) -> Result<Vec<T>, ClientError> {
|
ClientError::Api {
|
||||||
handle_api_error_string(response).await?;
|
id,
|
||||||
unreachable!()
|
message,
|
||||||
}
|
status_code: status,
|
||||||
async fn handle_api_error_channel(response: reqwest::Response) -> Result<ChannelId, ClientError> {
|
}
|
||||||
handle_api_error_string(response).await?;
|
|
||||||
unreachable!()
|
|
||||||
}
|
|
||||||
async fn handle_api_error_post(response: reqwest::Response) -> Result<Post, ClientError> {
|
|
||||||
handle_api_error_string(response).await?;
|
|
||||||
unreachable!()
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1 +1,78 @@
|
|||||||
//! WebSocket client.
|
use crate::error::ClientError;
|
||||||
|
use futures_util::{SinkExt, StreamExt};
|
||||||
|
use tokio_tungstenite::{connect_async_tls_with_config, tungstenite::Message};
|
||||||
|
use url::Url;
|
||||||
|
|
||||||
|
pub struct WsConnection {
|
||||||
|
stream: tokio_tungstenite::WebSocketStream<
|
||||||
|
tokio_tungstenite::MaybeTlsStream<tokio::net::TcpStream>,
|
||||||
|
>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl WsConnection {
|
||||||
|
pub async fn new(base_url: &str, token: &str) -> Result<Self, ClientError> {
|
||||||
|
tracing::info!("Connecting to WebSocket at {}", base_url);
|
||||||
|
|
||||||
|
let mut url = Url::parse(base_url).map_err(|e| ClientError::Tls(e.to_string()))?;
|
||||||
|
let scheme = if url.scheme() == "https" { "wss" } else { "ws" };
|
||||||
|
url.set_scheme(scheme)
|
||||||
|
.map_err(|_| ClientError::Tls("Invalid scheme".into()))?;
|
||||||
|
url.set_path("/api/v4/websocket");
|
||||||
|
|
||||||
|
let (stream, _) = connect_async_tls_with_config(url.to_string(), None, false, None)
|
||||||
|
.await
|
||||||
|
.map_err(|e| ClientError::Tls(format!("WS connect failed: {}", e)))?;
|
||||||
|
|
||||||
|
let mut conn = Self { stream };
|
||||||
|
tracing::debug!("Sending authentication challenge");
|
||||||
|
conn.authenticate(token).await?;
|
||||||
|
|
||||||
|
tracing::debug!("Waiting for hello event");
|
||||||
|
conn.wait_for_hello().await?;
|
||||||
|
tracing::info!("WebSocket authenticated successfully");
|
||||||
|
|
||||||
|
Ok(conn)
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn authenticate(&mut self, token: &str) -> Result<(), ClientError> {
|
||||||
|
let auth_msg = serde_json::json!({
|
||||||
|
"seq": 1,
|
||||||
|
"action": "authentication_challenge",
|
||||||
|
"data": { "token": token }
|
||||||
|
});
|
||||||
|
|
||||||
|
self.stream
|
||||||
|
.send(Message::Text(auth_msg.to_string().into()))
|
||||||
|
.await
|
||||||
|
.map_err(|e| ClientError::Tls(format!("Auth send failed: {}", e)))?;
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn wait_for_hello(&mut self) -> Result<(), ClientError> {
|
||||||
|
while let Some(msg) = self.stream.next().await {
|
||||||
|
match msg {
|
||||||
|
Ok(Message::Text(text)) => {
|
||||||
|
if text.contains("\"event\":\"hello\"") {
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(_) => continue,
|
||||||
|
Err(e) => return Err(ClientError::Tls(format!("WS read error: {}", e))),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Err(ClientError::Tls("Connection closed before hello".into()))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn next_event(&mut self) -> Result<Option<String>, ClientError> {
|
||||||
|
while let Some(msg) = self.stream.next().await {
|
||||||
|
match msg {
|
||||||
|
Ok(Message::Text(text)) => return Ok(Some(text.to_string())),
|
||||||
|
Ok(Message::Close(_)) => return Ok(None),
|
||||||
|
Ok(_) => continue,
|
||||||
|
Err(e) => return Err(ClientError::Tls(format!("WS read error: {}", e))),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(None)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -9,5 +9,5 @@ pub mod model;
|
|||||||
pub use error::{BridgeError, ErrorKind};
|
pub use error::{BridgeError, ErrorKind};
|
||||||
pub use ids::{ChannelId, PostId, ServerId, TeamId, UserId};
|
pub use ids::{ChannelId, PostId, ServerId, TeamId, UserId};
|
||||||
pub use model::{
|
pub use model::{
|
||||||
BridgeInfo, BridgeState, BridgeStatus, Post, ServerConfig, ServerSummary, Team, User,
|
BridgeInfo, BridgeState, BridgeStatus, Channel, Post, ServerConfig, ServerSummary, Team, User,
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -65,6 +65,17 @@ pub struct Team {
|
|||||||
pub display_name: String,
|
pub display_name: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Normalized Mattermost channel. Only fields needed by the MVP UI.
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
|
pub struct Channel {
|
||||||
|
pub id: ChannelId,
|
||||||
|
pub team_id: TeamId,
|
||||||
|
#[serde(rename = "type")]
|
||||||
|
pub channel_type: String, // "O" (Open), "P" (Private), "D" (Direct), "G" (Group)
|
||||||
|
pub display_name: String,
|
||||||
|
pub name: String,
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
pub struct Post {
|
pub struct Post {
|
||||||
pub id: PostId,
|
pub id: PostId,
|
||||||
|
|||||||
@@ -0,0 +1,45 @@
|
|||||||
|
;;; mattermost-custom.el --- Customization options for mattermost.el -*- lexical-binding: t; -*-
|
||||||
|
|
||||||
|
(defgroup mattermost nil
|
||||||
|
"Mattermost client for Emacs."
|
||||||
|
:group 'applications)
|
||||||
|
|
||||||
|
(defcustom mattermost-bridge-host "127.0.0.1"
|
||||||
|
"Host where the Mattermost bridge is listening."
|
||||||
|
:type 'string
|
||||||
|
:group 'mattermost)
|
||||||
|
|
||||||
|
(defcustom mattermost-bridge-port 8765
|
||||||
|
"Port where the Mattermost bridge is listening."
|
||||||
|
:type 'integer
|
||||||
|
:group 'mattermost)
|
||||||
|
|
||||||
|
(defcustom mattermost-thread-display 'separate-buffer
|
||||||
|
"How to display threads.
|
||||||
|
If `separate-buffer', open a new buffer for each thread.
|
||||||
|
If `inline', show replies in the main buffer."
|
||||||
|
:type '(choice (const separate-buffer)
|
||||||
|
(const inline))
|
||||||
|
:group 'mattermost)
|
||||||
|
|
||||||
|
(defcustom mattermost-server-url ""
|
||||||
|
"URL of your Mattermost server (e.g. https://mattermost.local)."
|
||||||
|
:type 'string
|
||||||
|
:group 'mattermost)
|
||||||
|
|
||||||
|
(defcustom mattermost-login-id ""
|
||||||
|
"Your Mattermost login ID or email."
|
||||||
|
:type 'string
|
||||||
|
:group 'mattermost)
|
||||||
|
|
||||||
|
(defcustom mattermost-password ""
|
||||||
|
"Your Mattermost password. Consider using auth-source instead for security."
|
||||||
|
:type 'string
|
||||||
|
:group 'mattermost)
|
||||||
|
|
||||||
|
(defcustom mattermost-server-id "work"
|
||||||
|
"Internal server identifier used for token storage."
|
||||||
|
:type 'string
|
||||||
|
:group 'mattermost)
|
||||||
|
|
||||||
|
(provide 'mattermost-custom)
|
||||||
|
|||||||
@@ -0,0 +1,116 @@
|
|||||||
|
;;; mattermost-dashboard.el --- Dashboard and channel list UI -*- lexical-binding: t; -*-
|
||||||
|
|
||||||
|
(require 'mattermost-custom)
|
||||||
|
(require 'mattermost-protocol)
|
||||||
|
|
||||||
|
(defvar mattermost--current-server-id nil
|
||||||
|
"Current server ID for the dashboard buffer.")
|
||||||
|
|
||||||
|
(defvar mattermost-dashboard-mode-map
|
||||||
|
(let ((map (make-sparse-keymap)))
|
||||||
|
(define-key map (kbd "RET") #'mattermost-dashboard-open-channel)
|
||||||
|
(define-key map (kbd "g") #'mattermost-dashboard-refresh)
|
||||||
|
map)
|
||||||
|
"Keymap for `mattermost-dashboard-mode`.")
|
||||||
|
|
||||||
|
(define-derived-mode mattermost-dashboard-mode special-mode "Mattermost-Dashboard"
|
||||||
|
"Major mode for viewing Mattermost channels list.
|
||||||
|
\\{mattermost-dashboard-mode-map}"
|
||||||
|
(setq buffer-read-only t)
|
||||||
|
(setq truncate-lines t))
|
||||||
|
|
||||||
|
(defun mattermost-ensure-connected (callback)
|
||||||
|
"Ensure connection to the bridge, prompting for missing credentials.
|
||||||
|
Calls CALLBACK with server-id on success. Password is never saved to disk."
|
||||||
|
(let* ((url (if (string= mattermost-server-url "")
|
||||||
|
(read-string "Mattermost URL (e.g., https://mattermost.local): ")
|
||||||
|
mattermost-server-url))
|
||||||
|
(login (if (string= mattermost-login-id "")
|
||||||
|
(read-string "Login ID or Email: ")
|
||||||
|
mattermost-login-id))
|
||||||
|
(password (read-passwd "Password (or PAT token): "))
|
||||||
|
(server-id mattermost-server-id))
|
||||||
|
|
||||||
|
;; Сохраняем только не-секретные настройки, если они были пустыми
|
||||||
|
(when (string= mattermost-server-url "")
|
||||||
|
(customize-save-variable 'mattermost-server-url url))
|
||||||
|
(when (string= mattermost-login-id "")
|
||||||
|
(customize-save-variable 'mattermost-login-id login))
|
||||||
|
|
||||||
|
(message "[MM-DEBUG] Connecting to %s as %s (password masked)" url login)
|
||||||
|
(mattermost--send-request
|
||||||
|
"connect"
|
||||||
|
(list :server_id server-id
|
||||||
|
:url url
|
||||||
|
:login_id login
|
||||||
|
:password password)
|
||||||
|
(lambda (response)
|
||||||
|
(if (plist-get response :ok)
|
||||||
|
(progn
|
||||||
|
(message "[MM] Connected successfully.")
|
||||||
|
(funcall callback server-id))
|
||||||
|
(message "[MM] Connect failed: %S" (plist-get response :error)))))))
|
||||||
|
|
||||||
|
(defun mattermost-dashboard ()
|
||||||
|
"Open the Mattermost dashboard showing available channels."
|
||||||
|
(interactive)
|
||||||
|
(mattermost-ensure-connected
|
||||||
|
(lambda (server-id)
|
||||||
|
(mattermost--send-request
|
||||||
|
"list_channels"
|
||||||
|
(list :server_id server-id)
|
||||||
|
(lambda (response)
|
||||||
|
(if (plist-get response :ok)
|
||||||
|
(mattermost--render-dashboard
|
||||||
|
server-id
|
||||||
|
(plist-get (plist-get response :result) :channels))
|
||||||
|
(message "[MM] Failed to list channels: %S" (plist-get response :error))))))))
|
||||||
|
|
||||||
|
(defun mattermost--render-dashboard (server-id channels)
|
||||||
|
"Render CHANNELS in a new Mattermost Dashboard buffer."
|
||||||
|
(let ((buf (get-buffer-create "*Mattermost Dashboard*")))
|
||||||
|
(with-current-buffer buf
|
||||||
|
(erase-buffer)
|
||||||
|
(mattermost-dashboard-mode)
|
||||||
|
(setq-local mattermost--current-server-id server-id)
|
||||||
|
(setq-local mattermost--channels channels)
|
||||||
|
|
||||||
|
(insert "Mattermost Channels\n")
|
||||||
|
(insert "==================\n\n")
|
||||||
|
|
||||||
|
(dolist (ch channels)
|
||||||
|
(let ((name (or (plist-get ch :display_name) "Unknown"))
|
||||||
|
(type (or (plist-get ch :channel_type) "?"))
|
||||||
|
(id (plist-get ch :id)))
|
||||||
|
(insert (format "[%s] %s (ID: %s)\n" type name id))))
|
||||||
|
|
||||||
|
(goto-char (point-min)))
|
||||||
|
(switch-to-buffer buf)))
|
||||||
|
|
||||||
|
(defun mattermost-dashboard-refresh ()
|
||||||
|
"Refresh the channel list in the current dashboard buffer."
|
||||||
|
(interactive)
|
||||||
|
(let ((server-id mattermost--current-server-id))
|
||||||
|
(unless server-id
|
||||||
|
(error "No server ID associated with this buffer"))
|
||||||
|
(message "[MM-DEBUG] Refreshing channels...")
|
||||||
|
(mattermost--send-request
|
||||||
|
"list_channels"
|
||||||
|
(list :server_id server-id)
|
||||||
|
(lambda (response)
|
||||||
|
(if (plist-get response :ok)
|
||||||
|
(mattermost--render-dashboard
|
||||||
|
server-id
|
||||||
|
(plist-get (plist-get response :result) :channels))
|
||||||
|
(message "[MM] Refresh failed: %S" (plist-get response :error)))))))
|
||||||
|
|
||||||
|
(defun mattermost-dashboard-open-channel ()
|
||||||
|
"Open the channel under point."
|
||||||
|
(interactive)
|
||||||
|
(let ((line (thing-at-point 'line t)))
|
||||||
|
(if (string-match "ID: \\([a-z0-9]+\\)" line)
|
||||||
|
(let ((channel-id (match-string 1 line)))
|
||||||
|
(message "[MM] Opening channel: %s (TODO: implement channel buffer)" channel-id))
|
||||||
|
(message "[MM] No channel ID found on this line."))))
|
||||||
|
|
||||||
|
(provide 'mattermost-dashboard)
|
||||||
@@ -0,0 +1,234 @@
|
|||||||
|
;;; mattermost-dm.el --- Direct Message handling -*- lexical-binding: t; -*-
|
||||||
|
|
||||||
|
(require 'mattermost-protocol)
|
||||||
|
|
||||||
|
(defvar mattermost-self-channel-id nil
|
||||||
|
"Channel ID for the current user's self-DM.")
|
||||||
|
|
||||||
|
(defvar mattermost-self-buffer nil
|
||||||
|
"Buffer showing the self-DM history.")
|
||||||
|
|
||||||
|
(defvar mattermost--oldest-post-id nil
|
||||||
|
"ID of the oldest loaded post, used for pagination.")
|
||||||
|
|
||||||
|
(defvar mattermost--history-limit 10
|
||||||
|
"Number of posts loaded per page.")
|
||||||
|
|
||||||
|
(defun mattermost-open-self-dm ()
|
||||||
|
"Open or switch to the Self-DM buffer. Auto-connects if needed."
|
||||||
|
(interactive)
|
||||||
|
(mattermost--ensure-connected))
|
||||||
|
|
||||||
|
(defun mattermost--ensure-connected ()
|
||||||
|
"Connect to bridge and Mattermost if not already connected, then open DM."
|
||||||
|
(mattermost-connect-to-bridge)
|
||||||
|
(if mattermost-self-channel-id
|
||||||
|
(progn
|
||||||
|
(mattermost-switch-to-self-dm)
|
||||||
|
(mattermost-load-history))
|
||||||
|
(let* ((env-pass (getenv "MM_PASSWORD"))
|
||||||
|
(url (or (and (stringp mattermost-server-url)
|
||||||
|
(not (string-empty-p mattermost-server-url))
|
||||||
|
mattermost-server-url)
|
||||||
|
(read-string "Mattermost URL: ")))
|
||||||
|
(login (or (and (stringp mattermost-login-id)
|
||||||
|
(not (string-empty-p mattermost-login-id))
|
||||||
|
mattermost-login-id)
|
||||||
|
(read-string "Login ID: ")))
|
||||||
|
(password (or (and (stringp mattermost-password)
|
||||||
|
(not (string-empty-p mattermost-password))
|
||||||
|
mattermost-password)
|
||||||
|
env-pass
|
||||||
|
(read-passwd "Password: "))))
|
||||||
|
(customize-save-variable 'mattermost-server-url url)
|
||||||
|
(customize-save-variable 'mattermost-login-id login)
|
||||||
|
(setq mattermost-password password)
|
||||||
|
(message "[MM] Connecting to %s as %s..." url login)
|
||||||
|
(mattermost--send-request
|
||||||
|
"connect"
|
||||||
|
(list :server_id mattermost-server-id
|
||||||
|
:url url
|
||||||
|
:login_id login
|
||||||
|
:password password)
|
||||||
|
#'mattermost--on-connect-response))))
|
||||||
|
|
||||||
|
(defun mattermost--on-connect-response (resp)
|
||||||
|
"Handle response from connect request."
|
||||||
|
(if (equal (plist-get resp :ok) t)
|
||||||
|
(progn
|
||||||
|
(message "[MM] Connected successfully!")
|
||||||
|
(mattermost-init-self-dm))
|
||||||
|
(let ((err (plist-get resp :error)))
|
||||||
|
(message "[MM] Connection FAILED: %s"
|
||||||
|
(if (listp err) (mm--extract err "message") err)))))
|
||||||
|
|
||||||
|
(defun mattermost-init-self-dm ()
|
||||||
|
"Request Self-DM channel from bridge."
|
||||||
|
(mattermost--send-request
|
||||||
|
"open_self_dm"
|
||||||
|
(list :server_id mattermost-server-id)
|
||||||
|
#'mattermost--on-self-dm-response))
|
||||||
|
|
||||||
|
(defun mattermost--on-self-dm-response (resp)
|
||||||
|
"Handle response from open_self_dm request."
|
||||||
|
(if (equal (plist-get resp :ok) t)
|
||||||
|
(let* ((result (plist-get resp :result))
|
||||||
|
(channel (plist-get result :channel))
|
||||||
|
(id (plist-get channel :id)))
|
||||||
|
(setq mattermost-self-channel-id id)
|
||||||
|
(mattermost-switch-to-self-dm)
|
||||||
|
(mattermost-load-history))
|
||||||
|
(message "[MM] Failed to open Self-DM: %s" (plist-get resp :error))))
|
||||||
|
|
||||||
|
(defun mattermost-switch-to-self-dm ()
|
||||||
|
"Switch to the Self-DM buffer."
|
||||||
|
(let ((buf-name "*Mattermost[work]/DM:self*"))
|
||||||
|
(setq mattermost-self-buffer (get-buffer-create buf-name))
|
||||||
|
(switch-to-buffer mattermost-self-buffer)
|
||||||
|
(mattermost-mode)))
|
||||||
|
|
||||||
|
(defun mattermost-load-history ()
|
||||||
|
"Load the latest page of self-DM history."
|
||||||
|
(interactive)
|
||||||
|
(unless (and mattermost-self-channel-id
|
||||||
|
(not (string-empty-p mattermost-self-channel-id)))
|
||||||
|
(user-error "No self-DM channel yet"))
|
||||||
|
(setq mattermost--oldest-post-id nil)
|
||||||
|
(mattermost--send-request
|
||||||
|
"get_history"
|
||||||
|
(list :server_id mattermost-server-id
|
||||||
|
:channel_id mattermost-self-channel-id
|
||||||
|
:limit mattermost--history-limit)
|
||||||
|
#'mattermost--on-history-response))
|
||||||
|
|
||||||
|
(defun mattermost-load-earlier ()
|
||||||
|
"Load the previous page of history (older messages)."
|
||||||
|
(interactive)
|
||||||
|
(unless mattermost--oldest-post-id
|
||||||
|
(user-error "Nothing loaded yet, or no earlier messages"))
|
||||||
|
(mattermost--send-request
|
||||||
|
"get_history"
|
||||||
|
(list :server_id mattermost-server-id
|
||||||
|
:channel_id mattermost-self-channel-id
|
||||||
|
:limit mattermost--history-limit
|
||||||
|
:before mattermost--oldest-post-id)
|
||||||
|
#'mattermost--on-earlier-response))
|
||||||
|
|
||||||
|
(defun mattermost--on-history-response (resp)
|
||||||
|
"Handle initial get_history response."
|
||||||
|
(if (equal (plist-get resp :ok) t)
|
||||||
|
(let ((posts (mm--extract (plist-get resp :result) "posts")))
|
||||||
|
(mattermost--render-history posts t))
|
||||||
|
(message "[MM] Failed to load history: %s" (plist-get resp :error))))
|
||||||
|
|
||||||
|
(defun mattermost--on-earlier-response (resp)
|
||||||
|
"Handle paginated get_history response."
|
||||||
|
(if (equal (plist-get resp :ok) t)
|
||||||
|
(let ((posts (mm--extract (plist-get resp :result) "posts")))
|
||||||
|
(if (and posts (> (length posts) 0))
|
||||||
|
(mattermost--render-history posts nil)
|
||||||
|
(message "[MM] No earlier messages")))
|
||||||
|
(message "[MM] Failed to load earlier: %s" (plist-get resp :error))))
|
||||||
|
|
||||||
|
(defun mattermost--render-history (posts initial)
|
||||||
|
"Render POSTS into the self-DM buffer.
|
||||||
|
If INITIAL, clear the buffer and render the whole page.
|
||||||
|
Otherwise prepend older posts under the header."
|
||||||
|
(unless (buffer-live-p mattermost-self-buffer)
|
||||||
|
(error "Self-DM buffer is gone"))
|
||||||
|
(with-current-buffer mattermost-self-buffer
|
||||||
|
(let ((inhibit-read-only t))
|
||||||
|
(if initial
|
||||||
|
(progn
|
||||||
|
(erase-buffer)
|
||||||
|
(mattermost--insert-header)
|
||||||
|
(dolist (post posts)
|
||||||
|
(mattermost--insert-post post))
|
||||||
|
;; oldest = first post of the ascending page
|
||||||
|
(when posts
|
||||||
|
(setq mattermost--oldest-post-id
|
||||||
|
(mm--extract (car posts) "id"))))
|
||||||
|
;; prepend: go to end of header line
|
||||||
|
(save-excursion
|
||||||
|
(goto-char (point-min))
|
||||||
|
(forward-line 1)
|
||||||
|
(let ((start (point)))
|
||||||
|
(dolist (post posts)
|
||||||
|
(mattermost--insert-post post))
|
||||||
|
(when posts
|
||||||
|
(setq mattermost--oldest-post-id
|
||||||
|
(mm--extract (car posts) "id")))))
|
||||||
|
(message "[MM] Loaded %d earlier messages" (length posts))))))
|
||||||
|
|
||||||
|
(defun mattermost--insert-header ()
|
||||||
|
"Insert buffer header."
|
||||||
|
(insert (format "*Mattermost[work]/DM:self* — %d latest messages\n"
|
||||||
|
mattermost--history-limit))
|
||||||
|
(insert "Press 'l' to load earlier messages, C-c C-c to send.\n\n"))
|
||||||
|
|
||||||
|
(defun mattermost--insert-post (post)
|
||||||
|
"Insert a single POST at point."
|
||||||
|
(let ((msg (mm--extract post "message"))
|
||||||
|
(user-id (mm--extract post "user_id"))
|
||||||
|
(files (mm--extract post "file_ids"))
|
||||||
|
(ts (mm--extract post "create_at")))
|
||||||
|
(insert (format "[%s] %s%s\n"
|
||||||
|
(mattermost--format-time ts)
|
||||||
|
msg
|
||||||
|
(if (and (listp files) (> (length files) 0))
|
||||||
|
(format " [+%d file(s)]" (length files))
|
||||||
|
"")))))
|
||||||
|
|
||||||
|
(defun mattermost--format-time (ms)
|
||||||
|
"Format epoch milliseconds MS as HH:MM."
|
||||||
|
(if (and (numberp ms) (> ms 0))
|
||||||
|
(format-time-string "%H:%M" (seconds-to-time (/ ms 1000)))
|
||||||
|
"??:??"))
|
||||||
|
|
||||||
|
;; ============================================================
|
||||||
|
;; УНИВЕРСАЛЬНАЯ ФУНКЦИЯ ИЗВЛЕЧЕНИЯ ДАННЫХ
|
||||||
|
;; ============================================================
|
||||||
|
|
||||||
|
(defun mm--extract (obj key)
|
||||||
|
"Safely extract KEY from OBJ, handling plists, alists (string/symbol), and hash tables."
|
||||||
|
(let ((key-sym (if (stringp key) (intern key) key))
|
||||||
|
(key-str (if (stringp key) key (symbol-name key)))
|
||||||
|
(key-kw (if (stringp key) (intern (concat ":" key)) (intern (concat ":" (symbol-name key))))))
|
||||||
|
(or (plist-get obj key-kw)
|
||||||
|
(plist-get obj key-sym)
|
||||||
|
(cdr (assq key-sym obj))
|
||||||
|
(cdr (assoc key-str obj))
|
||||||
|
(and (hash-table-p obj) (gethash key-str obj))
|
||||||
|
(and (hash-table-p obj) (gethash key-sym obj))
|
||||||
|
"[NOT FOUND]")))
|
||||||
|
|
||||||
|
;; ============================================================
|
||||||
|
|
||||||
|
(define-derived-mode mattermost-mode text-mode "Mattermost"
|
||||||
|
"Major mode for Mattermost chat buffers."
|
||||||
|
(setq-local comment-start "# ")
|
||||||
|
(setq buffer-read-only nil)
|
||||||
|
(local-set-key (kbd "C-c C-c") #'mattermost-send-message)
|
||||||
|
(local-set-key (kbd "l") #'mattermost-load-earlier))
|
||||||
|
|
||||||
|
(defun mattermost-send-message ()
|
||||||
|
"Send the current line as a message."
|
||||||
|
(interactive)
|
||||||
|
(unless mattermost-self-channel-id
|
||||||
|
(user-error "Not connected"))
|
||||||
|
(let ((msg (buffer-substring (line-beginning-position) (line-end-position))))
|
||||||
|
(mattermost--send-request
|
||||||
|
"send_post"
|
||||||
|
(list :server_id mattermost-server-id
|
||||||
|
:channel_id mattermost-self-channel-id
|
||||||
|
:message msg)
|
||||||
|
#'mattermost--on-send-response)))
|
||||||
|
|
||||||
|
(defun mattermost--on-send-response (_resp)
|
||||||
|
"Handle response after sending a message."
|
||||||
|
(with-current-buffer (or mattermost-self-buffer (current-buffer))
|
||||||
|
(let ((inhibit-read-only t))
|
||||||
|
(delete-region (line-beginning-position) (line-end-position))
|
||||||
|
(insert "\n"))))
|
||||||
|
|
||||||
|
(provide 'mattermost-dm)
|
||||||
|
|||||||
@@ -0,0 +1,91 @@
|
|||||||
|
;;; mattermost-protocol.el --- TCP JSONL protocol handler -*- lexical-binding: t; -*-
|
||||||
|
|
||||||
|
(require 'json)
|
||||||
|
(require 'mattermost-custom)
|
||||||
|
|
||||||
|
(defvar mattermost--process nil
|
||||||
|
"The process object for the bridge connection.")
|
||||||
|
|
||||||
|
(defvar mattermost--pending-requests (make-hash-table :test 'equal)
|
||||||
|
"Hash table of pending requests indexed by ID.")
|
||||||
|
|
||||||
|
(defvar mattermost--input-buffer ""
|
||||||
|
"Accumulator for incomplete TCP chunks.")
|
||||||
|
|
||||||
|
(defun mattermost-connect-to-bridge ()
|
||||||
|
"Connect to the running Rust bridge."
|
||||||
|
(interactive)
|
||||||
|
(when (and mattermost--process (process-live-p mattermost--process))
|
||||||
|
(delete-process mattermost--process))
|
||||||
|
|
||||||
|
(setq mattermost--process
|
||||||
|
(open-network-stream
|
||||||
|
"mattermost-bridge"
|
||||||
|
"*mattermost-log*"
|
||||||
|
mattermost-bridge-host
|
||||||
|
mattermost-bridge-port))
|
||||||
|
|
||||||
|
;; Очищаем буфер при новом подключении
|
||||||
|
(setq mattermost--input-buffer "")
|
||||||
|
|
||||||
|
(set-process-filter mattermost--process #'mattermost--process-filter)
|
||||||
|
(message "[MM-PROTOCOL] Connected to Mattermost bridge."))
|
||||||
|
|
||||||
|
(defun mattermost--process-filter (_proc output)
|
||||||
|
"Handle OUTPUT from the bridge process with proper chunk buffering."
|
||||||
|
;; Добавляем новые данные к накопителю
|
||||||
|
(setq mattermost--input-buffer (concat mattermost--input-buffer output))
|
||||||
|
|
||||||
|
;; Разбиваем по переносам строк
|
||||||
|
(let ((lines (split-string mattermost--input-buffer "\n" t)))
|
||||||
|
;; Последняя строка может быть неполной — сохраняем её на следующий вызов
|
||||||
|
(if (string-suffix-p "\n" output)
|
||||||
|
(setq mattermost--input-buffer "")
|
||||||
|
(setq mattermost--input-buffer (car (last lines)))
|
||||||
|
;; Убираем последний (неполный) элемент из списка для обработки
|
||||||
|
(setq lines (butlast lines)))
|
||||||
|
|
||||||
|
(dolist (line lines)
|
||||||
|
(let ((msg (ignore-errors (json-parse-string line :object-type 'plist))))
|
||||||
|
(if msg
|
||||||
|
(let ((id (plist-get msg :id))
|
||||||
|
(type (plist-get msg :type)))
|
||||||
|
(cond
|
||||||
|
((string= type "response")
|
||||||
|
(let ((cb (gethash id mattermost--pending-requests)))
|
||||||
|
(if cb
|
||||||
|
(progn
|
||||||
|
(funcall cb msg)
|
||||||
|
(remhash id mattermost--pending-requests))
|
||||||
|
(message "[MM-PROTOCOL] WARNING: No callback for id=%s" id))))
|
||||||
|
((string= type "event")
|
||||||
|
(mattermost--handle-event msg))))
|
||||||
|
(message "[MM-PROTOCOL] Failed to parse JSON: %S"
|
||||||
|
(substring line 0 (min 100 (length line)))))))))
|
||||||
|
|
||||||
|
(defun mattermost--send-request (method params callback)
|
||||||
|
"Send a request with METHOD and PARAMS, calling CALLBACK on response."
|
||||||
|
(let* ((id (format "req-%d" (random 100000)))
|
||||||
|
;; 1. Создаем реальный payload для отправки
|
||||||
|
(payload (list :id id :type "request" :method method :params params))
|
||||||
|
(json-str (concat (json-encode payload) "\n"))
|
||||||
|
;; 2. Создаем копию ТОЛЬКО для логирования
|
||||||
|
(safe-params (copy-tree params)))
|
||||||
|
|
||||||
|
;; Маскируем пароль в копии для лога
|
||||||
|
(when (plist-get safe-params :password)
|
||||||
|
(plist-put safe-params :password "***MASKED***"))
|
||||||
|
|
||||||
|
(let ((safe-payload (list :id id :type "request" :method method :params safe-params)))
|
||||||
|
(message "[MM-PROTOCOL] Sending request id=%s method=%s" id method))
|
||||||
|
|
||||||
|
(puthash id callback mattermost--pending-requests)
|
||||||
|
;; Отправляем реальный json-str с настоящим паролем!
|
||||||
|
(process-send-string mattermost--process json-str)))
|
||||||
|
|
||||||
|
(defun mattermost--handle-event (_msg)
|
||||||
|
"Handle an asynchronous event MSG from the bridge."
|
||||||
|
;; TODO: Fan out events to buffers
|
||||||
|
)
|
||||||
|
|
||||||
|
(provide 'mattermost-protocol)
|
||||||
|
|||||||
@@ -0,0 +1,8 @@
|
|||||||
|
;;; mattermost.el --- Emacs client for Mattermost -*- lexical-binding: t; -*-
|
||||||
|
|
||||||
|
(require 'mattermost-custom)
|
||||||
|
(require 'mattermost-protocol)
|
||||||
|
(require 'mattermost-dm)
|
||||||
|
(require 'mattermost-dashboard)
|
||||||
|
|
||||||
|
(provide 'mattermost)
|
||||||
|
|||||||
+15
-12
@@ -1,16 +1,19 @@
|
|||||||
#!/usr/bin/env bash
|
#!/bin/bash
|
||||||
set -euo pipefail
|
# scripts/dev-check.sh
|
||||||
|
# Быстрая проверка Rust-части проекта emacs-mattermost
|
||||||
|
|
||||||
ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
|
set -e
|
||||||
|
|
||||||
cd "${ROOT_DIR}/bridge"
|
# Переходим в директорию с Rust workspace
|
||||||
|
cd "$(dirname "$0")/../bridge"
|
||||||
|
|
||||||
if [[ ! -f Cargo.lock ]]; then
|
echo "==> Running cargo fmt --all..."
|
||||||
echo "Cargo.lock is missing. Generate it first:" >&2
|
cargo fmt --all
|
||||||
echo " cd bridge && cargo generate-lockfile" >&2
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
|
|
||||||
cargo fmt --all -- --check
|
echo "==> Running cargo check --workspace..."
|
||||||
cargo check --workspace --locked
|
cargo check --workspace
|
||||||
cargo test --workspace --locked
|
|
||||||
|
echo "==> Running cargo test --workspace..."
|
||||||
|
cargo test --workspace
|
||||||
|
|
||||||
|
echo "==> All checks passed successfully."
|
||||||
|
|||||||
Reference in New Issue
Block a user