Compare commits
12 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 84fdb0a8e6 | |||
| 0368d42c1f | |||
| e7089c9427 | |||
| ca973ac530 | |||
| d33edb4e44 | |||
| d05a3a180e | |||
| 332275eb2e | |||
| b5777565d7 | |||
| 452005b98c | |||
| 628df77588 | |||
| f2f4f62cd6 | |||
| 618632b03b |
@@ -0,0 +1,58 @@
|
||||
use mm_client::MattermostClient;
|
||||
use mm_core::Post;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
pub async fn enrich_posts_with_display_names(
|
||||
client: &MattermostClient,
|
||||
token: &str,
|
||||
posts: &mut [Post],
|
||||
) {
|
||||
let unique_ids: Vec<String> = posts
|
||||
.iter()
|
||||
.map(|p| p.user_id.0.clone())
|
||||
.collect::<HashSet<_>>()
|
||||
.into_iter()
|
||||
.collect();
|
||||
|
||||
if unique_ids.is_empty() {
|
||||
return;
|
||||
}
|
||||
|
||||
match client.get_users_by_ids(token, &unique_ids).await {
|
||||
Ok(users) => {
|
||||
let name_map: HashMap<String, String> = users
|
||||
.into_iter()
|
||||
.map(|u| (u.id.0.clone(), u.display_name()))
|
||||
.collect();
|
||||
|
||||
for post in posts.iter_mut() {
|
||||
if let Some(name) = name_map.get(&post.user_id.0) {
|
||||
post.user_display_name = name.clone();
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::warn!(error = %e, "Failed to resolve user display names, falling back to IDs");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn enrich_posts_with_files(client: &MattermostClient, token: &str, posts: &mut [Post]) {
|
||||
for post in posts.iter_mut() {
|
||||
if post.file_ids.is_empty() {
|
||||
continue;
|
||||
}
|
||||
match client.get_post_files(token, &post.id.0).await {
|
||||
Ok(files) => {
|
||||
post.files = files;
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::warn!(
|
||||
post_id = %post.id.0,
|
||||
error = %e,
|
||||
"Failed to fetch file info for post"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
use crate::app::state::AppState;
|
||||
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 fn protocol_err(id: impl Into<String>, msg: &str) -> protocol::Response {
|
||||
protocol::Response::err(id, BridgeError::new(ErrorKind::InvalidRequest, msg))
|
||||
}
|
||||
|
||||
pub 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"))
|
||||
}
|
||||
|
||||
pub 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()))
|
||||
}
|
||||
|
||||
pub fn get_token(app_state: &AppState, server_id: &ServerId) -> Result<String, BridgeError> {
|
||||
app_state.get_connection(server_id).map(|s| s.token.clone())
|
||||
}
|
||||
|
||||
pub 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())
|
||||
}
|
||||
|
||||
pub 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)
|
||||
}
|
||||
|
||||
pub 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)
|
||||
}
|
||||
|
||||
pub 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(())
|
||||
}
|
||||
+87
-121
@@ -1,10 +1,11 @@
|
||||
use crate::app::state::{AppState, ConnectionState};
|
||||
mod enrich;
|
||||
mod helpers;
|
||||
|
||||
use crate::app::state::AppState;
|
||||
use crate::protocol;
|
||||
use mm_client::MattermostClient;
|
||||
use mm_core::{BridgeError, Channel, ErrorKind, Post, ServerConfig, ServerId, User};
|
||||
use mm_store::{ServerStore, TokenStore};
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::path::{Path, PathBuf};
|
||||
use helpers::*;
|
||||
use mm_core::Post;
|
||||
use std::path::Path;
|
||||
|
||||
pub async fn handle_connect(
|
||||
app_state: &AppState,
|
||||
@@ -40,8 +41,8 @@ pub async fn handle_connect(
|
||||
} else if let Some(token) = params.get("token").and_then(|v| v.as_str()) {
|
||||
Ok(token.to_string())
|
||||
} else {
|
||||
Err(BridgeError::new(
|
||||
ErrorKind::InvalidRequest,
|
||||
Err(mm_core::BridgeError::new(
|
||||
mm_core::ErrorKind::InvalidRequest,
|
||||
"provide credentials or token",
|
||||
))
|
||||
};
|
||||
@@ -56,7 +57,7 @@ pub async fn handle_connect(
|
||||
Ok(user) => {
|
||||
app_state.add_connection(
|
||||
server_id.clone(),
|
||||
ConnectionState {
|
||||
crate::app::state::ConnectionState {
|
||||
user: user.clone(),
|
||||
token: token.clone(),
|
||||
url: url.clone(),
|
||||
@@ -159,8 +160,11 @@ pub async fn handle_list_channels(
|
||||
Err(e) => return protocol::Response::err(request.id, e),
|
||||
};
|
||||
|
||||
match client.get_my_channels(&token).await {
|
||||
Ok(mut channels) => {
|
||||
let channels_result = client.get_my_channels(&token).await;
|
||||
let teams_result = client.get_teams(&token).await;
|
||||
|
||||
match (channels_result, teams_result) {
|
||||
(Ok(mut channels), Ok(teams)) => {
|
||||
for ch in &mut channels {
|
||||
if ch.channel_type == "D" && ch.display_name.is_empty() {
|
||||
let parts: Vec<&str> = ch.name.split("__").collect();
|
||||
@@ -183,10 +187,11 @@ pub async fn handle_list_channels(
|
||||
serde_json::json!({
|
||||
"server_id": server_id,
|
||||
"channels": channels,
|
||||
"teams": teams,
|
||||
}),
|
||||
)
|
||||
}
|
||||
Err(e) => protocol::Response::err(request.id, e.into()),
|
||||
(Err(e), _) | (_, Err(e)) => protocol::Response::err(request.id, e.into()),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -261,8 +266,8 @@ pub async fn handle_get_history(
|
||||
|
||||
match client.get_posts(&token, channel_id, limit, before).await {
|
||||
Ok(mut posts) => {
|
||||
// Обогащаем посты именами отправителей
|
||||
enrich_posts_with_display_names(&client, &token, &mut posts).await;
|
||||
enrich::enrich_posts_with_display_names(&client, &token, &mut posts).await;
|
||||
enrich::enrich_posts_with_files(&client, &token, &mut posts).await;
|
||||
|
||||
protocol::Response::ok(
|
||||
request.id,
|
||||
@@ -278,44 +283,6 @@ pub async fn handle_get_history(
|
||||
}
|
||||
}
|
||||
|
||||
/// Batch-resolve user_ids in posts to human-readable display names.
|
||||
async fn enrich_posts_with_display_names(
|
||||
client: &MattermostClient,
|
||||
token: &str,
|
||||
posts: &mut [Post],
|
||||
) {
|
||||
// Собираем уникальные user_id
|
||||
let unique_ids: Vec<String> = posts
|
||||
.iter()
|
||||
.map(|p| p.user_id.0.clone())
|
||||
.collect::<HashSet<_>>()
|
||||
.into_iter()
|
||||
.collect();
|
||||
|
||||
if unique_ids.is_empty() {
|
||||
return;
|
||||
}
|
||||
|
||||
// Batch-запрос профилей
|
||||
match client.get_users_by_ids(token, &unique_ids).await {
|
||||
Ok(users) => {
|
||||
let name_map: HashMap<String, String> = users
|
||||
.into_iter()
|
||||
.map(|u| (u.id.0.clone(), u.display_name()))
|
||||
.collect();
|
||||
|
||||
for post in posts.iter_mut() {
|
||||
if let Some(name) = name_map.get(&post.user_id.0) {
|
||||
post.user_display_name = name.clone();
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::warn!(error = %e, "Failed to resolve user display names, falling back to IDs");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn handle_send_post(
|
||||
app_state: &AppState,
|
||||
request: protocol::Request,
|
||||
@@ -360,76 +327,75 @@ pub async fn handle_send_post(
|
||||
}
|
||||
}
|
||||
|
||||
// --- 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(
|
||||
pub async fn handle_download_file(
|
||||
app_state: &AppState,
|
||||
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(),
|
||||
request: protocol::Request,
|
||||
) -> protocol::Response {
|
||||
tracing::debug!("Received download_file request: {:?}", request.params);
|
||||
let params = match request.params.as_object() {
|
||||
Some(p) => p,
|
||||
None => return protocol_err(request.id, "params must be an object"),
|
||||
};
|
||||
server_store
|
||||
.save(&config)
|
||||
.map_err(|e| protocol::Response::err("req", e))?;
|
||||
let server_id = get_server_id(params);
|
||||
let file_id = match params.get("file_id").and_then(|v| v.as_str()) {
|
||||
Some(id) => id,
|
||||
None => return protocol_err(request.id, "missing file_id"),
|
||||
};
|
||||
let file_name = params
|
||||
.get("file_name")
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or_else(|| "download.bin");
|
||||
let download_dir = params
|
||||
.get("download_dir")
|
||||
.and_then(|v| v.as_str())
|
||||
.map(|s| s.to_string())
|
||||
.unwrap_or_else(|| data_dir.join("downloads").to_string_lossy().to_string());
|
||||
|
||||
Ok(())
|
||||
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.download_file(&token, file_id).await {
|
||||
Ok(bytes) => {
|
||||
let dir = std::path::PathBuf::from(&download_dir);
|
||||
if let Err(e) = std::fs::create_dir_all(&dir) {
|
||||
return protocol::Response::err(
|
||||
request.id,
|
||||
mm_core::BridgeError::new(
|
||||
mm_core::ErrorKind::InternalError,
|
||||
format!("Failed to create download dir: {}", e),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
let file_path = dir.join(file_name);
|
||||
|
||||
if let Err(e) = std::fs::write(&file_path, &bytes) {
|
||||
return protocol::Response::err(
|
||||
request.id,
|
||||
mm_core::BridgeError::new(
|
||||
mm_core::ErrorKind::InternalError,
|
||||
format!("Failed to write file: {}", e),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
protocol::Response::ok(
|
||||
request.id,
|
||||
serde_json::json!({
|
||||
"server_id": server_id,
|
||||
"file_id": file_id,
|
||||
"local_path": file_path.to_string_lossy(),
|
||||
"size": bytes.len(),
|
||||
}),
|
||||
)
|
||||
}
|
||||
Err(e) => protocol::Response::err(request.id, e.into()),
|
||||
}
|
||||
}
|
||||
@@ -32,6 +32,9 @@ impl App {
|
||||
"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,
|
||||
"download_file" => {
|
||||
handlers::handle_download_file(&self.state, &self.data_dir, request).await
|
||||
}
|
||||
_ => protocol::Response::err(
|
||||
request.id,
|
||||
BridgeError::new(
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
use mm_client::ws::WsConnection;
|
||||
use mm_client::MattermostClient;
|
||||
use mm_core::{BridgeError, ErrorKind, ServerId, User};
|
||||
use serde_json::Value;
|
||||
use std::collections::HashMap;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::{Arc, Mutex};
|
||||
use tokio::sync::broadcast;
|
||||
|
||||
@@ -22,7 +24,7 @@ pub struct AppState {
|
||||
|
||||
impl AppState {
|
||||
pub fn new() -> Self {
|
||||
let (tx, _) = broadcast::channel(100); // Буфер до 100 событий
|
||||
let (tx, _) = broadcast::channel(100);
|
||||
Self {
|
||||
connections: Arc::new(Mutex::new(HashMap::new())),
|
||||
event_tx: tx,
|
||||
@@ -51,6 +53,16 @@ impl AppState {
|
||||
let sid = server_id.clone();
|
||||
let event_tx = self.event_tx.clone();
|
||||
|
||||
let ca_path = state.ca_file.as_ref().map(PathBuf::from);
|
||||
let client = match MattermostClient::new(state.url.clone(), ca_path.as_deref()) {
|
||||
Ok(c) => c,
|
||||
Err(e) => {
|
||||
tracing::error!(server_id = %sid, "Failed to create client for WS: {}", e);
|
||||
return Err(BridgeError::new(ErrorKind::InternalError, e.to_string()));
|
||||
}
|
||||
};
|
||||
let token = state.token.clone();
|
||||
|
||||
tokio::spawn(async move {
|
||||
match WsConnection::new(&state.url, &state.token).await {
|
||||
Ok(mut ws) => {
|
||||
@@ -58,20 +70,99 @@ impl AppState {
|
||||
loop {
|
||||
match ws.next_event().await {
|
||||
Ok(Some(event_data)) => {
|
||||
// Пытаемся распарсить и нормализовать событие 'posted'
|
||||
if let Ok(json_val) = serde_json::from_str::<Value>(&event_data) {
|
||||
if let Some(event_type) =
|
||||
json_val.get("event").and_then(|v| v.as_str())
|
||||
{
|
||||
if event_type == "posted" {
|
||||
if let Some(data) = json_val.get("data") {
|
||||
// Mattermost присылает post как строку, содержащую JSON
|
||||
if let Some(post_str) =
|
||||
data.get("post").and_then(|v| v.as_str())
|
||||
{
|
||||
if let Ok(post_obj) =
|
||||
if let Ok(mut post_obj) =
|
||||
serde_json::from_str::<Value>(post_str)
|
||||
{
|
||||
let post_id = post_obj
|
||||
.get("id")
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or("unknown")
|
||||
.to_string();
|
||||
|
||||
// Резолвим имя отправителя
|
||||
if let Some(user_id) = post_obj
|
||||
.get("user_id")
|
||||
.and_then(|v| v.as_str())
|
||||
{
|
||||
if let Ok(user) = client
|
||||
.get_user(&token, user_id)
|
||||
.await
|
||||
{
|
||||
post_obj["user_display_name"] =
|
||||
Value::String(
|
||||
user.display_name(),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Проверяем file_ids в событии
|
||||
let file_ids: Vec<String> = post_obj
|
||||
.get("file_ids")
|
||||
.and_then(|v| v.as_array())
|
||||
.map(|arr| {
|
||||
arr.iter()
|
||||
.filter_map(|v| {
|
||||
v.as_str().map(String::from)
|
||||
})
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
|
||||
tracing::debug!(
|
||||
server_id = %sid,
|
||||
post_id = %post_id,
|
||||
file_ids_count = file_ids.len(),
|
||||
file_ids = ?file_ids,
|
||||
"WS posted event received"
|
||||
);
|
||||
|
||||
// Резолвим файлы, если они есть
|
||||
if !file_ids.is_empty() {
|
||||
match client
|
||||
.get_post_files(&token, &post_id)
|
||||
.await
|
||||
{
|
||||
Ok(files) => {
|
||||
tracing::debug!(
|
||||
server_id = %sid,
|
||||
post_id = %post_id,
|
||||
files_count = files.len(),
|
||||
"Resolved files for WS event"
|
||||
);
|
||||
let files_json: Vec<Value> = files
|
||||
.iter()
|
||||
.map(|f| {
|
||||
serde_json::json!({
|
||||
"id": f.id,
|
||||
"name": f.name,
|
||||
"size": f.size,
|
||||
"mime_type": f.mime_type,
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
post_obj["files"] =
|
||||
Value::Array(files_json);
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::warn!(
|
||||
server_id = %sid,
|
||||
post_id = %post_id,
|
||||
error = %e,
|
||||
"Failed to fetch file info for WS event"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let normalized = serde_json::json!({
|
||||
"type": "event",
|
||||
"method": "posted",
|
||||
@@ -79,7 +170,6 @@ impl AppState {
|
||||
"post": post_obj
|
||||
}
|
||||
});
|
||||
// Игнорируем ошибку, если нет подписчиков (Emacs отключён)
|
||||
let _ = event_tx.send(normalized);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use crate::error::ClientError;
|
||||
use crate::tls;
|
||||
use mm_core::{Channel, ChannelId, Post, User};
|
||||
use mm_core::{Channel, ChannelId, FileInfo, Post, User};
|
||||
use reqwest::header::AUTHORIZATION;
|
||||
use std::path::Path;
|
||||
|
||||
@@ -34,8 +34,7 @@ impl MattermostClient {
|
||||
.map_err(ClientError::Http)?;
|
||||
|
||||
if !response.status().is_success() {
|
||||
let err = api_error(response).await;
|
||||
return Err(err);
|
||||
return Err(api_error(response).await);
|
||||
}
|
||||
|
||||
let token = response
|
||||
@@ -84,7 +83,7 @@ impl MattermostClient {
|
||||
Ok(user)
|
||||
}
|
||||
|
||||
/// Batch-fetch users by their IDs. Mattermost limit is 1000 per request.
|
||||
/// Batch-fetch users by their IDs.
|
||||
pub async fn get_users_by_ids(
|
||||
&self,
|
||||
token: &str,
|
||||
@@ -175,6 +174,7 @@ 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,
|
||||
@@ -220,6 +220,46 @@ impl MattermostClient {
|
||||
Ok(posts)
|
||||
}
|
||||
|
||||
/// Fetch file metadata for a post.
|
||||
///
|
||||
/// Mattermost has returned different shapes for this endpoint across
|
||||
/// versions, so the body is parsed tolerantly and logged on debug.
|
||||
pub async fn get_post_files(
|
||||
&self,
|
||||
token: &str,
|
||||
post_id: &str,
|
||||
) -> Result<Vec<FileInfo>, ClientError> {
|
||||
let url = format!("{}/api/v4/posts/{}/files/info", self.base_url, post_id);
|
||||
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 body = response.text().await.map_err(ClientError::Http)?;
|
||||
let prefix: String = body.chars().take(300).collect();
|
||||
tracing::debug!(post_id, body = %prefix, "files/info raw response");
|
||||
|
||||
let value: serde_json::Value =
|
||||
serde_json::from_str(&body).map_err(|e| ClientError::Api {
|
||||
id: "decode_error".to_string(),
|
||||
message: format!("{e}; body prefix: {prefix}"),
|
||||
status_code: 200,
|
||||
})?;
|
||||
|
||||
let files = parse_file_infos(&value);
|
||||
if files.is_empty() {
|
||||
tracing::debug!(post_id, body = %prefix, "files/info parsed to zero files");
|
||||
}
|
||||
Ok(files)
|
||||
}
|
||||
|
||||
pub async fn create_post(
|
||||
&self,
|
||||
token: &str,
|
||||
@@ -254,6 +294,69 @@ impl MattermostClient {
|
||||
let post: Post = response.json().await.map_err(ClientError::Http)?;
|
||||
Ok(post)
|
||||
}
|
||||
|
||||
/// Download a file by its ID. Returns the file bytes.
|
||||
pub async fn download_file(&self, token: &str, file_id: &str) -> Result<Vec<u8>, ClientError> {
|
||||
let url = format!("{}/api/v4/files/{}", self.base_url, file_id);
|
||||
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 bytes = response.bytes().await.map_err(ClientError::Http)?;
|
||||
Ok(bytes.to_vec())
|
||||
}
|
||||
}
|
||||
|
||||
/// Accept `[fileinfo, ...]`, `{file_infos: [...]}`, or
|
||||
/// `{order: [...], file_infos: {id: fileinfo}}`.
|
||||
fn parse_file_infos(value: &serde_json::Value) -> Vec<FileInfo> {
|
||||
fn many(items: &[serde_json::Value]) -> Vec<FileInfo> {
|
||||
items
|
||||
.iter()
|
||||
.filter_map(|v| serde_json::from_value::<FileInfo>(v.clone()).ok())
|
||||
.collect()
|
||||
}
|
||||
|
||||
match value {
|
||||
serde_json::Value::Array(items) => many(items),
|
||||
serde_json::Value::Object(map) => {
|
||||
let order: Vec<String> = map
|
||||
.get("order")
|
||||
.and_then(|v| v.as_array())
|
||||
.map(|a| {
|
||||
a.iter()
|
||||
.filter_map(|v| v.as_str().map(String::from))
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
|
||||
match map.get("file_infos") {
|
||||
Some(serde_json::Value::Array(items)) => many(items),
|
||||
Some(serde_json::Value::Object(infos)) => {
|
||||
if order.is_empty() {
|
||||
many(&infos.values().cloned().collect::<Vec<_>>())
|
||||
} else {
|
||||
let items: Vec<serde_json::Value> = order
|
||||
.iter()
|
||||
.filter_map(|id| infos.get(id))
|
||||
.cloned()
|
||||
.collect();
|
||||
many(&items)
|
||||
}
|
||||
}
|
||||
_ => Vec::new(),
|
||||
}
|
||||
}
|
||||
_ => Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
async fn api_error(response: reqwest::Response) -> ClientError {
|
||||
|
||||
@@ -9,5 +9,6 @@ pub mod model;
|
||||
pub use error::{BridgeError, ErrorKind};
|
||||
pub use ids::{ChannelId, PostId, ServerId, TeamId, UserId};
|
||||
pub use model::{
|
||||
BridgeInfo, BridgeState, BridgeStatus, Channel, Post, ServerConfig, ServerSummary, Team, User,
|
||||
BridgeInfo, BridgeState, BridgeStatus, Channel, FileInfo, Post, ServerConfig, ServerSummary,
|
||||
Team, User,
|
||||
};
|
||||
|
||||
@@ -85,9 +85,25 @@ 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 channel_type: String,
|
||||
pub display_name: String,
|
||||
pub name: String,
|
||||
/// Timestamp of the last post in this channel (milliseconds since epoch).
|
||||
#[serde(default)]
|
||||
pub last_post_at: i64,
|
||||
}
|
||||
|
||||
/// File metadata attached to a post.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct FileInfo {
|
||||
#[serde(default)]
|
||||
pub id: String,
|
||||
#[serde(default)]
|
||||
pub name: String,
|
||||
#[serde(default)]
|
||||
pub size: i64,
|
||||
#[serde(default)]
|
||||
pub mime_type: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
@@ -103,7 +119,9 @@ pub struct Post {
|
||||
#[serde(default)]
|
||||
pub file_ids: Vec<String>,
|
||||
/// Populated by the bridge after resolving user_id via /users/ids.
|
||||
/// Skipped during deserialization from Mattermost API.
|
||||
#[serde(default, skip_deserializing)]
|
||||
pub user_display_name: String,
|
||||
/// Populated by the bridge after fetching file metadata.
|
||||
#[serde(default, skip_deserializing)]
|
||||
pub files: Vec<FileInfo>,
|
||||
}
|
||||
|
||||
+11
-4
@@ -8,13 +8,20 @@ services:
|
||||
RUNTIME_IMAGE: "${RUNTIME_IMAGE:-nexus.c68.spacecorp.ru/ci/debian:bookworm-ca}"
|
||||
container_name: emacs-mattermost-bridge
|
||||
restart: unless-stopped
|
||||
|
||||
# Контейнер будет использовать /etc/hosts и DNS хост-машины напрямую.
|
||||
# Это позволяет резолвить любые внутренние домены без знания их IP.
|
||||
network_mode: "host"
|
||||
|
||||
environment:
|
||||
# При network_mode: "host" привязываемся явно к localhost хоста для безопасности
|
||||
MM_BRIDGE_LISTEN: "0.0.0.0:8765"
|
||||
MM_WEB_LISTEN: "0.0.0.0:8766"
|
||||
MM_DATA_DIR: "/data"
|
||||
RUST_LOG: "mm_bridge=info,mm_web=info,warn"
|
||||
ports:
|
||||
- "127.0.0.1:8765:8765"
|
||||
- "127.0.0.1:8766:8766"
|
||||
RUST_LOG: "mm_bridge=debug,mm_client=debug,mm_store=debug"
|
||||
|
||||
volumes:
|
||||
- ./data:/data
|
||||
|
||||
# Секция 'ports' игнорируется при network_mode: "host",
|
||||
# так как порты открываются напрямую на интерфейсах хоста.
|
||||
|
||||
+5
-1
@@ -6,6 +6,7 @@ FROM ${RUST_BUILDER_IMAGE} AS builder
|
||||
# Corporate CA so cargo trusts nexus.local over HTTPS.
|
||||
COPY docker/certs/corporate-ca.crt /usr/local/share/ca-certificates/corporate-ca.crt
|
||||
RUN update-ca-certificates
|
||||
RUN apt install -y curl
|
||||
|
||||
WORKDIR /build
|
||||
|
||||
@@ -30,7 +31,10 @@ COPY docker/entrypoint.sh /usr/local/bin/entrypoint.sh
|
||||
|
||||
RUN chmod +x /usr/local/bin/entrypoint.sh
|
||||
|
||||
USER mmbridge
|
||||
# NOTE: Intentionally no `USER mmbridge` here. The entrypoint runs as root,
|
||||
# fixes /data ownership, then drops privileges via runuser(1).
|
||||
# This avoids "Permission denied" on bind-mounted volumes whose host-side
|
||||
# ownership does not match UID 10001.
|
||||
|
||||
ENV MM_BRIDGE_LISTEN=0.0.0.0:8765
|
||||
ENV MM_WEB_LISTEN=0.0.0.0:8766
|
||||
|
||||
@@ -5,15 +5,19 @@ export MM_BRIDGE_LISTEN="${MM_BRIDGE_LISTEN:-0.0.0.0:8765}"
|
||||
export MM_WEB_LISTEN="${MM_WEB_LISTEN:-0.0.0.0:8766}"
|
||||
export MM_DATA_DIR="${MM_DATA_DIR:-/data}"
|
||||
|
||||
# Ensure data directory exists with correct ownership.
|
||||
# Entrypoint runs as root; we fix permissions then drop to mmbridge below.
|
||||
mkdir -p "${MM_DATA_DIR}"
|
||||
chown -R mmbridge:mmbridge "${MM_DATA_DIR}" 2>/dev/null || true
|
||||
|
||||
# Drop privileges to the unprivileged mmbridge user.
|
||||
if [[ "$#" -eq 0 ]]; then
|
||||
exec mm-bridge
|
||||
exec runuser -u mmbridge -- mm-bridge
|
||||
fi
|
||||
|
||||
if [[ "$1" == "mm-bridge" ]]; then
|
||||
shift
|
||||
exec mm-bridge "$@"
|
||||
exec runuser -u mmbridge -- mm-bridge "$@"
|
||||
fi
|
||||
|
||||
exec "$@"
|
||||
exec runuser -u mmbridge -- "$@"
|
||||
|
||||
+249
-59
@@ -2,19 +2,39 @@
|
||||
|
||||
(require 'mattermost-custom)
|
||||
(require 'mattermost-protocol)
|
||||
(require 'mattermost-files)
|
||||
|
||||
(defvar mattermost-channel-mode-map
|
||||
(let ((map (make-sparse-keymap)))
|
||||
;; Отцепляемся от special-mode-map, чтобы его одиночные клавиши
|
||||
;; (space, DEL, g, q, h, ...) не мешали набору текста в черновике.
|
||||
(set-keymap-parent map nil)
|
||||
(define-key map (kbd "RET") #'mattermost-channel-ret)
|
||||
(define-key map (kbd "SPC") #'mattermost-channel-space)
|
||||
(define-key map (kbd "DEL") #'mattermost-channel-backspace)
|
||||
(define-key map "g" #'mattermost-channel-g)
|
||||
(define-key map "q" #'mattermost-channel-q)
|
||||
(define-key map "h" #'mattermost-channel-h)
|
||||
(define-key map "?" #'mattermost-channel-h)
|
||||
(define-key map (kbd "C-c C-c") #'mattermost-channel-send-message)
|
||||
(define-key map (kbd "C-c C-s") #'mattermost-channel-send-message)
|
||||
(define-key map (kbd "g") #'mattermost-channel-refresh)
|
||||
(define-key map [remap self-insert-command] #'mattermost-channel-self-insert)
|
||||
map)
|
||||
"Keymap for `mattermost-channel-mode`.")
|
||||
"Keymap for `mattermost-channel-mode'.
|
||||
Single-key commands are context wrappers: they type in the draft and
|
||||
act on history otherwise.")
|
||||
|
||||
(define-derived-mode mattermost-channel-mode special-mode "Mattermost-Channel"
|
||||
"Major mode for viewing a Mattermost channel.
|
||||
"Major mode for viewing and writing in a Mattermost channel.
|
||||
History above the \"> \" prompt is protected by a local before-change
|
||||
hook; the draft after the prompt is editable and kept at buffer end.
|
||||
\\{mattermost-channel-mode-map}"
|
||||
(setq buffer-read-only t)
|
||||
(setq truncate-lines t))
|
||||
(setq buffer-read-only nil)
|
||||
(setq truncate-lines nil)
|
||||
;; Построчная прокрутка стрелками, без перекидывания экрана
|
||||
(setq-local scroll-conservatively 101)
|
||||
(setq-local scroll-margin 0)
|
||||
(add-hook 'before-change-functions #'mattermost--protect-history nil t))
|
||||
|
||||
(defvar-local mattermost--channel-id nil
|
||||
"Channel ID for the current buffer.")
|
||||
@@ -25,6 +45,35 @@
|
||||
(defvar-local mattermost--channel-name nil
|
||||
"Display name of the current channel.")
|
||||
|
||||
(defvar-local mattermost--posts nil
|
||||
"List of post plists currently displayed, oldest first.")
|
||||
|
||||
(defvar-local mattermost--input-text ""
|
||||
"Draft message text kept across re-renders.")
|
||||
|
||||
(defvar-local mattermost--input-start nil
|
||||
"Buffer position where the editable draft begins.")
|
||||
|
||||
(defvar-local mattermost--rendering nil
|
||||
"Non-nil while the buffer is re-rendered programmatically.")
|
||||
|
||||
(defvar-local mattermost--sending nil
|
||||
"Non-nil while a send_post request is in flight.")
|
||||
|
||||
(defun mattermost--protect-history (beg _end)
|
||||
"Forbid modifications starting in the history area (before the draft)."
|
||||
(unless mattermost--rendering
|
||||
(when (and mattermost--input-start (< beg mattermost--input-start))
|
||||
(user-error "History is read-only"))))
|
||||
|
||||
(defun mattermost--in-draft-p ()
|
||||
"Return non-nil when point is inside the editable draft."
|
||||
(and mattermost--input-start (>= (point) mattermost--input-start)))
|
||||
|
||||
(defun mattermost--channel-window ()
|
||||
"Return a window displaying the current buffer, searching all frames."
|
||||
(get-buffer-window (current-buffer) t))
|
||||
|
||||
(defun mattermost-channel-open (server-id channel-id channel-name)
|
||||
"Open a buffer for CHANNEL-ID on SERVER-ID with CHANNEL-NAME."
|
||||
(let ((buf-name (format "*MM: %s*" channel-name)))
|
||||
@@ -34,14 +83,24 @@
|
||||
(setq-local mattermost--server-id server-id)
|
||||
(setq-local mattermost--channel-id channel-id)
|
||||
(setq-local mattermost--channel-name channel-name)
|
||||
(setq-local mattermost--posts nil)
|
||||
(setq-local mattermost--input-text "")
|
||||
(setq-local mattermost--input-start nil)
|
||||
(mattermost-channel-load-history))
|
||||
(switch-to-buffer buf))))
|
||||
(switch-to-buffer buf)
|
||||
(with-current-buffer buf
|
||||
(goto-char (point-max))
|
||||
(when-let ((win (mattermost--channel-window)))
|
||||
(set-window-point win (point-max))
|
||||
(with-selected-window win
|
||||
(recenter -1))))
|
||||
buf)))
|
||||
|
||||
(defun mattermost-channel-load-history ()
|
||||
"Load and display message history for the current channel."
|
||||
"Load message history for the current channel into `mattermost--posts'."
|
||||
(let ((server-id mattermost--server-id)
|
||||
(channel-id mattermost--channel-id)
|
||||
(channel-name mattermost--channel-name))
|
||||
(buf (current-buffer)))
|
||||
(message "[MM-DEBUG] Loading history for channel %s..." channel-id)
|
||||
(mattermost--send-request
|
||||
"get_history"
|
||||
@@ -49,81 +108,212 @@
|
||||
:channel_id channel-id
|
||||
:limit 50)
|
||||
(lambda (response)
|
||||
(if (plist-get response :ok)
|
||||
(mattermost--render-channel-history
|
||||
channel-name
|
||||
(plist-get (plist-get response :result) :posts))
|
||||
(message "[MM] Failed to load history: %S" (plist-get response :error)))))))
|
||||
(when (buffer-live-p buf)
|
||||
(with-current-buffer buf
|
||||
(if (plist-get response :ok)
|
||||
(progn
|
||||
(setq mattermost--posts
|
||||
(plist-get (plist-get response :result) :posts))
|
||||
(mattermost--render-channel-buffer))
|
||||
(message "[MM] Failed to load history: %S"
|
||||
(plist-get response :error)))))))))
|
||||
|
||||
(defun mattermost--render-channel-history (channel-name posts)
|
||||
"Render POSTS in the current channel buffer with CHANNEL-NAME."
|
||||
(let ((inhibit-read-only t))
|
||||
(defun mattermost--format-post (post)
|
||||
"Format a POST plist: timestamp, bold sender, message, file block."
|
||||
(let* ((msg-text (or (plist-get post :message) ""))
|
||||
(create-at (plist-get post :create_at))
|
||||
(time-str (if create-at
|
||||
(format-time-string "%Y-%m-%d %H:%M"
|
||||
(seconds-to-time (/ create-at 1000)))
|
||||
"????-??-?? ??:??"))
|
||||
(sender (or (plist-get post :user_display_name)
|
||||
(plist-get post :user_id)
|
||||
"unknown"))
|
||||
(files (plist-get post :files))
|
||||
(has-content (or (not (string-empty-p msg-text)) files)))
|
||||
(unless has-content
|
||||
(setq msg-text "[empty message]"))
|
||||
(concat
|
||||
(format "[%s] **" time-str)
|
||||
(propertize sender 'face 'mattermost-sender-face)
|
||||
(format ":**\n%s"
|
||||
(if (string-empty-p msg-text) "" (concat msg-text "\n")))
|
||||
(when files (mattermost--format-file-block files))
|
||||
"\n")))
|
||||
|
||||
(defun mattermost--render-channel-buffer (&optional new-draft)
|
||||
"Re-render history, prompt and draft.
|
||||
When NEW-DRAFT is non-nil, replace the draft with it instead of
|
||||
recapturing from the buffer. If the user was at the bottom (in the
|
||||
draft or with the buffer end visible), point returns to the draft and
|
||||
the window is recentered to show the prompt; otherwise the window view
|
||||
is left undisturbed."
|
||||
(let* ((mattermost--rendering t)
|
||||
(win (mattermost--channel-window))
|
||||
(old-point (point))
|
||||
(old-window-start (when win (window-start win)))
|
||||
(was-in-draft (and mattermost--input-start
|
||||
(>= old-point mattermost--input-start)))
|
||||
(was-at-bottom (or (null win)
|
||||
(pos-visible-in-window-p (point-max) win)))
|
||||
(draft-offset nil))
|
||||
(when new-draft
|
||||
(setq mattermost--input-text new-draft))
|
||||
(when (and (null new-draft)
|
||||
mattermost--input-start
|
||||
(>= (point-max) mattermost--input-start))
|
||||
(setq mattermost--input-text
|
||||
(buffer-substring-no-properties mattermost--input-start (point-max)))
|
||||
(when was-in-draft
|
||||
(setq draft-offset (- old-point mattermost--input-start))))
|
||||
(erase-buffer)
|
||||
(insert (format "Channel: %s\n" channel-name))
|
||||
(insert (format "Channel: %s\n" mattermost--channel-name))
|
||||
(insert "========================================\n\n")
|
||||
|
||||
(dolist (post posts)
|
||||
(let* ((msg-text (or (plist-get post :message) ""))
|
||||
(create-at (plist-get post :create_at))
|
||||
(time-str (if create-at
|
||||
(format-time-string "%H:%M" (seconds-to-time (/ create-at 1000)))
|
||||
"??:??"))
|
||||
;; Используем user_display_name, если есть, иначе user_id
|
||||
(sender (or (plist-get post :user_display_name)
|
||||
(plist-get post :user_id)
|
||||
"unknown")))
|
||||
(insert (format "[%s] %s: %s\n" time-str sender msg-text))))
|
||||
|
||||
(insert "\n")
|
||||
(goto-char (point-max))))
|
||||
(dolist (post mattermost--posts)
|
||||
(insert (mattermost--format-post post))
|
||||
(insert "\n"))
|
||||
(insert (propertize "> " 'face 'mattermost-sender-face))
|
||||
(setq mattermost--input-start (point))
|
||||
(insert mattermost--input-text)
|
||||
(cond
|
||||
((or was-in-draft was-at-bottom)
|
||||
(goto-char (if draft-offset
|
||||
(min (+ mattermost--input-start draft-offset) (point-max))
|
||||
(point-max)))
|
||||
(when win
|
||||
(set-window-point win (point))
|
||||
(with-selected-window win
|
||||
(recenter -1))))
|
||||
(t
|
||||
(goto-char (min old-point (max 1 (1- mattermost--input-start))))
|
||||
(when win
|
||||
(set-window-start win old-window-start t)
|
||||
(set-window-point win (point)))))))
|
||||
|
||||
(defun mattermost-channel-refresh ()
|
||||
"Reload message history for the current channel."
|
||||
"Reload message history, keeping the current draft."
|
||||
(interactive)
|
||||
(message "[MM-DEBUG] Refreshing channel...")
|
||||
(mattermost-channel-load-history))
|
||||
|
||||
(defun mattermost-channel-send-message ()
|
||||
"Send a message to the current channel.
|
||||
The message will appear automatically via WebSocket fan-out; no refresh needed."
|
||||
(defun mattermost-channel-self-insert ()
|
||||
"Jump to the draft before inserting a character typed in history."
|
||||
(interactive)
|
||||
(unless (mattermost--in-draft-p)
|
||||
(goto-char (point-max)))
|
||||
(self-insert-command 1))
|
||||
|
||||
(defun mattermost-channel-space (arg)
|
||||
"Insert a space in the draft; scroll down when in history."
|
||||
(interactive "p")
|
||||
(if (mattermost--in-draft-p)
|
||||
(self-insert-command arg)
|
||||
(scroll-up-command arg)))
|
||||
|
||||
(defun mattermost-channel-backspace (arg)
|
||||
"Delete backwards in the draft; scroll up when in history."
|
||||
(interactive "p")
|
||||
(if (mattermost--in-draft-p)
|
||||
(delete-backward-char arg)
|
||||
(scroll-down-command arg)))
|
||||
|
||||
(defun mattermost-channel-g ()
|
||||
"Insert g in the draft; refresh history otherwise."
|
||||
(interactive)
|
||||
(if (mattermost--in-draft-p)
|
||||
(self-insert-command 1)
|
||||
(mattermost-channel-refresh)))
|
||||
|
||||
(defun mattermost-channel-q ()
|
||||
"Insert q in the draft; quit window otherwise."
|
||||
(interactive)
|
||||
(if (mattermost--in-draft-p)
|
||||
(self-insert-command 1)
|
||||
(quit-window)))
|
||||
|
||||
(defun mattermost-channel-h ()
|
||||
"Insert the typed key in the draft; describe mode otherwise."
|
||||
(interactive)
|
||||
(if (mattermost--in-draft-p)
|
||||
(self-insert-command 1)
|
||||
(describe-mode)))
|
||||
|
||||
(defun mattermost-channel-ret ()
|
||||
"In the draft send the message; in history open the file link."
|
||||
(interactive)
|
||||
(if (mattermost--in-draft-p)
|
||||
(mattermost-channel-send-message)
|
||||
(mattermost-channel-open-link)))
|
||||
|
||||
(defun mattermost-channel-send-message ()
|
||||
"Send the draft text to the current channel and clear the draft."
|
||||
(interactive)
|
||||
(when mattermost--sending
|
||||
(user-error "Message send already in progress"))
|
||||
(let* ((server-id mattermost--server-id)
|
||||
(channel-id mattermost--channel-id)
|
||||
(msg (read-string "Message: ")))
|
||||
(when (string-empty-p msg)
|
||||
(error "Message cannot be empty"))
|
||||
|
||||
(message "[MM-DEBUG] Sending message to channel %s..." channel-id)
|
||||
(buf (current-buffer))
|
||||
(msg (if (and mattermost--input-start
|
||||
(>= (point-max) mattermost--input-start))
|
||||
(buffer-substring-no-properties
|
||||
mattermost--input-start (point-max))
|
||||
mattermost--input-text)))
|
||||
(when (string-empty-p (string-trim msg))
|
||||
(user-error "Message is empty"))
|
||||
(setq mattermost--sending t)
|
||||
(mattermost--render-channel-buffer "")
|
||||
(mattermost--send-request
|
||||
"send_post"
|
||||
(list :server_id server-id
|
||||
:channel_id channel-id
|
||||
:message msg)
|
||||
(lambda (response)
|
||||
(if (plist-get response :ok)
|
||||
(message "[MM] Message sent. Waiting for WS echo...")
|
||||
(message "[MM] Failed to send message: %S" (plist-get response :error)))))))
|
||||
(when (buffer-live-p buf)
|
||||
(with-current-buffer buf
|
||||
(setq mattermost--sending nil)
|
||||
(unless (plist-get response :ok)
|
||||
(mattermost--render-channel-buffer msg)
|
||||
(message "[MM] Failed to send message: %S"
|
||||
(plist-get response :error)))))))))
|
||||
|
||||
(defun mattermost-channel-open-link ()
|
||||
"Download the file attachment under point and open it with xdg-open."
|
||||
(interactive)
|
||||
(let ((file-id (get-text-property (point) 'mm-file-id))
|
||||
(file-name (get-text-property (point) 'mm-file-name)))
|
||||
(cond
|
||||
((and file-id file-name)
|
||||
(let ((server-id mattermost--server-id)
|
||||
(download-dir (expand-file-name mattermost-download-dir)))
|
||||
(unless server-id
|
||||
(error "No server ID associated with this buffer"))
|
||||
(message "[MM] Downloading file: %s to %s..." file-name download-dir)
|
||||
(mattermost--send-request
|
||||
"download_file"
|
||||
(list :server_id server-id
|
||||
:file_id file-id
|
||||
:file_name file-name
|
||||
:download_dir download-dir)
|
||||
(lambda (response)
|
||||
(if (plist-get response :ok)
|
||||
(let* ((result (plist-get response :result))
|
||||
(local-path (plist-get result :local_path)))
|
||||
(message "[MM] File saved to: %s" local-path)
|
||||
(start-process "xdg-open" nil "xdg-open" local-path))
|
||||
(message "[MM] Failed to download file: %S"
|
||||
(plist-get response :error)))))))
|
||||
(t
|
||||
(message "[MM] No downloadable link under point.")))))
|
||||
|
||||
(defun mattermost-channel-on-posted (params)
|
||||
"Handle a 'posted' event. PARAMS should contain the 'post' plist."
|
||||
"Handle a 'posted' event: append the post and re-render, keeping the draft."
|
||||
(let* ((post (plist-get params :post))
|
||||
(channel-id (plist-get post :channel_id))
|
||||
(msg-text (or (plist-get post :message) ""))
|
||||
(create-at (plist-get post :create_at))
|
||||
(time-str (if create-at
|
||||
(format-time-string "%H:%M" (seconds-to-time (/ create-at 1000)))
|
||||
"??:??"))
|
||||
(sender (or (plist-get post :user_display_name)
|
||||
(plist-get post :user_id)
|
||||
"unknown")))
|
||||
(channel-id (plist-get post :channel_id)))
|
||||
(dolist (buf (buffer-list))
|
||||
(with-current-buffer buf
|
||||
(when (and (eq major-mode 'mattermost-channel-mode)
|
||||
(string= mattermost--channel-id channel-id))
|
||||
(let ((inhibit-read-only t))
|
||||
(goto-char (point-max))
|
||||
(insert (format "[%s] %s: %s\n" time-str sender msg-text))
|
||||
(when (= (point) (point-max))
|
||||
(goto-char (point-max)))))))))
|
||||
(setq mattermost--posts (append mattermost--posts (list post)))
|
||||
(mattermost--render-channel-buffer))))))
|
||||
|
||||
(provide 'mattermost-channel)
|
||||
|
||||
@@ -42,4 +42,14 @@ If `inline', show replies in the main buffer."
|
||||
:type 'string
|
||||
:group 'mattermost)
|
||||
|
||||
(defcustom mattermost-download-dir "~/Downloads"
|
||||
"Directory where downloaded files are saved."
|
||||
:type 'directory
|
||||
:group 'mattermost)
|
||||
|
||||
(defface mattermost-sender-face
|
||||
'((t (:weight bold)))
|
||||
"Face used for message sender names in channel buffers."
|
||||
:group 'mattermost)
|
||||
|
||||
(provide 'mattermost-custom)
|
||||
|
||||
+190
-80
@@ -5,133 +5,243 @@
|
||||
(require 'mattermost-channel)
|
||||
|
||||
(defvar mattermost--current-server-id nil
|
||||
"Current server ID for the dashboard buffer.")
|
||||
"Server id owning the current dashboard buffer.")
|
||||
(defvar mattermost--channels nil
|
||||
"Last channel list rendered in this buffer.")
|
||||
(defvar mattermost--teams nil
|
||||
"Last team list rendered in this buffer.")
|
||||
(defvar mattermost--collapsed-teams nil
|
||||
"List of team IDs currently collapsed in the dashboard.")
|
||||
|
||||
(defvar mattermost-dashboard-mode-map
|
||||
(let ((map (make-sparse-keymap)))
|
||||
(define-key map (kbd "RET") #'mattermost-dashboard-open-channel)
|
||||
(define-key map (kbd "TAB") #'mattermost-dashboard-toggle-section)
|
||||
(define-key map (kbd "<backtab>") #'mattermost-dashboard-toggle-all)
|
||||
(define-key map (kbd "g") #'mattermost-dashboard-refresh)
|
||||
map)
|
||||
"Keymap for `mattermost-dashboard-mode`.")
|
||||
"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}"
|
||||
(define-derived-mode mattermost-dashboard-mode special-mode "Mattermost"
|
||||
"Major mode for the Mattermost channel list.
|
||||
\\{mattermost-dashboard-mode-map}
|
||||
TAB on a team header collapses/expands its section.
|
||||
S-TAB (backtab) collapses/expands all sections."
|
||||
(setq buffer-read-only t)
|
||||
(setq truncate-lines t))
|
||||
(setq truncate-lines t)
|
||||
(add-to-invisibility-spec 'mm-section))
|
||||
|
||||
(defun mattermost-reset-state ()
|
||||
"Reset all connection state and clear pending requests."
|
||||
"Reset bridge connection state and pending requests."
|
||||
(interactive)
|
||||
(when (and (boundp 'mattermost--process) mattermost--process (process-live-p mattermost--process))
|
||||
(when (and mattermost--process (process-live-p mattermost--process))
|
||||
(delete-process mattermost--process))
|
||||
(setq mattermost--process nil)
|
||||
(setq mattermost--pending-requests (make-hash-table :test 'equal))
|
||||
(setq mattermost--input-buffer "")
|
||||
(message "[MM] State reset complete. Ready to reconnect."))
|
||||
(setq mattermost--collapsed-teams nil)
|
||||
(when (get-buffer "*Mattermost Dashboard*")
|
||||
(kill-buffer "*Mattermost Dashboard*"))
|
||||
(message "[MM] State reset complete."))
|
||||
|
||||
(defun mattermost-ensure-connected (callback)
|
||||
"Ensure connection to the bridge, prompting for missing credentials."
|
||||
(let* ((url (if (string= mattermost-server-url "")
|
||||
(read-string "Mattermost URL (e.g., https://mattermost.local): ")
|
||||
"Connect to bridge and Mattermost, then call CALLBACK with server-id."
|
||||
(let* ((url (if (string-empty-p mattermost-server-url)
|
||||
(read-string "Mattermost URL: ")
|
||||
mattermost-server-url))
|
||||
(login (if (string= mattermost-login-id "")
|
||||
(read-string "Login ID or Email: ")
|
||||
(login (if (string-empty-p mattermost-login-id)
|
||||
(read-string "Login ID or email: ")
|
||||
mattermost-login-id))
|
||||
(password (read-passwd "Password (or PAT token): "))
|
||||
(password (read-passwd "Password: "))
|
||||
(server-id mattermost-server-id))
|
||||
|
||||
(when (string= mattermost-server-url "")
|
||||
(when (string-empty-p mattermost-server-url)
|
||||
(customize-save-variable 'mattermost-server-url url))
|
||||
(when (string= mattermost-login-id "")
|
||||
(when (string-empty-p mattermost-login-id)
|
||||
(customize-save-variable 'mattermost-login-id login))
|
||||
|
||||
(unless (and (boundp 'mattermost--process)
|
||||
mattermost--process
|
||||
(process-live-p mattermost--process))
|
||||
(unless (and mattermost--process (process-live-p mattermost--process))
|
||||
(mattermost-connect-to-bridge))
|
||||
|
||||
(message "[MM-DEBUG] Connecting to %s as %s (password masked)" url 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)
|
||||
(list :server_id server-id :url url :login_id login :password password)
|
||||
(lambda (response)
|
||||
(if (plist-get response :ok)
|
||||
(progn
|
||||
(message "[MM] Connected successfully.")
|
||||
(message "[MM] Connected.")
|
||||
(funcall callback server-id))
|
||||
(message "[MM] Connect failed: %S" (plist-get response :error)))))))
|
||||
|
||||
(defun mattermost-dashboard ()
|
||||
"Open the Mattermost dashboard showing available channels."
|
||||
"Open the Mattermost dashboard."
|
||||
(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))))))))
|
||||
(mattermost-ensure-connected #'mattermost--request-channels))
|
||||
|
||||
(defun mattermost--render-dashboard (server-id channels)
|
||||
"Render CHANNELS in a new Mattermost Dashboard buffer."
|
||||
(let ((buf (get-buffer-create "*Mattermost Dashboard*")))
|
||||
(defun mattermost--request-channels (server-id)
|
||||
"Fetch channels and teams for SERVER-ID, then render the dashboard."
|
||||
(message "[MM-DEBUG] Requesting list_channels for %s" server-id)
|
||||
(mattermost--send-request
|
||||
"list_channels"
|
||||
(list :server_id server-id)
|
||||
(lambda (response)
|
||||
(if (plist-get response :ok)
|
||||
(let ((result (plist-get response :result)))
|
||||
(mattermost--render-dashboard
|
||||
server-id
|
||||
(plist-get result :channels)
|
||||
(plist-get result :teams)))
|
||||
(message "[MM] list_channels failed: %S" (plist-get response :error))))))
|
||||
|
||||
(defun mattermost--insert-team-header (title)
|
||||
"Insert a section header TITLE with collapse marker. Return (start . end)."
|
||||
(let ((start (point)))
|
||||
(insert (format "%s ▼\n" title))
|
||||
(put-text-property start (point) 'face 'mattermost-sender-face)
|
||||
(cons start (point))))
|
||||
|
||||
(defun mattermost--insert-channel-line (ch)
|
||||
"Insert one selectable line for channel CH."
|
||||
(let* ((id (plist-get ch :id))
|
||||
(type (or (plist-get ch :type) "?"))
|
||||
(name (or (plist-get ch :display_name) ""))
|
||||
(label (if (string-empty-p name) (or (plist-get ch :name) id) name))
|
||||
(line (format " [%s] %s\n" type label)))
|
||||
(insert (propertize line
|
||||
'mm-channel-id id
|
||||
'mm-channel-name label
|
||||
'mouse-face 'highlight))))
|
||||
|
||||
(defun mattermost--sort-channels-by-activity (channels)
|
||||
"Sort CHANNELS by last_post_at descending."
|
||||
(sort channels
|
||||
(lambda (a b)
|
||||
(> (or (plist-get a :last_post_at) 0)
|
||||
(or (plist-get b :last_post_at) 0)))))
|
||||
|
||||
(defun mattermost--set-header-marker (start end marker)
|
||||
"Replace the collapse marker between START and END with MARKER.
|
||||
Caller must bind `inhibit-read-only'."
|
||||
(save-excursion
|
||||
(goto-char start)
|
||||
(when (re-search-forward "[▼▶]" end t)
|
||||
(replace-match marker t t))))
|
||||
|
||||
(defun mattermost--collapse-section (overlay collapse)
|
||||
"Set COLLAPSE state on section OVERLAY and update its header marker."
|
||||
(let ((inhibit-read-only t)
|
||||
(team-id (overlay-get overlay 'mm-team-id)))
|
||||
(overlay-put overlay 'invisible (and collapse 'mm-section))
|
||||
(mattermost--set-header-marker
|
||||
(overlay-get overlay 'mm-header-start)
|
||||
(overlay-get overlay 'mm-header-end)
|
||||
(if collapse "▶" "▼"))
|
||||
(if collapse
|
||||
(unless (member team-id mattermost--collapsed-teams)
|
||||
(setq mattermost--collapsed-teams
|
||||
(cons team-id mattermost--collapsed-teams)))
|
||||
(setq mattermost--collapsed-teams
|
||||
(delete team-id mattermost--collapsed-teams)))))
|
||||
|
||||
(defun mattermost-dashboard-toggle-section ()
|
||||
"Toggle visibility of the section whose header is at point."
|
||||
(interactive)
|
||||
(let ((overlay (get-text-property (point) 'mm-section-overlay)))
|
||||
(if (not overlay)
|
||||
(message "[MM] Not on a team header.")
|
||||
(mattermost--collapse-section overlay (not (overlay-get overlay 'invisible)))
|
||||
(message "[MM-DEBUG] collapsed-teams=%S" mattermost--collapsed-teams))))
|
||||
|
||||
(defun mattermost-dashboard-toggle-all ()
|
||||
"Collapse or expand all team sections."
|
||||
(interactive)
|
||||
(let ((overlays nil)
|
||||
(any-expanded nil))
|
||||
(save-excursion
|
||||
(goto-char (point-min))
|
||||
(while (not (eobp))
|
||||
(let ((ov (get-text-property (point) 'mm-section-overlay)))
|
||||
(when (and ov (not (memq ov overlays)))
|
||||
(push ov overlays)
|
||||
(unless (overlay-get ov 'invisible)
|
||||
(setq any-expanded t))))
|
||||
(forward-line 1)))
|
||||
(dolist (ov overlays)
|
||||
(mattermost--collapse-section ov any-expanded))
|
||||
(message "[MM-DEBUG] collapsed-teams=%S" mattermost--collapsed-teams)))
|
||||
|
||||
(defun mattermost--insert-section (title team-id channels)
|
||||
"Insert section TITLE for TEAM-ID with CHANNELS, honouring collapse state."
|
||||
(let* ((header (mattermost--insert-team-header title))
|
||||
(section-start (point)))
|
||||
(dolist (ch channels)
|
||||
(mattermost--insert-channel-line ch))
|
||||
(let ((ov (make-overlay section-start (point))))
|
||||
(overlay-put ov 'mm-header-start (car header))
|
||||
(overlay-put ov 'mm-header-end (cdr header))
|
||||
(overlay-put ov 'mm-team-id team-id)
|
||||
(put-text-property (car header) (cdr header) 'mm-section-overlay ov)
|
||||
(when (member team-id mattermost--collapsed-teams)
|
||||
(overlay-put ov 'invisible 'mm-section)
|
||||
(mattermost--set-header-marker (car header) (cdr header) "▶")))))
|
||||
|
||||
(defun mattermost--render-dashboard (server-id channels teams)
|
||||
"Render CHANNELS grouped by TEAMS for SERVER-ID, preserving collapse state."
|
||||
(message "[MM-DEBUG] Rendering: collapsed-teams=%S" mattermost--collapsed-teams)
|
||||
(let ((by-team (make-hash-table :test 'equal))
|
||||
(dms nil)
|
||||
(buf (get-buffer-create "*Mattermost Dashboard*")))
|
||||
(setq channels (mattermost--sort-channels-by-activity channels))
|
||||
(dolist (ch channels)
|
||||
(if (member (plist-get ch :type) '("D" "G"))
|
||||
(push ch dms)
|
||||
(let* ((tid (or (plist-get ch :team_id) ""))
|
||||
(prev (gethash tid by-team)))
|
||||
(puthash tid (cons ch prev) by-team))))
|
||||
(with-current-buffer buf
|
||||
(let ((inhibit-read-only t))
|
||||
(erase-buffer)
|
||||
(mattermost-dashboard-mode)
|
||||
(erase-buffer)
|
||||
(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))))
|
||||
|
||||
(setq-local mattermost--teams teams)
|
||||
(insert "Mattermost channels RET open · TAB toggle · g refresh\n\n")
|
||||
(let ((rendered (make-hash-table :test 'equal)))
|
||||
(dolist (team teams)
|
||||
(let* ((tid (plist-get team :id))
|
||||
(chs (gethash tid by-team)))
|
||||
(when chs
|
||||
(puthash tid t rendered)
|
||||
(mattermost--insert-section
|
||||
(plist-get team :display_name) tid (nreverse chs))
|
||||
(insert "\n"))))
|
||||
(maphash
|
||||
(lambda (tid chs)
|
||||
(unless (gethash tid rendered)
|
||||
(mattermost--insert-section
|
||||
(if (string-empty-p tid) "Other" tid) tid (nreverse chs))
|
||||
(insert "\n")))
|
||||
by-team))
|
||||
(when dms
|
||||
(mattermost--insert-section "Direct messages" "dms" (nreverse dms))
|
||||
(insert "\n"))
|
||||
(goto-char (point-min))))
|
||||
(switch-to-buffer buf)))
|
||||
|
||||
(defun mattermost-dashboard-refresh ()
|
||||
"Refresh the channel list in the current dashboard buffer."
|
||||
"Refresh the channel list, preserving collapse state."
|
||||
(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)))))))
|
||||
(unless mattermost--current-server-id
|
||||
(error "No server ID associated with this buffer"))
|
||||
(mattermost--request-channels mattermost--current-server-id))
|
||||
|
||||
(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))
|
||||
(server-id mattermost--current-server-id)
|
||||
(channel-name (if (string-match "\\] \\(.+\\) (ID:" line)
|
||||
(match-string 1 line)
|
||||
"Unknown")))
|
||||
(if server-id
|
||||
(mattermost-channel-open server-id channel-id channel-name)
|
||||
(error "No server ID associated with this dashboard")))
|
||||
(message "[MM] No channel ID found on this line."))))
|
||||
(let ((id (get-text-property (point) 'mm-channel-id))
|
||||
(name (get-text-property (point) 'mm-channel-name)))
|
||||
(cond
|
||||
((not id) (message "[MM] No channel on this line."))
|
||||
((not mattermost--current-server-id)
|
||||
(error "No server ID associated with this dashboard"))
|
||||
(t (mattermost-channel-open mattermost--current-server-id id name)))))
|
||||
|
||||
(provide 'mattermost-dashboard)
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
;;; mattermost-files.el --- File attachment helpers -*- lexical-binding: t; -*-
|
||||
|
||||
(require 'mattermost-custom)
|
||||
(require 'mattermost-protocol)
|
||||
|
||||
(defun mattermost--format-file-size (bytes)
|
||||
"Format BYTES as human-readable size."
|
||||
(cond
|
||||
((< bytes 1024) (format "%d B" bytes))
|
||||
((< bytes (* 1024 1024)) (format "%.1f KB" (/ bytes 1024.0)))
|
||||
((< bytes (* 1024 1024 1024)) (format "%.1f MB" (/ bytes (* 1024.0 1024.0))))
|
||||
(t (format "%.1f GB" (/ bytes (* 1024.0 1024.0 1024.0))))))
|
||||
|
||||
(defun mattermost--format-file-block (files)
|
||||
"Return a propertized multi-line string describing FILES plist list."
|
||||
(mapconcat
|
||||
(lambda (f)
|
||||
(let* ((name (or (plist-get f :name) "unknown"))
|
||||
(size (or (plist-get f :size) 0))
|
||||
(id (plist-get f :id)))
|
||||
(propertize
|
||||
(format " 📎 %s (%s)\n" name (mattermost--format-file-size size))
|
||||
'mm-file-id id
|
||||
'mm-file-name name
|
||||
'mouse-face 'highlight
|
||||
'help-echo "RET to download and open")))
|
||||
files
|
||||
""))
|
||||
|
||||
(provide 'mattermost-files)
|
||||
Reference in New Issue
Block a user