tg-cli 0.2.1

A "unix-like" utility for sending yourself Telegram messages from the terminal
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
use std::{collections::HashMap, fs, path::PathBuf};

use serde::{Deserialize, Serialize};

use crate::secret_store;

#[derive(Serialize, Deserialize, Default, Clone)]
pub(crate) struct ProfileConfig {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub(crate) token: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub(crate) chat_id: Option<i64>,
}

#[derive(Serialize, Deserialize, Default)]
pub(crate) struct ConfigFile {
    // Default profile fields at the top level for backward compatibility
    #[serde(skip_serializing_if = "Option::is_none")]
    pub(crate) token: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub(crate) chat_id: Option<i64>,
    #[serde(default, skip_serializing_if = "HashMap::is_empty")]
    pub(crate) profiles: HashMap<String, ProfileConfig>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[allow(dead_code)]
pub(crate) enum TokenPersistence {
    SecretService,
    PlaintextFallback,
}

// The path to the config file, e.g. ~/.config/tg/config.toml
pub(crate) fn config_path() -> PathBuf {
    let home = std::env::var("HOME").unwrap_or_else(|_| ".".to_string());
    PathBuf::from(home)
        .join(".config")
        .join("tg")
        .join("config.toml")
}

impl ConfigFile {
    pub(crate) fn load() -> Self {
        Self::load_from_path(&config_path())
    }

    pub(crate) fn save(&self) {
        let path = config_path();
        if let Some(parent) = path.parent() {
            fs::create_dir_all(parent).expect("failed to create config directory");
        }
        let contents = toml::to_string(self).expect("failed to serialize config");
        fs::write(&path, contents).expect("failed to write config");
    }

    pub(crate) fn get_profile(&self, profile: Option<&str>) -> ProfileConfig {
        match profile {
            None => ProfileConfig {
                token: self.token.clone(),
                chat_id: self.chat_id,
            },
            Some(name) => self.profiles.get(name).cloned().unwrap_or_default(),
        }
    }

    pub(crate) fn set_profile(&mut self, profile: Option<&str>, data: ProfileConfig) {
        match profile {
            None => {
                self.token = data.token;
                self.chat_id = data.chat_id;
            }
            Some(name) => {
                self.profiles.insert(name.to_string(), data);
            }
        }
    }

    pub(crate) fn delete_profile(&mut self, profile: Option<&str>) {
        match profile {
            None => {
                self.token = None;
                self.chat_id = None;
            }
            Some(name) => {
                self.profiles.remove(name);
            }
        }
    }

    pub(crate) fn is_empty(&self) -> bool {
        self.token.is_none() && self.chat_id.is_none() && self.profiles.is_empty()
    }

    fn load_from_path(path: &std::path::Path) -> Self {
        if path.exists() {
            let contents = fs::read_to_string(path).unwrap_or_default();
            toml::from_str(&contents).unwrap_or_default()
        } else {
            ConfigFile::default()
        }
    }
}

impl ProfileConfig {
    pub(crate) async fn resolved_token_for(&self, profile: Option<&str>) -> Option<String> {
        let path = config_path();
        let profile_owned = profile.map(|s| s.to_string());
        self.resolved_token_with(
            || secret_store::load_token_for(profile_owned),
            |message| eprintln!("{message}"),
            &path,
        )
        .await
    }

    pub(crate) async fn persist_token_for(
        &mut self,
        token: &str,
        profile: Option<&str>,
    ) -> TokenPersistence {
        let path = config_path();
        let profile_owned = profile.map(|s| s.to_string());
        self.persist_token_with(
            token,
            |t| secret_store::save_token_for(profile_owned, t),
            |message| eprintln!("{message}"),
            &path,
        )
        .await
    }

    async fn resolved_token_with<F, Fut, W>(
        &self,
        load_secret: F,
        mut warn: W,
        config_path: &std::path::Path,
    ) -> Option<String>
    where
        F: FnOnce() -> Fut,
        Fut: std::future::Future<Output = Result<Option<String>, secret_store::SecretStoreError>>,
        W: FnMut(String),
    {
        match load_secret().await {
            Ok(Some(token)) => Some(token),
            Ok(None) => self.token.clone(),
            Err(err) if secret_store::is_unavailable(&err) => {
                warn(format!(
                    "Warning: Secret Service API unavailable; falling back to plaintext token in {}",
                    config_path.display()
                ));
                self.token.clone()
            }
            Err(err) => {
                warn(format!(
                    "Warning: failed to read token from Secret Service ({err}); falling back to plaintext token in {}",
                    config_path.display()
                ));
                self.token.clone()
            }
        }
    }

    async fn persist_token_with<F, Fut, W>(
        &mut self,
        token: &str,
        save_secret: F,
        mut warn: W,
        config_path: &std::path::Path,
    ) -> TokenPersistence
    where
        F: FnOnce(String) -> Fut,
        Fut: std::future::Future<Output = Result<(), secret_store::SecretStoreError>>,
        W: FnMut(String),
    {
        match save_secret(token.to_string()).await {
            Ok(()) => {
                self.token = None;
                TokenPersistence::SecretService
            }
            Err(err) if secret_store::is_unavailable(&err) => {
                warn(format!(
                    "Warning: Secret Service API unavailable; falling back to plaintext token in {}",
                    config_path.display()
                ));
                self.token = Some(token.to_string());
                TokenPersistence::PlaintextFallback
            }
            Err(err) => {
                warn(format!(
                    "Warning: failed to store token in Secret Service ({err}); falling back to plaintext token in {}",
                    config_path.display()
                ));
                self.token = Some(token.to_string());
                TokenPersistence::PlaintextFallback
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use std::{
        path::{Path, PathBuf},
        time::{SystemTime, UNIX_EPOCH},
    };

    use crate::secret_store::SecretStoreError;

    use super::{ConfigFile, ProfileConfig, TokenPersistence};

    #[test]
    fn load_from_path_returns_default_when_missing() {
        let missing = unique_tmp_path("missing-config");
        let config = ConfigFile::load_from_path(&missing);
        assert!(config.token.is_none());
        assert!(config.chat_id.is_none());
        assert!(config.profiles.is_empty());
    }

    #[test]
    fn load_from_path_parses_toml_when_present() {
        let path = unique_tmp_path("present-config");
        std::fs::write(&path, "token = \"plaintext-token\"\nchat_id = 123456\n")
            .expect("failed to write temporary config");

        let config = ConfigFile::load_from_path(&path);
        assert_eq!(config.token.as_deref(), Some("plaintext-token"));
        assert_eq!(config.chat_id, Some(123456));

        let _ = std::fs::remove_file(path);
    }

    #[test]
    fn load_from_path_parses_named_profiles() {
        let path = unique_tmp_path("profiles-config");
        std::fs::write(
            &path,
            "chat_id = 111\n\n[profiles.work]\nchat_id = 222\n",
        )
        .expect("failed to write temporary config");

        let config = ConfigFile::load_from_path(&path);
        assert_eq!(config.chat_id, Some(111));
        assert_eq!(config.profiles["work"].chat_id, Some(222));

        let _ = std::fs::remove_file(path);
    }

    #[tokio::test]
    async fn resolved_token_prefers_secret_service_value() {
        let profile = ProfileConfig {
            token: Some("plaintext-token".to_string()),
            chat_id: None,
        };

        let mut warnings = Vec::<String>::new();
        let token = profile
            .resolved_token_with(
                || async { Ok(Some("secret-service-token".to_string())) },
                |warning| warnings.push(warning),
                Path::new("/home/test/.config/tg/config.toml"),
            )
            .await;

        assert_eq!(token.as_deref(), Some("secret-service-token"));
        assert!(warnings.is_empty());
    }

    #[tokio::test]
    async fn resolved_token_falls_back_to_plaintext_when_secret_missing() {
        let profile = ProfileConfig {
            token: Some("plaintext-token".to_string()),
            chat_id: None,
        };

        let mut warnings = Vec::<String>::new();
        let token = profile
            .resolved_token_with(
                || async { Ok(None) },
                |warning| warnings.push(warning),
                Path::new("/home/test/.config/tg/config.toml"),
            )
            .await;

        assert_eq!(token.as_deref(), Some("plaintext-token"));
        assert!(warnings.is_empty());
    }

    #[tokio::test]
    async fn resolved_token_warns_and_falls_back_when_secret_service_unavailable() {
        let profile = ProfileConfig {
            token: Some("plaintext-token".to_string()),
            chat_id: None,
        };

        let mut warnings = Vec::<String>::new();
        let token = profile
            .resolved_token_with(
                || async {
                    Err(SecretStoreError::Unavailable(
                        "dbus unavailable".to_string(),
                    ))
                },
                |warning| warnings.push(warning),
                Path::new("/home/test/.config/tg/config.toml"),
            )
            .await;

        assert_eq!(token.as_deref(), Some("plaintext-token"));
        assert_eq!(warnings.len(), 1);
        assert!(
            warnings[0].contains("Secret Service API unavailable")
                && warnings[0].contains("/home/test/.config/tg/config.toml")
        );
    }

    #[tokio::test]
    async fn resolved_token_warns_and_falls_back_on_other_secret_errors() {
        let profile = ProfileConfig {
            token: Some("plaintext-token".to_string()),
            chat_id: None,
        };

        let mut warnings = Vec::<String>::new();
        let token = profile
            .resolved_token_with(
                || async { Err(SecretStoreError::Backend(keyring::Error::NoEntry)) },
                |warning| warnings.push(warning),
                Path::new("/home/test/.config/tg/config.toml"),
            )
            .await;

        assert_eq!(token.as_deref(), Some("plaintext-token"));
        assert_eq!(warnings.len(), 1);
        assert!(
            warnings[0].contains("failed to read token from Secret Service")
                && warnings[0].contains("/home/test/.config/tg/config.toml")
        );
    }

    #[tokio::test]
    async fn persist_token_uses_secret_service_when_available() {
        let mut profile = ProfileConfig::default();
        let mut warnings = Vec::<String>::new();

        let persistence = profile
            .persist_token_with(
                "secret-service-token",
                |_| async { Ok(()) },
                |warning| warnings.push(warning),
                Path::new("/home/test/.config/tg/config.toml"),
            )
            .await;

        assert_eq!(persistence, TokenPersistence::SecretService);
        assert!(profile.token.is_none());
        assert!(warnings.is_empty());
    }

    #[tokio::test]
    async fn persist_token_warns_and_falls_back_when_secret_service_unavailable() {
        let mut profile = ProfileConfig::default();
        let mut warnings = Vec::<String>::new();

        let persistence = profile
            .persist_token_with(
                "plaintext-token",
                |_| async {
                    Err(SecretStoreError::Unavailable(
                        "dbus unavailable".to_string(),
                    ))
                },
                |warning| warnings.push(warning),
                Path::new("/home/test/.config/tg/config.toml"),
            )
            .await;

        assert_eq!(persistence, TokenPersistence::PlaintextFallback);
        assert_eq!(profile.token.as_deref(), Some("plaintext-token"));
        assert_eq!(warnings.len(), 1);
        assert!(
            warnings[0].contains("Secret Service API unavailable")
                && warnings[0].contains("/home/test/.config/tg/config.toml")
        );
    }

    #[tokio::test]
    async fn persist_token_warns_and_falls_back_on_other_secret_errors() {
        let mut profile = ProfileConfig::default();
        let mut warnings = Vec::<String>::new();

        let persistence = profile
            .persist_token_with(
                "plaintext-token",
                |_| async { Err(SecretStoreError::Backend(keyring::Error::NoEntry)) },
                |warning| warnings.push(warning),
                Path::new("/home/test/.config/tg/config.toml"),
            )
            .await;

        assert_eq!(persistence, TokenPersistence::PlaintextFallback);
        assert_eq!(profile.token.as_deref(), Some("plaintext-token"));
        assert_eq!(warnings.len(), 1);
        assert!(
            warnings[0].contains("failed to store token in Secret Service")
                && warnings[0].contains("/home/test/.config/tg/config.toml")
        );
    }

    fn unique_tmp_path(prefix: &str) -> PathBuf {
        let nanos = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .expect("clock before UNIX_EPOCH")
            .as_nanos();
        std::env::temp_dir().join(format!("tg-cli-{prefix}-{nanos}.toml"))
    }
}