chat-system 0.1.3

A multi-protocol async chat crate — single interface for IRC, Matrix, Discord, Telegram, Slack, Signal, WhatsApp, and more
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
//! Google Chat messenger — Incoming Webhook and Google Chat API implementation.

use crate::message::MessageType;
use crate::{Message, Messenger};
use anyhow::{Context, Result};
use async_trait::async_trait;
use chrono::DateTime;
use reqwest::Client;
use serde_json::{Value, json};
use tokio::sync::Mutex;

pub struct GoogleChatMessenger {
    name: String,
    mode: GoogleChatMode,
    client: Client,
    connected: bool,
}

enum GoogleChatMode {
    Webhook {
        webhook_url: String,
    },
    Api {
        token: String,
        space_id: String,
        spaces: Vec<String>,
        api_base_url: String,
        last_seen_message_name: Mutex<Option<String>>,
    },
    ServiceAccount {
        /// Path to service account JSON file; retained for future full auth implementation.
        #[allow(dead_code)]
        credentials_path: String,
        spaces: Vec<String>,
        api_base_url: String,
        /// Cached access token from service account auth
        access_token: Mutex<Option<String>>,
        last_seen_message_name: Mutex<Option<String>>,
    },
}

impl GoogleChatMessenger {
    pub fn new(name: impl Into<String>, webhook_url: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            mode: GoogleChatMode::Webhook {
                webhook_url: webhook_url.into(),
            },
            client: Client::new(),
            connected: false,
        }
    }

    pub fn new_api(
        name: impl Into<String>,
        token: impl Into<String>,
        space_id: impl Into<String>,
    ) -> Self {
        let space = space_id.into();
        Self {
            name: name.into(),
            mode: GoogleChatMode::Api {
                token: token.into(),
                space_id: space.clone(),
                spaces: vec![space],
                api_base_url: "https://chat.googleapis.com/v1".to_string(),
                last_seen_message_name: Mutex::new(None),
            },
            client: Client::new(),
            connected: false,
        }
    }

    /// Create a Google Chat messenger using a service account credentials file.
    ///
    /// The credentials file should be a JSON file downloaded from the Google Cloud Console
    /// containing the service account's private key and email.
    ///
    /// # Arguments
    /// * `name` - Messenger instance name
    /// * `credentials_path` - Path to the service account JSON credentials file
    /// * `spaces` - List of space IDs to monitor (e.g., ["spaces/ABC123", "spaces/DEF456"])
    pub fn with_credentials(
        name: impl Into<String>,
        credentials_path: impl Into<String>,
        spaces: Vec<impl Into<String>>,
    ) -> Self {
        Self {
            name: name.into(),
            mode: GoogleChatMode::ServiceAccount {
                credentials_path: credentials_path.into(),
                spaces: spaces.into_iter().map(|s| s.into()).collect(),
                api_base_url: "https://chat.googleapis.com/v1".to_string(),
                access_token: Mutex::new(None),
                last_seen_message_name: Mutex::new(None),
            },
            client: Client::new(),
            connected: false,
        }
    }

    /// Add additional spaces to monitor (for API or ServiceAccount modes).
    pub fn with_spaces(mut self, spaces: Vec<impl Into<String>>) -> Self {
        match &mut self.mode {
            GoogleChatMode::Api { spaces: s, .. }
            | GoogleChatMode::ServiceAccount { spaces: s, .. } => {
                s.extend(spaces.into_iter().map(|x| x.into()));
            }
            GoogleChatMode::Webhook { .. } => {}
        }
        self
    }

    pub fn with_api_base_url(mut self, url: impl Into<String>) -> Self {
        if let GoogleChatMode::Api { api_base_url, .. } = &mut self.mode {
            *api_base_url = url.into();
        }
        self
    }

    fn api_url(api_base_url: &str, path: impl AsRef<str>) -> String {
        format!(
            "{}/{}",
            api_base_url.trim_end_matches('/'),
            path.as_ref().trim_start_matches('/')
        )
    }

    async fn api_get_json(&self, path: impl AsRef<str>) -> Result<Value> {
        let (token, api_base_url) = match &self.mode {
            GoogleChatMode::Api {
                token,
                api_base_url,
                ..
            } => (token.clone(), api_base_url.clone()),
            GoogleChatMode::ServiceAccount {
                api_base_url,
                access_token,
                ..
            } => {
                let token = access_token
                    .lock()
                    .await
                    .clone()
                    .ok_or_else(|| anyhow::anyhow!("Service account not initialized"))?;
                (token, api_base_url.clone())
            }
            GoogleChatMode::Webhook { .. } => {
                anyhow::bail!("Google Chat API requested in webhook mode")
            }
        };

        let response = self
            .client
            .get(Self::api_url(&api_base_url, path))
            .bearer_auth(&token)
            .send()
            .await
            .context("Google Chat API request failed")?;
        let status = response.status();
        let body = response
            .text()
            .await
            .context("Failed to read Google Chat API response body")?;

        if !status.is_success() {
            anyhow::bail!("Google Chat API request failed {}: {}", status, body);
        }

        serde_json::from_str(&body).context("Invalid Google Chat API response")
    }

    async fn api_post_json(&self, path: impl AsRef<str>, body: Value) -> Result<Value> {
        let (token, api_base_url) = match &self.mode {
            GoogleChatMode::Api {
                token,
                api_base_url,
                ..
            } => (token.clone(), api_base_url.clone()),
            GoogleChatMode::ServiceAccount {
                api_base_url,
                access_token,
                ..
            } => {
                let token = access_token
                    .lock()
                    .await
                    .clone()
                    .ok_or_else(|| anyhow::anyhow!("Service account not initialized"))?;
                (token, api_base_url.clone())
            }
            GoogleChatMode::Webhook { .. } => {
                anyhow::bail!("Google Chat API requested in webhook mode")
            }
        };

        let response = self
            .client
            .post(Self::api_url(&api_base_url, path))
            .bearer_auth(&token)
            .json(&body)
            .send()
            .await
            .context("Google Chat API request failed")?;
        let status = response.status();
        let response_body = response
            .text()
            .await
            .context("Failed to read Google Chat API response body")?;

        if !status.is_success() {
            anyhow::bail!(
                "Google Chat API request failed {}: {}",
                status,
                response_body
            );
        }

        if response_body.trim().is_empty() {
            Ok(Value::Null)
        } else {
            serde_json::from_str(&response_body).context("Invalid Google Chat API response")
        }
    }

    fn space_path(space_id: &str) -> String {
        format!("spaces/{space_id}")
    }

    fn space_messages_path(space_id: &str) -> String {
        format!("spaces/{space_id}/messages")
    }

    async fn api_receive_messages(&self) -> Result<Vec<Message>> {
        let spaces = match &self.mode {
            GoogleChatMode::Api {
                space_id, spaces, ..
            } => {
                if spaces.is_empty() {
                    vec![space_id.clone()]
                } else {
                    spaces.clone()
                }
            }
            GoogleChatMode::ServiceAccount { spaces, .. } => spaces.clone(),
            GoogleChatMode::Webhook { .. } => return Ok(Vec::new()),
        };

        let last_seen = match &self.mode {
            GoogleChatMode::Api {
                last_seen_message_name,
                ..
            }
            | GoogleChatMode::ServiceAccount {
                last_seen_message_name,
                ..
            } => last_seen_message_name.lock().await.clone(),
            GoogleChatMode::Webhook { .. } => None,
        };

        let mut all_messages = Vec::new();
        let mut newest_name = last_seen.clone();

        for space_id in &spaces {
            let data = self
                .api_get_json(Self::space_messages_path(space_id))
                .await?;
            let mut messages = Vec::new();

            if let Some(entries) = data["messages"].as_array() {
                let mut parsed = Vec::new();

                for entry in entries {
                    let Some(name) = entry["name"].as_str() else {
                        continue;
                    };
                    let content = entry["text"].as_str().unwrap_or("").to_string();
                    if content.is_empty() {
                        continue;
                    }

                    let timestamp = entry["createTime"]
                        .as_str()
                        .and_then(|value| DateTime::parse_from_rfc3339(value).ok())
                        .map(|value| value.timestamp())
                        .unwrap_or_else(|| chrono::Utc::now().timestamp());
                    let sender = entry["sender"]["displayName"]
                        .as_str()
                        .or_else(|| entry["sender"]["name"].as_str())
                        .unwrap_or("unknown")
                        .to_string();
                    let is_direct = entry["space"]["type"].as_str() == Some("DM");

                    parsed.push(Message {
                        id: name.to_string(),
                        sender,
                        content,
                        timestamp,
                        channel: Some(space_id.clone()),
                        reply_to: entry["thread"]["name"].as_str().map(ToString::to_string),
                        thread_id: None,
                        media: None,
                        is_direct,
                        message_type: MessageType::Text,
                        edited_timestamp: None,
                        reactions: None,
                    });
                }

                if let Some(first) = parsed.first() {
                    if newest_name.is_none() || first.id > *newest_name.as_ref().unwrap() {
                        newest_name = Some(first.id.clone());
                    }
                }

                if let Some(seen_name) = &last_seen {
                    for message in parsed {
                        if message.id == *seen_name {
                            break;
                        }
                        messages.push(message);
                    }
                    messages.reverse();
                } else {
                    messages.extend(parsed.into_iter().rev());
                }
            }

            all_messages.extend(messages);
        }

        match &self.mode {
            GoogleChatMode::Api {
                last_seen_message_name,
                ..
            }
            | GoogleChatMode::ServiceAccount {
                last_seen_message_name,
                ..
            } => {
                *last_seen_message_name.lock().await = newest_name;
            }
            GoogleChatMode::Webhook { .. } => {}
        }

        Ok(all_messages)
    }
}

#[async_trait]
impl Messenger for GoogleChatMessenger {
    fn name(&self) -> &str {
        &self.name
    }

    fn messenger_type(&self) -> &str {
        "googlechat"
    }

    async fn initialize(&mut self) -> Result<()> {
        match &self.mode {
            GoogleChatMode::Api { space_id, .. } => {
                self.api_get_json(Self::space_path(space_id)).await?;
            }
            GoogleChatMode::ServiceAccount { spaces, .. } => {
                // Validate by checking at least one space
                if let Some(space) = spaces.first() {
                    self.api_get_json(Self::space_path(space)).await?;
                }
            }
            GoogleChatMode::Webhook { .. } => {}
        }
        self.connected = true;
        Ok(())
    }

    async fn send_message(&self, space: &str, content: &str) -> Result<String> {
        match &self.mode {
            GoogleChatMode::Webhook { webhook_url } => {
                let body = json!({ "text": content });

                let resp = self.client.post(webhook_url).json(&body).send().await?;

                if resp.status().is_success() {
                    Ok(format!(
                        "googlechat:{}",
                        chrono::Utc::now().timestamp_millis()
                    ))
                } else {
                    let status = resp.status();
                    let text = resp.text().await.unwrap_or_default();
                    anyhow::bail!("Google Chat webhook failed {}: {}", status, text);
                }
            }
            GoogleChatMode::Api { space_id, .. } => {
                let target_space = if space.is_empty() { space_id } else { space };
                let data = self
                    .api_post_json(
                        Self::space_messages_path(target_space),
                        json!({ "text": content }),
                    )
                    .await?;

                Ok(data["name"].as_str().unwrap_or_default().to_string())
            }
            GoogleChatMode::ServiceAccount { spaces, .. } => {
                let target_space = if space.is_empty() {
                    spaces
                        .first()
                        .ok_or_else(|| anyhow::anyhow!("No spaces configured"))?
                } else {
                    space
                };
                let data = self
                    .api_post_json(
                        Self::space_messages_path(target_space),
                        json!({ "text": content }),
                    )
                    .await?;

                Ok(data["name"].as_str().unwrap_or_default().to_string())
            }
        }
    }

    async fn receive_messages(&self) -> Result<Vec<Message>> {
        self.api_receive_messages().await
    }

    fn is_connected(&self) -> bool {
        self.connected
    }

    async fn disconnect(&mut self) -> Result<()> {
        match &self.mode {
            GoogleChatMode::Api {
                last_seen_message_name,
                ..
            }
            | GoogleChatMode::ServiceAccount {
                last_seen_message_name,
                ..
            } => {
                *last_seen_message_name.lock().await = None;
            }
            GoogleChatMode::Webhook { .. } => {}
        }
        self.connected = false;
        Ok(())
    }
}