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"
|
||||
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]]
|
||||
name = "bumpalo"
|
||||
version = "3.20.4"
|
||||
@@ -148,8 +157,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"cpufeatures",
|
||||
"rand_core",
|
||||
"cpufeatures 0.3.1",
|
||||
"rand_core 0.10.1",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -184,6 +193,15 @@ version = "1.0.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7f8f80099a98041a3d1622845c271458a2d73e688351bf3cb999266764b81d48"
|
||||
|
||||
[[package]]
|
||||
name = "cpufeatures"
|
||||
version = "0.2.17"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280"
|
||||
dependencies = [
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cpufeatures"
|
||||
version = "0.3.1"
|
||||
@@ -193,6 +211,32 @@ dependencies = [
|
||||
"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]]
|
||||
name = "displaydoc"
|
||||
version = "0.2.7"
|
||||
@@ -291,6 +335,17 @@ version = "0.3.34"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
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]]
|
||||
name = "futures-sink"
|
||||
version = "0.3.34"
|
||||
@@ -310,11 +365,23 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc"
|
||||
dependencies = [
|
||||
"futures-core",
|
||||
"futures-macro",
|
||||
"futures-sink",
|
||||
"futures-task",
|
||||
"pin-project-lite",
|
||||
"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]]
|
||||
name = "getrandom"
|
||||
version = "0.2.17"
|
||||
@@ -328,6 +395,18 @@ dependencies = [
|
||||
"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]]
|
||||
name = "getrandom"
|
||||
version = "0.4.3"
|
||||
@@ -337,8 +416,8 @@ dependencies = [
|
||||
"cfg-if",
|
||||
"js-sys",
|
||||
"libc",
|
||||
"r-efi",
|
||||
"rand_core",
|
||||
"r-efi 6.0.0",
|
||||
"rand_core 0.10.1",
|
||||
"wasm-bindgen",
|
||||
]
|
||||
|
||||
@@ -724,6 +803,7 @@ dependencies = [
|
||||
name = "mm-client"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"futures-util",
|
||||
"mm-core",
|
||||
"reqwest",
|
||||
"serde",
|
||||
@@ -731,7 +811,9 @@ dependencies = [
|
||||
"tempfile",
|
||||
"thiserror 1.0.69",
|
||||
"tokio",
|
||||
"tokio-tungstenite",
|
||||
"tracing",
|
||||
"url",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -871,6 +953,15 @@ dependencies = [
|
||||
"zerovec",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ppv-lite86"
|
||||
version = "0.2.21"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9"
|
||||
dependencies = [
|
||||
"zerocopy",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "proc-macro2"
|
||||
version = "1.0.107"
|
||||
@@ -909,7 +1000,7 @@ dependencies = [
|
||||
"bytes",
|
||||
"getrandom 0.4.3",
|
||||
"lru-slab",
|
||||
"rand",
|
||||
"rand 0.10.4",
|
||||
"rand_pcg",
|
||||
"ring",
|
||||
"rustc-hash",
|
||||
@@ -945,12 +1036,28 @@ dependencies = [
|
||||
"proc-macro2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "r-efi"
|
||||
version = "5.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f"
|
||||
|
||||
[[package]]
|
||||
name = "r-efi"
|
||||
version = "6.0.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf"
|
||||
|
||||
[[package]]
|
||||
name = "rand"
|
||||
version = "0.9.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b9ef1d0d795eb7d84685bca4f72f3649f064e6641543d3a8c415898726a57b41"
|
||||
dependencies = [
|
||||
"rand_chacha",
|
||||
"rand_core 0.9.5",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rand"
|
||||
version = "0.10.4"
|
||||
@@ -959,7 +1066,26 @@ checksum = "8f6fa277c67e6ea590466f04c3fe82cb509f0864fe470643e5570de9514a9b11"
|
||||
dependencies = [
|
||||
"chacha20",
|
||||
"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]]
|
||||
@@ -974,7 +1100,7 @@ version = "0.10.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "caa0f4137e1c0a72f4c651489402276c8e8e1cf081f3b0ba156d2cbeef09e86a"
|
||||
dependencies = [
|
||||
"rand_core",
|
||||
"rand_core 0.10.1",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -1234,6 +1360,17 @@ dependencies = [
|
||||
"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]]
|
||||
name = "sharded-slab"
|
||||
version = "0.1.7"
|
||||
@@ -1476,6 +1613,22 @@ dependencies = [
|
||||
"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]]
|
||||
name = "tokio-util"
|
||||
version = "0.7.20"
|
||||
@@ -1604,6 +1757,31 @@ version = "0.2.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
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]]
|
||||
name = "unicode-ident"
|
||||
version = "1.0.27"
|
||||
@@ -1628,6 +1806,12 @@ dependencies = [
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "utf-8"
|
||||
version = "0.7.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "09cc8ee72d2a9becf2f2febe0205bbed8fc6615b7cb429ad062dc7b7ddd036a9"
|
||||
|
||||
[[package]]
|
||||
name = "utf8_iter"
|
||||
version = "1.1.0"
|
||||
@@ -1655,6 +1839,12 @@ version = "0.2.15"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426"
|
||||
|
||||
[[package]]
|
||||
name = "version_check"
|
||||
version = "0.9.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"
|
||||
|
||||
[[package]]
|
||||
name = "want"
|
||||
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"
|
||||
checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b"
|
||||
|
||||
[[package]]
|
||||
name = "wasip2"
|
||||
version = "1.0.4+wasi-0.2.12"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b67efb37e106e55ce722a510d6b5f9c17f083e5fc79afc2badeb12cc313d9487"
|
||||
dependencies = [
|
||||
"wit-bindgen",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wasm-bindgen"
|
||||
version = "0.2.130"
|
||||
@@ -1862,6 +2061,12 @@ version = "0.52.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec"
|
||||
|
||||
[[package]]
|
||||
name = "wit-bindgen"
|
||||
version = "0.57.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e"
|
||||
|
||||
[[package]]
|
||||
name = "writeable"
|
||||
version = "0.6.4"
|
||||
@@ -1891,6 +2096,26 @@ dependencies = [
|
||||
"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]]
|
||||
name = "zerofrom"
|
||||
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 mm_client::MattermostClient;
|
||||
use mm_core::{BridgeError, ErrorKind, ServerConfig, ServerId, User};
|
||||
use mm_store::{ServerStore, TokenStore};
|
||||
use std::collections::HashMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::{Arc, Mutex};
|
||||
use mm_core::BridgeError;
|
||||
use std::path::PathBuf;
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
struct ConnectionState {
|
||||
user: User,
|
||||
#[allow(dead_code)]
|
||||
token: String,
|
||||
url: String,
|
||||
ca_file: Option<String>,
|
||||
}
|
||||
pub use state::AppState;
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
#[derive(Clone)]
|
||||
pub struct App {
|
||||
data_dir: PathBuf,
|
||||
connections: Arc<Mutex<HashMap<ServerId, ConnectionState>>>,
|
||||
pub data_dir: PathBuf,
|
||||
pub state: AppState,
|
||||
}
|
||||
|
||||
impl App {
|
||||
pub fn new(data_dir: impl Into<PathBuf>) -> Self {
|
||||
Self {
|
||||
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 {
|
||||
match request.method.as_str() {
|
||||
"ping" => protocol::Response::ok(request.id, protocol::pong_result()),
|
||||
"status" => protocol::Response::ok(request.id, status::status_result(&self.data_dir)),
|
||||
"connect" => self.handle_connect(request).await,
|
||||
"me" => self.handle_me(request),
|
||||
"teams" => self.handle_teams(request).await,
|
||||
"open_self_dm" => self.handle_open_self_dm(request).await,
|
||||
"get_history" => self.handle_get_history(request).await,
|
||||
"send_post" => self.handle_send_post(request).await,
|
||||
"connect" => handlers::handle_connect(&self.state, &self.data_dir, request).await,
|
||||
"me" => handlers::handle_me(&self.state, request).await,
|
||||
"teams" => handlers::handle_teams(&self.state, request).await,
|
||||
"list_channels" => handlers::handle_list_channels(&self.state, request).await,
|
||||
"open_self_dm" => handlers::handle_open_self_dm(&self.state, 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(
|
||||
request.id,
|
||||
BridgeError::new(
|
||||
ErrorKind::UnknownMethod,
|
||||
mm_core::ErrorKind::UnknownMethod,
|
||||
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 {
|
||||
let response = match protocol::parse_request(line) {
|
||||
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 {
|
||||
let response = protocol::Response::err(id, error);
|
||||
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
|
||||
tracing.workspace = true
|
||||
thiserror.workspace = true
|
||||
tokio-tungstenite = { version = "0.26", features = ["rustls-tls-native-roots"] }
|
||||
futures-util = "0.3"
|
||||
url = "2.5"
|
||||
|
||||
[dev-dependencies]
|
||||
tempfile = "3"
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use crate::error::ClientError;
|
||||
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 std::path::Path;
|
||||
|
||||
@@ -34,9 +34,8 @@ impl MattermostClient {
|
||||
.map_err(ClientError::Http)?;
|
||||
|
||||
if !response.status().is_success() {
|
||||
return handle_api_error_string(response)
|
||||
.await
|
||||
.map(|_| unreachable!());
|
||||
let err = api_error(response).await;
|
||||
return Err(err);
|
||||
}
|
||||
|
||||
let token = response
|
||||
@@ -60,15 +59,15 @@ impl MattermostClient {
|
||||
.map_err(ClientError::Http)?;
|
||||
|
||||
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)?;
|
||||
Ok(user)
|
||||
}
|
||||
|
||||
pub async fn get_teams(&self, token: &str) -> Result<Vec<Team>, ClientError> {
|
||||
let url = format!("{}/api/v4/teams", self.base_url);
|
||||
pub async fn get_teams(&self, token: &str) -> Result<Vec<mm_core::Team>, ClientError> {
|
||||
let url = format!("{}/api/v4/users/me/teams", self.base_url);
|
||||
let response = self
|
||||
.client
|
||||
.get(&url)
|
||||
@@ -78,13 +77,31 @@ impl MattermostClient {
|
||||
.map_err(ClientError::Http)?;
|
||||
|
||||
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)
|
||||
}
|
||||
|
||||
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(
|
||||
&self,
|
||||
token: &str,
|
||||
@@ -101,7 +118,7 @@ impl MattermostClient {
|
||||
.map_err(ClientError::Http)?;
|
||||
|
||||
if !response.status().is_success() {
|
||||
return handle_api_error_channel(response).await;
|
||||
return Err(api_error(response).await);
|
||||
}
|
||||
|
||||
#[derive(serde::Deserialize)]
|
||||
@@ -113,16 +130,21 @@ impl MattermostClient {
|
||||
Ok(ChannelId::new(ch.id))
|
||||
}
|
||||
|
||||
/// Get posts for a channel. `before` = oldest known post id for pagination.
|
||||
pub async fn get_posts(
|
||||
&self,
|
||||
token: &str,
|
||||
channel_id: &str,
|
||||
limit: u32,
|
||||
before: Option<&str>,
|
||||
) -> Result<Vec<Post>, ClientError> {
|
||||
let url = format!(
|
||||
"{}/api/v4/channels/{}/posts?page=0&per_page={}",
|
||||
let mut url = format!(
|
||||
"{}/api/v4/channels/{}/posts?per_page={}",
|
||||
self.base_url, channel_id, limit
|
||||
);
|
||||
if let Some(b) = before {
|
||||
url.push_str(&format!("&before={}", b));
|
||||
}
|
||||
|
||||
let response = self
|
||||
.client
|
||||
@@ -133,10 +155,9 @@ impl MattermostClient {
|
||||
.map_err(ClientError::Http)?;
|
||||
|
||||
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)]
|
||||
struct PostsResponse {
|
||||
order: Vec<String>,
|
||||
@@ -145,16 +166,13 @@ impl MattermostClient {
|
||||
|
||||
let data: PostsResponse = response.json().await.map_err(ClientError::Http)?;
|
||||
|
||||
// Normalize to ordered vector
|
||||
let mut posts: Vec<Post> = data
|
||||
.order
|
||||
.iter()
|
||||
.filter_map(|id| data.posts.get(id).cloned())
|
||||
.collect();
|
||||
|
||||
// Sort ascending by create_at for display
|
||||
posts.sort_by_key(|p| p.create_at);
|
||||
|
||||
Ok(posts)
|
||||
}
|
||||
|
||||
@@ -186,7 +204,7 @@ impl MattermostClient {
|
||||
.map_err(ClientError::Http)?;
|
||||
|
||||
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)?;
|
||||
@@ -194,39 +212,23 @@ impl MattermostClient {
|
||||
}
|
||||
}
|
||||
|
||||
// --- Helpers for error handling ---
|
||||
|
||||
async fn handle_api_error_string(response: reqwest::Response) -> Result<String, ClientError> {
|
||||
async fn api_error(response: reqwest::Response) -> ClientError {
|
||||
let status = response.status().as_u16();
|
||||
let body = response.text().await.unwrap_or_default();
|
||||
|
||||
#[derive(serde::Deserialize)]
|
||||
struct MmError {
|
||||
id: 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> {
|
||||
handle_api_error_string(response).await?;
|
||||
unreachable!()
|
||||
}
|
||||
async fn handle_api_error_vec<T>(response: reqwest::Response) -> Result<Vec<T>, ClientError> {
|
||||
handle_api_error_string(response).await?;
|
||||
unreachable!()
|
||||
}
|
||||
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!()
|
||||
let (id, message) = serde_json::from_str::<MmError>(&body)
|
||||
.map(|e| (e.id, e.message))
|
||||
.unwrap_or_else(|_| ("api_error".to_string(), body));
|
||||
|
||||
ClientError::Api {
|
||||
id,
|
||||
message,
|
||||
status_code: status,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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 ids::{ChannelId, PostId, ServerId, TeamId, UserId};
|
||||
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,
|
||||
}
|
||||
|
||||
/// 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)]
|
||||
pub struct Post {
|
||||
pub id: PostId,
|
||||
|
||||
Reference in New Issue
Block a user