tod 0.12.0

An unofficial Todoist command-line client
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
use crate::{
    config::Config,
    errors::Error,
    tasks::format::{format_osc8_link, hyperlinks_disabled},
    time,
};
use serde::{Deserialize, Serialize};

#[derive(Serialize, Deserialize, Debug, Clone, Eq, PartialEq)]
pub struct Comment {
    pub id: String,
    pub posted_uid: Option<String>,
    pub content: String,
    pub uids_to_notify: Option<Vec<String>>,
    pub is_deleted: bool,
    pub posted_at: String,
    pub reactions: Option<Reactions>,
    pub item_id: String,
    pub file_attachment: Option<Attachment>,
}

#[derive(Serialize, Deserialize, Debug, Clone, Eq, PartialEq)]
pub struct CommentResponse {
    pub results: Vec<Comment>,
    pub next_cursor: Option<String>,
}

#[derive(Serialize, Deserialize, Debug, Clone, Eq, PartialEq)]
pub struct Reactions {}

#[derive(Serialize, Deserialize, Debug, Clone, Eq, PartialEq)]
#[serde(untagged)]
pub enum Attachment {
    File(FileAttachment),
    Url(UrlAttachment),
    ShortUrl(ShortUrlAttachment),
    Video(VideoAttachment),
    Image(ImageAttachment),
}

#[derive(Serialize, Deserialize, Debug, Clone, Eq, PartialEq)]
pub struct FileAttachment {
    pub file_name: String,
    pub file_type: String,
    pub file_url: String,
    pub resource_type: String,
}

#[derive(Serialize, Deserialize, Debug, Clone, Eq, PartialEq)]
pub struct UrlAttachment {
    description: String,
    favicon: String,
    image: String,
    image_height: u32,
    image_width: u32,
    resource_type: String,
    site_name: String,
    title: String,
    url: String,
}

#[derive(Serialize, Deserialize, Debug, Clone, Eq, PartialEq)]
pub struct ShortUrlAttachment {
    resource_type: String,
    title: String,
    url: String,
}

#[derive(Serialize, Deserialize, Debug, Clone, Eq, PartialEq)]
pub struct VideoAttachment {
    html: String,
    resource_type: String,
    title: String,
    url: String,
    site_name: String,
}

#[derive(Serialize, Deserialize, Debug, Clone, Eq, PartialEq)]
pub struct ImageAttachment {
    pub resource_type: String,
    pub url: String,
    pub image: String,
    pub image_height: u32,
    pub image_width: u32,
    pub site_name: Option<String>,
    pub title: Option<String>,
    #[serde(default)]
    pub tn_s: Option<serde_json::Value>,
    #[serde(default)]
    pub tn_m: Option<serde_json::Value>,
    #[serde(default)]
    pub tn_l: Option<serde_json::Value>,
}

impl Comment {
    pub fn fmt(&self, config: &Config) -> Result<String, Error> {
        let timezone = config.get_timezone()?;
        let timezone = time::timezone_from_str(&timezone)?;
        let datetime = time::datetime_from_str(&self.posted_at, timezone)?;
        let formatted_date = time::datetime_to_string(&datetime, config)?;

        let link = match &self.file_attachment {
            None => String::new(),
            Some(Attachment::Url(UrlAttachment {
                url,
                site_name,
                title,
                ..
            })) => Self::render_link(url, &format!("{site_name}: {title}"), config),
            Some(Attachment::ShortUrl(ShortUrlAttachment { url, title, .. })) => {
                Self::render_link(url, title, config)
            }
            Some(Attachment::Video(VideoAttachment {
                url,
                site_name,
                title,
                ..
            })) => Self::render_link(url, &format!("{site_name}: {title}"), config),
            Some(Attachment::File(FileAttachment {
                file_url,
                file_name,
                ..
            })) => Self::render_link(file_url, file_name, config),
            Some(Attachment::Image(ImageAttachment {
                url,
                site_name,
                title,
                ..
            })) => {
                let site = site_name.as_deref().unwrap_or("Image");
                let title = title.as_deref().unwrap_or(url);
                Self::render_link(url, &format!("{site}: {title}"), config)
            }
        };

        Ok(format!(
            "Posted {}{}\n{}",
            formatted_date, link, self.content
        ))
    }

    fn render_link(url: &str, label: &str, config: &Config) -> String {
        if hyperlinks_disabled(config) {
            format!("\nAttachment [{label}]({url})")
        } else {
            format!(
                "\nAttachment {}",
                format_osc8_link(url, &format!("[{label}]"))
            )
        }
    }
}

pub fn json_to_comment_response(json: String) -> Result<CommentResponse, Error> {
    let response: CommentResponse = serde_json::from_str(&json)?;
    Ok(response)
}

pub fn json_to_comment(json: String) -> Result<Comment, Error> {
    let comment: Comment = serde_json::from_str(&json)?;
    Ok(comment)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::comments::json_to_comment_response;
    use crate::test::fixtures;
    use crate::test::responses::ResponseFromFile;
    use pretty_assertions::assert_eq;

    async fn load_comments() -> Vec<Comment> {
        let json = ResponseFromFile::CommentsAllTypes.read().await;
        let response =
            json_to_comment_response(json).expect("Failed to parse JSON to comment response");
        response
            .results
            .into_iter()
            .filter(|c| !c.is_deleted)
            .collect()
    }

    #[tokio::test]
    async fn test_filters_deleted_comment() {
        let comments = load_comments().await;
        assert_eq!(
            comments.len(),
            7,
            "One deleted comment should be filtered out"
        );
    }

    #[tokio::test]
    async fn test_fmt_file_attachment() {
        let config = fixtures::config().await;
        let comment = load_comments()
            .await
            .into_iter()
            .find(|c| c.id == "file-1")
            .expect("Failed to find comment with id 'file-1'");
        let output = comment
            .fmt(&config)
            .expect("Failed to format the comment with the provided config");
        assert!(output.contains("file.pdf"));
    }

    #[tokio::test]
    async fn test_fmt_video_attachment() {
        let config = fixtures::config().await;
        let comment = load_comments()
            .await
            .into_iter()
            .find(|c| c.id == "video-1")
            .expect("Could not find ID video-1");
        let output = comment
            .fmt(&config)
            .expect("Failed to format the comment with the provided config");
        assert!(output.contains("Test Video"));
    }

    #[tokio::test]
    async fn test_fmt_image_attachment() {
        let config = fixtures::config().await;
        let comment = load_comments()
            .await
            .into_iter()
            .find(|c| c.id == "image-1")
            .expect("could not find id image-1");
        let output = comment
            .fmt(&config)
            .expect("Failed to format the comment with the provided config");
        assert!(output.contains("Example Image"));
    }

    #[tokio::test]
    async fn test_fmt_url_attachment() {
        let config = fixtures::config().await;
        let comment = load_comments()
            .await
            .into_iter()
            .find(|c| c.id == "url-1")
            .expect("Could not find ID url-1");
        let output = comment
            .fmt(&config)
            .expect("Failed to format the comment with the provided config");
        assert!(output.contains("Interesting Article"));
    }

    #[tokio::test]
    async fn test_fmt_short_url_attachment() {
        let config = fixtures::config().await;
        let comment = load_comments()
            .await
            .into_iter()
            .find(|c| c.id == "shorturl-1")
            .expect("Could not find ID shorturl-1");
        let output = comment
            .fmt(&config)
            .expect("Failed to format the comment with the provided config");
        assert!(output.contains("Shortened Link"));
    }

    #[tokio::test]
    async fn test_fmt_rich_attachment() {
        let config = fixtures::config().await;
        let comment = load_comments()
            .await
            .into_iter()
            .find(|c| c.id == "rich-1")
            .expect("Could not find ID rich-1");
        let output = comment
            .fmt(&config)
            .expect("Failed to format the comment with the provided config");
        assert!(output.contains("News Story"));
    }

    #[tokio::test]
    async fn test_fmt_no_attachment() {
        let config = fixtures::config().await;
        let comment = load_comments()
            .await
            .into_iter()
            .find(|c| c.id == "noattach-1")
            .expect("Could not find ID noattach-1");
        let output = comment
            .fmt(&config)
            .expect("Failed to format the comment with the provided config");
        assert!(output.contains("Just a plain comment"));
    }

    #[test]
    fn test_json_to_comment_valid() {
        let json = r#"{
            "id": "c1",
            "posted_uid": null,
            "content": "Hello world",
            "uids_to_notify": null,
            "is_deleted": false,
            "posted_at": "2024-01-15T10:00:00Z",
            "reactions": null,
            "item_id": "task1",
            "file_attachment": null
        }"#;
        let comment = json_to_comment(json.to_string()).expect("should parse comment JSON");
        assert_eq!(comment.id, "c1");
        assert_eq!(comment.content, "Hello world");
        assert!(!comment.is_deleted);
    }

    #[test]
    fn test_json_to_comment_invalid() {
        let result = json_to_comment("not json".to_string());
        assert!(result.is_err());
    }

    #[test]
    fn test_json_to_comment_response_valid() {
        let json = r#"{
            "results": [
                {
                    "id": "c1",
                    "posted_uid": null,
                    "content": "Test",
                    "uids_to_notify": null,
                    "is_deleted": false,
                    "posted_at": "2024-01-15T10:00:00Z",
                    "reactions": null,
                    "item_id": "t1",
                    "file_attachment": null
                }
            ],
            "next_cursor": null
        }"#;
        let response =
            json_to_comment_response(json.to_string()).expect("should parse comment response JSON");
        assert_eq!(response.results.len(), 1);
        assert_eq!(response.results[0].content, "Test");
        assert!(response.next_cursor.is_none());
    }

    #[test]
    fn test_json_to_comment_response_invalid() {
        let result = json_to_comment_response("not json".to_string());
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn test_fmt_attachment_links_enabled() {
        // With hyperlinks enabled (disable_links = false, default), the output should contain
        // an OSC8 escape sequence for the attachment link.
        let config = fixtures::config().await;
        // Skip the test if hyperlinks are not supported in this environment
        if !supports_hyperlinks::on(supports_hyperlinks::Stream::Stdout) {
            eprintln!("Skipping test: hyperlinks not supported in this environment");
            return;
        }
        let comment = load_comments()
            .await
            .into_iter()
            .find(|c| c.id == "file-1")
            .expect("Failed to find comment with id 'file-1'");
        let output = comment
            .fmt(&config)
            .expect("Failed to format the comment with the provided config");
        // OSC8 opener sequence must be present when links are enabled
        assert!(
            output.contains("\x1B]8;;"),
            "Expected OSC8 hyperlink sequence in output"
        );
    }

    #[tokio::test]
    async fn test_fmt_attachment_links_disabled() {
        // With hyperlinks disabled, the output should contain a plain Markdown-style link
        // and must not contain any OSC8 escape sequences.
        let mut config = fixtures::config().await;
        config.disable_links = true;
        let comment = load_comments()
            .await
            .into_iter()
            .find(|c| c.id == "file-1")
            .expect("Failed to find comment with id 'file-1'");
        let output = comment
            .fmt(&config)
            .expect("Failed to format the comment with the provided config");
        assert!(
            !output.contains("\x1B]8;;"),
            "Expected no OSC8 hyperlink sequence in output when links are disabled"
        );
        assert!(
            output.contains("file.pdf"),
            "Expected plain-text label in output when links are disabled"
        );
    }

    /// Test with inline JSON to simulate the behavior of excluding comments
    /// This needs to be updated to work with the actual Regex and Mockito setup
    #[tokio::test]
    async fn test_exclude_comments_inline_json() {
        // Simulated inline JSON response with 3 comments
        let json = r#"
        {
            "results": [
                {
                    "id": "c1",
                    "posted_uid": null,
                    "content": "Via Habit Tracker: Wake up at 6am",
                    "uids_to_notify": null,
                    "is_deleted": false,
                    "posted_at": "2024-01-01T08:00:00Z",
                    "reactions": null,
                    "item_id": "t1",
                    "file_attachment": null
                },
                {
                    "id": "c2",
                    "posted_uid": null,
                    "content": "This is a normal comment",
                    "uids_to_notify": null,
                    "is_deleted": false,
                    "posted_at": "2024-01-01T09:00:00Z",
                    "reactions": null,
                    "item_id": "t1",
                    "file_attachment": null
                },
                {
                    "id": "c3",
                    "posted_uid": null,
                    "content": "IGNORE ME PLEASE",
                    "uids_to_notify": null,
                    "is_deleted": false,
                    "posted_at": "2024-01-01T10:00:00Z",
                    "reactions": null,
                    "item_id": "t1",
                    "file_attachment": null
                }
            ],
            "next_cursor": null
        }
        "#;

        let mut comments = json_to_comment_response(json.to_string())
            .expect("Could not convert JSON into comment response")
            .results;

        // Simulate filtering using a regex from config
        let re =
            regex::Regex::new(r"(?i)^via habit tracker|ignore me").expect("Could not create regex");
        comments.retain(|c| !re.is_match(&c.content));

        let remaining_ids: Vec<_> = comments.iter().map(|c| &c.id).collect();

        assert_eq!(
            remaining_ids,
            vec!["c2"],
            "Only the normal comment should remain"
        );
    }
}