slack-rs 0.1.70

A Slack CLI tool with OAuth authentication, profile management, and API access
Documentation
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
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
//! Users cache for mention resolution
//!
//! Provides caching for user information to enable mention resolution
//! without repeated API calls. Cache is stored per workspace with TTL.

use crate::api::{ApiClient, ApiError};
use regex::Regex;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::fs;
use std::path::{Path, PathBuf};
use std::time::{SystemTime, UNIX_EPOCH};

/// Default cache TTL in seconds (24 hours)
const DEFAULT_TTL_SECONDS: u64 = 86400;

/// Cached user information
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct CachedUser {
    pub id: String,
    pub name: String,
    pub real_name: Option<String>,
    pub display_name: Option<String>,
    pub deleted: bool,
    pub is_bot: bool,
}

/// Workspace-specific user cache
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct WorkspaceCache {
    pub team_id: String,
    pub updated_at: u64,
    pub users: HashMap<String, CachedUser>,
}

/// Users cache file containing multiple workspace caches
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct UsersCacheFile {
    pub caches: HashMap<String, WorkspaceCache>,
}

impl UsersCacheFile {
    /// Create a new empty cache file
    pub fn new() -> Self {
        Self {
            caches: HashMap::new(),
        }
    }

    /// Get the default cache file path
    pub fn default_path() -> Result<PathBuf, String> {
        directories::ProjectDirs::from("", "", "slack-rs")
            .map(|dirs| dirs.config_dir().join("users_cache.json"))
            .ok_or_else(|| "Could not determine config directory".to_string())
    }

    /// Load cache from file
    pub fn load(path: &Path) -> Result<Self, String> {
        if !path.exists() {
            return Ok(Self::new());
        }

        let content =
            fs::read_to_string(path).map_err(|e| format!("Failed to read cache file: {}", e))?;
        serde_json::from_str(&content).map_err(|e| format!("Failed to parse cache file: {}", e))
    }

    /// Save cache to file
    pub fn save(&self, path: &Path) -> Result<(), String> {
        if let Some(parent) = path.parent() {
            fs::create_dir_all(parent)
                .map_err(|e| format!("Failed to create cache directory: {}", e))?;
        }

        let content = serde_json::to_string_pretty(self)
            .map_err(|e| format!("Failed to serialize cache: {}", e))?;
        fs::write(path, content).map_err(|e| format!("Failed to write cache file: {}", e))
    }

    /// Get workspace cache
    pub fn get_workspace(&self, team_id: &str) -> Option<&WorkspaceCache> {
        self.caches.get(team_id)
    }

    /// Set workspace cache
    pub fn set_workspace(&mut self, cache: WorkspaceCache) {
        self.caches.insert(cache.team_id.clone(), cache);
    }

    /// Check if workspace cache is expired
    pub fn is_expired(&self, team_id: &str, ttl_seconds: u64) -> bool {
        match self.get_workspace(team_id) {
            Some(cache) => {
                let now = SystemTime::now()
                    .duration_since(UNIX_EPOCH)
                    .unwrap()
                    .as_secs();
                now - cache.updated_at > ttl_seconds
            }
            None => true, // No cache means expired
        }
    }
}

impl Default for UsersCacheFile {
    fn default() -> Self {
        Self::new()
    }
}

/// Format option for mention resolution
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum MentionFormat {
    DisplayName,
    RealName,
    Username,
}

impl std::str::FromStr for MentionFormat {
    type Err = String;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "display_name" => Ok(Self::DisplayName),
            "real_name" => Ok(Self::RealName),
            "username" => Ok(Self::Username),
            _ => Err(format!("Invalid format: {}", s)),
        }
    }
}

/// Fetch all users from Slack API with pagination
///
/// # Arguments
/// * `client` - API client with authentication
/// * `team_id` - Team ID for the workspace
///
/// # Returns
/// * `Ok(WorkspaceCache)` with all users
/// * `Err(ApiError)` if the operation fails
pub async fn fetch_all_users(
    client: &ApiClient,
    team_id: String,
) -> Result<WorkspaceCache, ApiError> {
    let mut all_users = HashMap::new();
    let mut cursor: Option<String> = None;
    let limit = 200;

    loop {
        let mut params = HashMap::new();
        params.insert("limit".to_string(), serde_json::json!(limit));
        if let Some(c) = &cursor {
            params.insert("cursor".to_string(), serde_json::json!(c));
        }

        let response = client
            .call_method(crate::api::ApiMethod::UsersList, params)
            .await?;

        // Extract users from response
        if let Some(members) = response.data.get("members").and_then(|v| v.as_array()) {
            for member in members {
                if let Some(user) = parse_user_from_json(member) {
                    all_users.insert(user.id.clone(), user);
                }
            }
        }

        // Check for next cursor
        cursor = response
            .data
            .get("response_metadata")
            .and_then(|v| v.get("next_cursor"))
            .and_then(|v| v.as_str())
            .filter(|s| !s.is_empty())
            .map(|s| s.to_string());

        if cursor.is_none() {
            break;
        }
    }

    let now = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap()
        .as_secs();

    Ok(WorkspaceCache {
        team_id,
        updated_at: now,
        users: all_users,
    })
}

/// Parse user from JSON value
fn parse_user_from_json(value: &serde_json::Value) -> Option<CachedUser> {
    let id = value.get("id")?.as_str()?.to_string();
    let name = value.get("name")?.as_str()?.to_string();

    let profile = value.get("profile");
    let display_name = profile
        .and_then(|p| p.get("display_name"))
        .and_then(|v| v.as_str())
        .filter(|s| !s.is_empty())
        .map(|s| s.to_string());

    let real_name = profile
        .and_then(|p| p.get("real_name"))
        .and_then(|v| v.as_str())
        .filter(|s| !s.is_empty())
        .map(|s| s.to_string());

    let deleted = value
        .get("deleted")
        .and_then(|v| v.as_bool())
        .unwrap_or(false);
    let is_bot = value
        .get("is_bot")
        .and_then(|v| v.as_bool())
        .unwrap_or(false);

    Some(CachedUser {
        id,
        name,
        real_name,
        display_name,
        deleted,
        is_bot,
    })
}

/// Resolve mentions in text using cache
///
/// # Arguments
/// * `text` - Input text containing mentions
/// * `cache` - Workspace cache with user information
/// * `format` - Format to use for resolved mentions
///
/// # Returns
/// Text with mentions resolved to user names
pub fn resolve_mentions(text: &str, cache: &WorkspaceCache, format: MentionFormat) -> String {
    let mention_regex = Regex::new(r"<@(U[A-Z0-9]+)(?:\|[^>]+)?>").unwrap();

    mention_regex
        .replace_all(text, |caps: &regex::Captures| {
            let user_id = &caps[1];
            match cache.users.get(user_id) {
                Some(user) => {
                    let name = match format {
                        MentionFormat::DisplayName => user
                            .display_name
                            .as_deref()
                            .or(Some(&user.name))
                            .unwrap_or(&user.name),
                        MentionFormat::RealName => user.real_name.as_deref().unwrap_or(&user.name),
                        MentionFormat::Username => &user.name,
                    };

                    format!("@{}", name)
                }
                None => caps[0].to_string(), // Keep original if not found
            }
        })
        .to_string()
}

/// Update users cache for a workspace
///
/// # Arguments
/// * `client` - API client
/// * `team_id` - Team ID
/// * `force` - Force update even if cache is not expired
///
/// # Returns
/// * `Ok(())` if successful
/// * `Err(String)` if the operation fails
pub async fn update_cache(client: &ApiClient, team_id: String, force: bool) -> Result<(), String> {
    let cache_path = UsersCacheFile::default_path()?;
    let mut cache_file = UsersCacheFile::load(&cache_path)?;

    // Check if update is needed
    if !force && !cache_file.is_expired(&team_id, DEFAULT_TTL_SECONDS) {
        return Err("Cache is still valid. Use --force to update anyway.".to_string());
    }

    // Fetch users
    let workspace_cache = fetch_all_users(client, team_id)
        .await
        .map_err(|e| format!("Failed to fetch users: {}", e))?;

    // Update cache
    cache_file.set_workspace(workspace_cache);
    cache_file.save(&cache_path)?;

    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use tempfile::TempDir;
    use wiremock::{
        matchers::{method, path},
        Mock, MockServer, ResponseTemplate,
    };

    #[test]
    fn test_cache_file_new() {
        let cache = UsersCacheFile::new();
        assert!(cache.caches.is_empty());
    }

    #[test]
    fn test_cache_file_save_load() {
        let temp_dir = TempDir::new().unwrap();
        let cache_path = temp_dir.path().join("users_cache.json");

        let mut cache_file = UsersCacheFile::new();
        let workspace = WorkspaceCache {
            team_id: "T123".to_string(),
            updated_at: 1700000000,
            users: HashMap::new(),
        };
        cache_file.set_workspace(workspace);

        cache_file.save(&cache_path).unwrap();
        assert!(cache_path.exists());

        let loaded = UsersCacheFile::load(&cache_path).unwrap();
        assert_eq!(cache_file, loaded);
    }

    #[test]
    fn test_cache_expiration() {
        let mut cache_file = UsersCacheFile::new();
        let now = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_secs();

        // Recent cache should not be expired
        let workspace = WorkspaceCache {
            team_id: "T123".to_string(),
            updated_at: now - 1000, // 1000 seconds ago
            users: HashMap::new(),
        };
        cache_file.set_workspace(workspace);

        assert!(!cache_file.is_expired("T123", 86400)); // 24 hours TTL

        // Old cache should be expired
        let old_workspace = WorkspaceCache {
            team_id: "T456".to_string(),
            updated_at: now - 100000, // > 24 hours ago
            users: HashMap::new(),
        };
        cache_file.set_workspace(old_workspace);

        assert!(cache_file.is_expired("T456", 86400));

        // Non-existent cache should be expired
        assert!(cache_file.is_expired("T999", 86400));
    }

    #[test]
    fn test_mention_resolution() {
        let mut users = HashMap::new();
        users.insert(
            "U123".to_string(),
            CachedUser {
                id: "U123".to_string(),
                name: "john".to_string(),
                real_name: Some("John Doe".to_string()),
                display_name: Some("johnd".to_string()),
                deleted: false,
                is_bot: false,
            },
        );
        users.insert(
            "U456".to_string(),
            CachedUser {
                id: "U456".to_string(),
                name: "jane".to_string(),
                real_name: Some("Jane Smith".to_string()),
                display_name: None,
                deleted: true,
                is_bot: false,
            },
        );

        let cache = WorkspaceCache {
            team_id: "T123".to_string(),
            updated_at: 1700000000,
            users,
        };

        // Test display_name format
        let text = "Hello <@U123> and <@U456>!";
        let result = resolve_mentions(text, &cache, MentionFormat::DisplayName);
        assert_eq!(result, "Hello @johnd and @jane!");

        // Test real_name format
        let result = resolve_mentions(text, &cache, MentionFormat::RealName);
        assert_eq!(result, "Hello @John Doe and @Jane Smith!");

        // Test username format
        let result = resolve_mentions(text, &cache, MentionFormat::Username);
        assert_eq!(result, "Hello @john and @jane!");

        // Test unknown user
        let text_unknown = "Hello <@U999>!";
        let result = resolve_mentions(text_unknown, &cache, MentionFormat::DisplayName);
        assert_eq!(result, "Hello <@U999>!");

        // Test mention with pipe notation
        let text_pipe = "Hello <@U123|john>!";
        let result = resolve_mentions(text_pipe, &cache, MentionFormat::DisplayName);
        assert_eq!(result, "Hello @johnd!");
    }

    #[test]
    fn test_parse_user_from_json() {
        let json = serde_json::json!({
            "id": "U123",
            "name": "john",
            "profile": {
                "display_name": "johnd",
                "real_name": "John Doe"
            },
            "deleted": false,
            "is_bot": false
        });

        let user = parse_user_from_json(&json).unwrap();
        assert_eq!(user.id, "U123");
        assert_eq!(user.name, "john");
        assert_eq!(user.display_name, Some("johnd".to_string()));
        assert_eq!(user.real_name, Some("John Doe".to_string()));
        assert!(!user.deleted);
        assert!(!user.is_bot);
    }

    #[test]
    fn test_mention_format_from_str() {
        use std::str::FromStr;
        assert_eq!(
            MentionFormat::from_str("display_name"),
            Ok(MentionFormat::DisplayName)
        );
        assert_eq!(
            MentionFormat::from_str("real_name"),
            Ok(MentionFormat::RealName)
        );
        assert_eq!(
            MentionFormat::from_str("username"),
            Ok(MentionFormat::Username)
        );
        assert!(MentionFormat::from_str("invalid").is_err());
    }

    #[tokio::test]
    async fn test_fetch_all_users_with_pagination() {
        let mock_server = MockServer::start().await;

        // First page response
        let first_response = serde_json::json!({
            "ok": true,
            "members": [
                {
                    "id": "U001",
                    "name": "user1",
                    "profile": {
                        "display_name": "User One",
                        "real_name": "User One"
                    },
                    "deleted": false,
                    "is_bot": false
                },
                {
                    "id": "U002",
                    "name": "user2",
                    "profile": {
                        "display_name": "User Two",
                        "real_name": "User Two"
                    },
                    "deleted": false,
                    "is_bot": false
                }
            ],
            "response_metadata": {
                "next_cursor": "cursor123"
            }
        });

        // Second page response
        let second_response = serde_json::json!({
            "ok": true,
            "members": [
                {
                    "id": "U003",
                    "name": "user3",
                    "profile": {
                        "display_name": "User Three",
                        "real_name": "User Three"
                    },
                    "deleted": false,
                    "is_bot": false
                }
            ],
            "response_metadata": {
                "next_cursor": ""
            }
        });

        // Use up() to respond to first request
        Mock::given(method("GET"))
            .and(path("/users.list"))
            .respond_with(
                ResponseTemplate::new(200)
                    .set_body_json(&first_response)
                    .append_header("content-type", "application/json"),
            )
            .up_to_n_times(1)
            .mount(&mock_server)
            .await;

        // Use up() to respond to second request
        Mock::given(method("GET"))
            .and(path("/users.list"))
            .respond_with(
                ResponseTemplate::new(200)
                    .set_body_json(&second_response)
                    .append_header("content-type", "application/json"),
            )
            .mount(&mock_server)
            .await;

        let client =
            crate::api::ApiClient::new_with_base_url("test-token".to_string(), mock_server.uri());

        let result = fetch_all_users(&client, "T123".to_string()).await;
        assert!(result.is_ok());

        let cache = result.unwrap();
        assert_eq!(cache.team_id, "T123");
        assert_eq!(cache.users.len(), 3);
        assert!(cache.users.contains_key("U001"));
        assert!(cache.users.contains_key("U002"));
        assert!(cache.users.contains_key("U003"));
    }
}