gtasks_core 0.1.2

Core logic for Google Tasks TUI
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
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use std::sync::Arc;
use tokio::sync::RwLock;

#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct TaskList {
    pub id: String,
    pub title: String,
    pub updated: Option<String>,
}

// Wrapper for the Google Tasks API client response
#[derive(Debug, Serialize, Deserialize)]
pub struct TaskListsResponse {
    pub items: Option<Vec<TaskList>>,
    #[serde(rename = "nextPageToken")]
    pub next_page_token: Option<String>,
}

#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct TaskGet {
    pub id: String,
    pub title: Option<String>,
    pub status: Option<String>,    // Task done or not
    pub notes: Option<String>,     // description of the task
    pub due: Option<String>,       // Deadline
    pub completed: Option<String>, // Completion date of the task
    pub parent: Option<String>,    // Parent task ID (in case of subtask)
    pub updated: Option<String>,   // Last modification date
    pub deleted: Option<bool>,     // Remote deletion status
}

#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct TaskLocal {
    pub id: String,
    pub list_id: String,
    pub title: Option<String>,
    pub is_completed: bool,                               // Task done or not
    pub notes: Option<String>,                            // description of the task
    pub due: Option<chrono::DateTime<chrono::Utc>>,       // Deadline
    pub completed: Option<chrono::DateTime<chrono::Utc>>, // Completion date of the task
    pub parent: Option<String>,                           // Parent task ID (in case of subtask)
    pub updated: Option<chrono::DateTime<chrono::Utc>>,   // Last modification date
    pub is_dirty: bool,
    pub is_deleted: bool,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct TasksResponse {
    pub items: Option<Vec<TaskGet>>,
    #[serde(rename = "nextPageToken")]
    pub next_page_token: Option<String>,
}

/// Patch payload builder for updating task fields.
#[derive(Debug, Default, Clone, Serialize, Deserialize)]
pub struct TaskPatch {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub title: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub notes: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub status: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub due: Option<String>,
}

impl TaskPatch {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn title(mut self, title: impl Into<String>) -> Self {
        self.title = Some(title.into());
        self
    }

    pub fn notes(mut self, notes: impl Into<String>) -> Self {
        self.notes = Some(notes.into());
        self
    }

    pub fn completed(mut self, completed: bool) -> Self {
        self.status = Some(if completed {
            "completed".to_string()
        } else {
            "needsAction".to_string()
        });
        self
    }

    pub fn due(mut self, due: &chrono::DateTime<chrono::Utc>) -> Self {
        self.due = Some(due.to_rfc3339());
        self
    }
}

// API
#[derive(Debug, Clone)]
pub struct GoogleTasksClient {
    pub client: reqwest::Client,
    pub access_token: Arc<RwLock<String>>,
}

impl GoogleTasksClient {
    pub fn new(access_token: String) -> Self {
        Self {
            client: reqwest::Client::new(),
            access_token: Arc::new(RwLock::new(access_token)),
        }
    }

    pub async fn get_access_token(&self) -> String {
        self.access_token.read().await.clone()
    }

    // Get the list of task lists for the authenticated user
    pub async fn get_task_lists(&self) -> crate::Result<Vec<TaskList>> {
        let url = "https://www.googleapis.com/tasks/v1/users/@me/lists";
        let mut all_lists = Vec::new();
        let mut page_token: Option<String> = None;

        loop {
            let response = self
                .execute_with_retry(|client, token| {
                    let mut req = client.get(url).bearer_auth(token);
                    if let Some(ref pt) = page_token {
                        req = req.query(&[("pageToken", pt)]);
                    }
                    req
                })
                .await?;
            let response = response.error_for_status()?;
            let task_lists_response: TaskListsResponse = response.json().await?;

            if let Some(items) = task_lists_response.items {
                all_lists.extend(items);
            }

            match task_lists_response.next_page_token {
                Some(token) if !token.is_empty() => page_token = Some(token),
                _ => break,
            }
        }

        Ok(all_lists)
    }

    // Create a new task list
    pub async fn create_task_list(&self, title: &str) -> crate::Result<TaskList> {
        let url = "https://www.googleapis.com/tasks/v1/users/@me/lists";
        let payload = serde_json::json!({ "title": title });
        let response = self
            .execute_with_retry(|client, token| client.post(url).bearer_auth(token).json(&payload))
            .await?;
        let response = response.error_for_status()?;
        let created: TaskList = response.json().await?;
        Ok(created)
    }

    pub async fn delete_task_list(&self, list_id: &str) -> crate::Result<()> {
        let url = format!(
            "https://www.googleapis.com/tasks/v1/users/@me/lists/{}",
            list_id
        );
        let response = self
            .execute_with_retry(|client, token| client.delete(&url).bearer_auth(token))
            .await?;
        if response.status() == reqwest::StatusCode::NOT_FOUND
            || response.status() == reqwest::StatusCode::NO_CONTENT
        {
            return Ok(());
        }
        response.error_for_status()?;
        Ok(())
    }

    // Get the tasks for a specific task list
    pub async fn get_tasks(
        &self,
        list_id: &str,
        show_completed: bool,
        updated_min: Option<&chrono::DateTime<chrono::Utc>>,
    ) -> crate::Result<Vec<TaskGet>> {
        let url = format!(
            "https://www.googleapis.com/tasks/v1/lists/{}/tasks",
            list_id
        );

        let updated_min_str = updated_min.map(|dt| dt.to_rfc3339());
        let mut all_tasks = Vec::new();
        let mut page_token: Option<String> = None;

        loop {
            let response = self
                .execute_with_retry(|client, token| {
                    let mut query = vec![
                        ("showCompleted", show_completed.to_string()),
                        ("showHidden", show_completed.to_string()),
                        ("showDeleted", "true".to_string()),
                    ];
                    if let Some(ref dt_str) = updated_min_str {
                        query.push(("updatedMin", dt_str.clone()));
                    }
                    if let Some(ref pt) = page_token {
                        query.push(("pageToken", pt.clone()));
                    }
                    client.get(&url).bearer_auth(token).query(&query)
                })
                .await?;
            let response = response.error_for_status()?;
            let tasks_response: TasksResponse = response.json().await?;

            if let Some(items) = tasks_response.items {
                all_tasks.extend(items);
            }

            match tasks_response.next_page_token {
                Some(token) if !token.is_empty() => page_token = Some(token),
                _ => break,
            }
        }

        Ok(all_tasks)
    }

    pub async fn create_task(
        &self,
        list_id: &str,
        task: &TaskLocal,
    ) -> crate::Result<TaskGet> {
        let url = format!(
            "https://www.googleapis.com/tasks/v1/lists/{}/tasks",
            list_id
        );
        let body = serde_json::json!({
            "title": task.title,
            "notes": task.notes,
            "due": task.due.map(|d| d.to_rfc3339()),
            "parent": task.parent,
        });

        let response = self
            .execute_with_retry(|client, token| client.post(&url).bearer_auth(token).json(&body))
            .await?;
        let response = response.error_for_status()?;
        let created_task: TaskGet = response.json().await?;
        Ok(created_task)
    }

    pub async fn patch_task(
        &self,
        list_id: &str,
        task_id: &str,
        patch: &TaskPatch,
    ) -> crate::Result<TaskGet> {
        let url = format!(
            "https://www.googleapis.com/tasks/v1/lists/{list_id}/tasks/{task_id}"
        );
        let response = self
            .execute_with_retry(|client, token| client.patch(&url).bearer_auth(token).json(patch))
            .await?;
        let response = response.error_for_status()?;
        let updated_task: TaskGet = response.json().await?;
        Ok(updated_task)
    }

    pub async fn update_task(
        &self,
        list_id: &str,
        task_id: &str,
        title: Option<&str>,
        notes: Option<&str>,
        completed: Option<bool>,
        due: Option<&chrono::DateTime<chrono::Utc>>,
    ) -> crate::Result<TaskGet> {
        let mut patch = TaskPatch::new();
        if let Some(t) = title {
            patch = patch.title(t);
        }
        if let Some(n) = notes {
            patch = patch.notes(n);
        }
        if let Some(c) = completed {
            patch = patch.completed(c);
        }
        if let Some(d) = due {
            patch = patch.due(d);
        }
        self.patch_task(list_id, task_id, &patch).await
    }

    pub async fn toggle_task_completion(
        &self,
        list_id: &str,
        task_id: &str,
        completed: bool,
    ) -> crate::Result<TaskGet> {
        self.update_task(list_id, task_id, None, None, Some(completed), None)
            .await
    }

    async fn execute_with_retry(
        &self,
        build_request: impl Fn(&reqwest::Client, &str) -> reqwest::RequestBuilder,
    ) -> crate::Result<reqwest::Response> {
        let token = self.access_token.read().await.clone();
        let request = build_request(&self.client, &token);
        let response = request.send().await?;

        if response.status() == reqwest::StatusCode::UNAUTHORIZED {
            if let Ok(refresh_token) = crate::auth::keyring::get_refresh_token() {
                if let Ok(token_response) = crate::auth::refresh_access_token(&refresh_token).await
                {
                    let mut token_writer = self.access_token.write().await;
                    *token_writer = token_response.access_token.clone();

                    let retry_token = build_request(&self.client, &token_response.access_token);
                    return Ok(retry_token.send().await?);
                }
            }
        }
        Ok(response)
    }

    pub async fn delete_task(
        &self,
        list_id: &str,
        task_id: &str,
    ) -> crate::Result<()> {
        let url = format!(
            "https://www.googleapis.com/tasks/v1/lists/{list_id}/tasks/{task_id}"
        );

        let response = self
            .execute_with_retry(|client, token| client.delete(&url).bearer_auth(token))
            .await?;
        if response.status() == reqwest::StatusCode::NOT_FOUND {
            return Ok(());
        }
        response.error_for_status()?;
        Ok(())
    }
}

impl TaskLocal {
    pub fn from_task_get(task_get: TaskGet, list_id: String) -> Self {
        let due = task_get.due.as_ref().and_then(|due_str| {
            DateTime::parse_from_rfc3339(due_str)
                .ok()
                .map(|dt| dt.with_timezone(&Utc))
        });

        let completed = task_get.completed.as_ref().and_then(|completed_str| {
            DateTime::parse_from_rfc3339(completed_str)
                .ok()
                .map(|dt| dt.with_timezone(&Utc))
        });

        let updated = task_get.updated.as_ref().and_then(|updated_str| {
            DateTime::parse_from_rfc3339(updated_str)
                .ok()
                .map(|dt| dt.with_timezone(&Utc))
        });
        let is_dirty = false;
        let is_deleted = task_get.deleted.unwrap_or(false);

        TaskLocal {
            id: task_get.id,
            list_id,
            title: task_get.title,
            is_completed: task_get.status.map(|s| s == "completed").unwrap_or(false),
            notes: task_get.notes,
            due,
            completed,
            parent: task_get.parent,
            updated,
            is_dirty,
            is_deleted,
        }
    }

    pub fn is_local_id(&self) -> bool {
        TaskId::new(&self.id).is_local()
    }

    pub fn is_local_list(&self) -> bool {
        TaskListId::new(&self.list_id).is_local()
    }

    pub fn toggle_task_completion(&self) -> TaskLocal {
        let mut updated_task = self.clone();
        updated_task.is_completed = !self.is_completed;
        if updated_task.is_completed {
            updated_task.completed = Some(Utc::now());
        } else {
            updated_task.completed = None;
        }
        updated_task
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum TaskStatus {
    NeedsAction,
    Completed,
}

impl TaskStatus {
    pub fn as_str(&self) -> &'static str {
        match self {
            TaskStatus::NeedsAction => "needsAction",
            TaskStatus::Completed => "completed",
        }
    }
}

impl From<&str> for TaskStatus {
    fn from(s: &str) -> Self {
        match s {
            "completed" => TaskStatus::Completed,
            _ => TaskStatus::NeedsAction,
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(transparent)]
pub struct TaskId(pub String);

impl TaskId {
    pub fn new(id: impl Into<String>) -> Self {
        Self(id.into())
    }

    pub fn is_local(&self) -> bool {
        self.0.is_empty() || self.0.starts_with("local_")
    }

    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl std::fmt::Display for TaskId {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.0)
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(transparent)]
pub struct TaskListId(pub String);

impl TaskListId {
    pub fn new(id: impl Into<String>) -> Self {
        Self(id.into())
    }

    pub fn is_local(&self) -> bool {
        self.0.starts_with("list_")
    }

    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl std::fmt::Display for TaskListId {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.0)
    }
}

#[allow(async_fn_in_trait)]
pub trait TasksApi: Send + Sync {

    async fn get_task_lists(&self) -> crate::Result<Vec<TaskList>>;
    async fn create_task_list(&self, title: &str) -> crate::Result<TaskList>;
    async fn delete_task_list(&self, list_id: &str) -> crate::Result<()>;
    async fn get_tasks(
        &self,
        list_id: &str,
        show_completed: bool,
        updated_min: Option<&chrono::DateTime<chrono::Utc>>,
    ) -> crate::Result<Vec<TaskGet>>;
    async fn create_task(&self, list_id: &str, task: &TaskLocal) -> crate::Result<TaskGet>;
    async fn patch_task(&self, list_id: &str, task_id: &str, patch: &TaskPatch) -> crate::Result<TaskGet>;
    async fn delete_task(&self, list_id: &str, task_id: &str) -> crate::Result<()>;
}

impl TasksApi for GoogleTasksClient {
    async fn get_task_lists(&self) -> crate::Result<Vec<TaskList>> {
        self.get_task_lists().await
    }
    async fn create_task_list(&self, title: &str) -> crate::Result<TaskList> {
        self.create_task_list(title).await
    }
    async fn delete_task_list(&self, list_id: &str) -> crate::Result<()> {
        self.delete_task_list(list_id).await
    }
    async fn get_tasks(
        &self,
        list_id: &str,
        show_completed: bool,
        updated_min: Option<&chrono::DateTime<chrono::Utc>>,
    ) -> crate::Result<Vec<TaskGet>> {
        self.get_tasks(list_id, show_completed, updated_min).await
    }
    async fn create_task(&self, list_id: &str, task: &TaskLocal) -> crate::Result<TaskGet> {
        self.create_task(list_id, task).await
    }
    async fn patch_task(&self, list_id: &str, task_id: &str, patch: &TaskPatch) -> crate::Result<TaskGet> {
        self.patch_task(list_id, task_id, patch).await
    }
    async fn delete_task(&self, list_id: &str, task_id: &str) -> crate::Result<()> {
        self.delete_task(list_id, task_id).await
    }
}