cfait 1.0.8

Powerful, fast and elegant task / TODO manager. (GUI & TUI, CalDAV & local)
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
// SPDX-License-Identifier: GPL-3.0-or-later
//! Central logic controller for Task operations.
//! This is the single source of truth for background persistence orchestration.
use crate::client::RustyClient;
use crate::config::Config;
use crate::context::AppContext;
use crate::journal::{Action, Journal};
use crate::model::Task;
use crate::storage::{LocalCalendarRegistry, LocalStorage};
use crate::store::TaskStore;
use chrono::{DateTime, Utc};
use serde_json;
use std::sync::Arc;
use tokio::sync::Mutex;

/// Central logic controller for Task operations.
/// Handles business workflows and coordinates in-memory store mutations,
/// network client interactions and the journaling fallback used for offline-safe writes.
#[derive(Clone)]
pub struct TaskController {
    pub store: Arc<Mutex<TaskStore>>,
    pub client: Arc<Mutex<Option<RustyClient>>>,
    pub ctx: Arc<dyn AppContext>,
}

impl TaskController {
    pub fn new(
        store: Arc<Mutex<TaskStore>>,
        client: Arc<Mutex<Option<RustyClient>>>,
        ctx: Arc<dyn AppContext>,
    ) -> Self {
        Self { store, client, ctx }
    }

    /// Process a batch of actions atomically to ensure proper journal queueing.
    /// This is an instantaneous operation that saves to disk and returns without hitting the network.
    pub async fn persist_changes(&self, actions: Vec<Action>) -> Result<(), String> {
        let mut remote_actions = Vec::new();

        for action in actions {
            // Prevent Data-Loss: Ensure Trash calendar is registered on disk during a trash-create event
            if let Action::Create(ref t) | Action::Update(ref t) = action
                && t.calendar_href == crate::storage::LOCAL_TRASH_HREF
            {
                let _ = LocalCalendarRegistry::ensure_trash_calendar_exists(self.ctx.as_ref());
            }

            let is_local = match &action {
                Action::Create(t) | Action::Update(t) | Action::Delete(t) => {
                    t.calendar_href.starts_with("local://")
                }
                Action::Move(t, _) => t.calendar_href.starts_with("local://"),
            };

            if is_local {
                match &action {
                    Action::Create(t) | Action::Update(t) => {
                        let task_clone = t.clone();
                        let _ = LocalStorage::modify_for_href(
                            self.ctx.as_ref(),
                            &t.calendar_href,
                            |all| {
                                if let Some(idx) =
                                    all.iter().position(|item| item.uid == task_clone.uid)
                                {
                                    all[idx] = task_clone;
                                } else {
                                    all.push(task_clone);
                                }
                            },
                        );
                    }
                    Action::Delete(t) => {
                        let _ = LocalStorage::modify_for_href(
                            self.ctx.as_ref(),
                            &t.calendar_href,
                            |all| {
                                all.retain(|item| item.uid != t.uid);
                            },
                        );
                    }
                    Action::Move(t, target_href) => {
                        let _ = LocalStorage::modify_for_href(
                            self.ctx.as_ref(),
                            &t.calendar_href,
                            |all| {
                                all.retain(|item| item.uid != t.uid);
                            },
                        );
                        if target_href.starts_with("local://") {
                            let mut moved = t.clone();
                            moved.calendar_href = target_href.clone();
                            let _ = LocalStorage::modify_for_href(
                                self.ctx.as_ref(),
                                target_href,
                                |all| {
                                    all.push(moved);
                                },
                            );
                        }
                    }
                }
            } else {
                remote_actions.push(action);
            }
        }

        if remote_actions.is_empty() {
            return Ok(());
        }

        {
            let mut store = self.store.lock().await;
            for action in &remote_actions {
                let uid = match action {
                    Action::Create(t) | Action::Update(t) | Action::Delete(t) => &t.uid,
                    Action::Move(t, _) => &t.uid,
                };
                if let Some((existing, _)) = store.get_task_mut(uid)
                    && existing.etag.is_empty()
                {
                    existing.etag = "pending_refresh".to_string();
                }
            }
        }

        Journal::modify(self.ctx.as_ref(), |queue| {
            queue.extend(remote_actions);
            let mut tmp_j = Journal {
                queue: std::mem::take(queue),
            };
            tmp_j.compact();
            *queue = tmp_j.queue;
        })
        .map_err(|e| e.to_string())?;

        Ok(())
    }

    /// Synchronizes the configuration and aliases via a hidden CalDAV VTODO.
    pub async fn sync_settings(&self) -> Result<bool, String> {
        let mut config = Config::load(self.ctx.as_ref()).unwrap_or_default();
        if !config.sync_settings {
            return Ok(false);
        }

        let settings_uid = "cfait-global-settings-v1";
        let mut store = self.store.lock().await;
        let existing_task = store.get_task_ref(settings_uid).cloned();

        let local_syncable = config.get_syncable();
        let config_changed = false;

        match existing_task {
            Some(mut task) => {
                if let Ok(remote_payload) =
                    serde_json::from_str::<crate::config::SettingsPayload>(&task.description)
                {
                    if remote_payload.updated_at > config.settings_updated_at
                        || (config.settings_updated_at == 0
                            && remote_payload.config != local_syncable)
                    {
                        // Remote is newer! Sync down.
                        config.apply_syncable(remote_payload.config.clone());

                        let mut needs_upstream_fix = false;
                        if remote_payload.updated_at == 0 {
                            config.settings_updated_at = chrono::Utc::now().timestamp();
                            needs_upstream_fix = true;
                        } else {
                            config.settings_updated_at = remote_payload.updated_at;
                        }
                        let _ = config.save(self.ctx.as_ref());

                        let mut modified_tasks = Vec::new();
                        for (key, values) in &remote_payload.config.tag_aliases {
                            modified_tasks.extend(store.apply_alias_retroactively(key, values));
                        }

                        if needs_upstream_fix {
                            let fixed_payload = crate::config::SettingsPayload {
                                updated_at: config.settings_updated_at,
                                config: remote_payload.config,
                            };
                            task.description =
                                serde_json::to_string_pretty(&fixed_payload).unwrap_or_default();
                            task.sequence += 1;
                            store.update_or_add_task(task.clone());
                            drop(store);

                            let mut actions = modified_tasks
                                .into_iter()
                                .map(Action::Update)
                                .collect::<Vec<_>>();
                            actions.push(Action::Update(task));
                            let _ = self.persist_changes(actions).await;
                        } else {
                            drop(store);
                            if !modified_tasks.is_empty() {
                                let actions =
                                    modified_tasks.into_iter().map(Action::Update).collect();
                                let _ = self.persist_changes(actions).await;
                            }
                        }

                        return Ok(true);
                    } else if config.settings_updated_at > remote_payload.updated_at
                        || (config.settings_updated_at > 0
                            && remote_payload.config != local_syncable)
                    {
                        // Local is newer! Sync up.
                        let local_payload = crate::config::SettingsPayload {
                            updated_at: config.settings_updated_at,
                            config: local_syncable,
                        };
                        task.description =
                            serde_json::to_string_pretty(&local_payload).unwrap_or_default();
                        task.sequence += 1;
                        store.update_or_add_task(task.clone());
                        drop(store);
                        let _ = self.persist_changes(vec![Action::Update(task)]).await;
                    }
                } else {
                    // Invalid JSON in task, overwrite with local
                    if config.settings_updated_at == 0 {
                        config.settings_updated_at = chrono::Utc::now().timestamp();
                        let _ = config.save(self.ctx.as_ref());
                    }
                    let local_payload = crate::config::SettingsPayload {
                        updated_at: config.settings_updated_at,
                        config: local_syncable,
                    };
                    task.description =
                        serde_json::to_string_pretty(&local_payload).unwrap_or_default();
                    task.sequence += 1;
                    store.update_or_add_task(task.clone());
                    drop(store);
                    let _ = self.persist_changes(vec![Action::Update(task)]).await;
                }
            }
            None => {
                // Task doesn't exist, deploy local settings upstream
                if config.settings_updated_at == 0 {
                    config.settings_updated_at = chrono::Utc::now().timestamp();
                    let _ = config.save(self.ctx.as_ref());
                }

                let target_href = if let Some(def) = &config.default_calendar {
                    if !def.starts_with("local://") {
                        def.clone()
                    } else {
                        let cals = crate::cache::Cache::load_calendars(self.ctx.as_ref())
                            .unwrap_or_default();
                        cals.into_iter()
                            .find(|c| !c.href.starts_with("local://"))
                            .map(|c| c.href)
                            .unwrap_or_else(|| crate::storage::LOCAL_CALENDAR_HREF.to_string())
                    }
                } else {
                    let cals =
                        crate::cache::Cache::load_calendars(self.ctx.as_ref()).unwrap_or_default();
                    cals.into_iter()
                        .find(|c| !c.href.starts_with("local://"))
                        .map(|c| c.href)
                        .unwrap_or_else(|| crate::storage::LOCAL_CALENDAR_HREF.to_string())
                };

                let local_payload = crate::config::SettingsPayload {
                    updated_at: config.settings_updated_at,
                    config: local_syncable,
                };
                let local_json = serde_json::to_string_pretty(&local_payload).unwrap_or_default();

                let mut new_task = Task::new(
                    "âš™ Cfait Settings (Do not delete)",
                    &std::collections::HashMap::new(),
                    None,
                );
                new_task.uid = settings_uid.to_string();
                new_task.status = crate::model::TaskStatus::Cancelled; // Hides it in standard clients
                new_task.description = local_json;
                new_task.categories.push("cfait-internal".to_string());
                new_task.calendar_href = target_href;

                store.add_task(new_task.clone());
                drop(store);
                let _ = self.persist_changes(vec![Action::Create(new_task)]).await;
            }
        }
        Ok(config_changed)
    }

    /// Synchronize the journal with the remote server and update the in-memory store
    /// with the resulting ETags and URLs.
    pub async fn sync_and_update_store(&self) -> Result<(Vec<String>, Vec<Task>, bool), String> {
        // Inject the settings synchronization cycle FIRST, so if it creates a settings task,
        // it gets pushed to the journal before we upload the journal to the server!
        let config_changed = self.sync_settings().await.unwrap_or(false);

        let client_opt = self.client.lock().await.clone();

        let (warns, actual_synced) = if let Some(client) = client_opt {
            match client.sync_journal().await {
                Ok((w, s)) => {
                    let mut st = self.store.lock().await;
                    let mut actual = Vec::new();
                    let mut to_delete = Vec::new();

                    for sync_task in &s {
                        if sync_task.summary.starts_with("âš™ Cfait Settings")
                            && sync_task.summary.ends_with("(Conflict Copy)")
                        {
                            to_delete.push(sync_task.clone());
                            continue; // Prevent it from entering the store
                        }

                        if let Some((existing, _)) = st.get_task_mut(&sync_task.uid) {
                            existing.etag = sync_task.etag.clone();
                            existing.href = sync_task.href.clone();
                            actual.push(sync_task.clone());
                        } else if sync_task.summary.ends_with("(Conflict Copy)") {
                            // Safe to resurrect because it is a new server-generated conflict resolution
                            st.add_task(sync_task.clone());
                            actual.push(sync_task.clone());
                        }
                    }
                    drop(st);

                    if !to_delete.is_empty() {
                        let actions = to_delete.into_iter().map(Action::Delete).collect();
                        let _ = self.persist_changes(actions).await;
                    }

                    (w, actual)
                }
                Err(e) => return Err(e),
            }
        } else {
            (vec!["Offline: Changes queued.".to_string()], vec![])
        };

        Ok((warns, actual_synced, config_changed))
    }

    pub async fn create_task(&self, mut task: Task) -> Result<String, String> {
        if task.calendar_href == crate::storage::LOCAL_TRASH_HREF
            || task.calendar_href == "local://recovery"
        {
            task.calendar_href = crate::storage::LOCAL_CALENDAR_HREF.to_string();
        }
        if !task.calendar_href.starts_with("local://") {
            let cal_path = task.calendar_href.clone();
            let filename = format!("{}.ics", task.uid);
            let full_href = if cal_path.ends_with('/') {
                format!("{}{}", cal_path, filename)
            } else {
                format!("{}/{}", cal_path, filename)
            };
            task.href = full_href;
        }
        self.store.lock().await.add_task(task.clone());
        let _ = self
            .persist_changes(vec![Action::Create(task.clone())])
            .await;
        Ok(task.uid)
    }

    pub async fn update_task(&self, mut task: Task) -> Result<Vec<String>, String> {
        task.sequence += 1;
        let mut store = self.store.lock().await;
        store.update_or_add_task(task.clone());
        drop(store);
        let _ = self.persist_changes(vec![Action::Update(task)]).await;
        Ok(vec![])
    }

    pub async fn prune_trash(&self) -> Result<usize, String> {
        let config = Config::load(self.ctx.as_ref()).unwrap_or_default();
        let retention_days = config.trash_retention_days as i64;
        if retention_days == 0 {
            return Ok(0);
        }

        let now = Utc::now();
        let mut tasks_to_purge = Vec::new();

        let mut store = self.store.lock().await;

        if let Some(trash_map) = store.calendars.get(crate::storage::LOCAL_TRASH_HREF) {
            for task in trash_map.values() {
                if let Some(prop) = task
                    .unmapped_properties
                    .iter()
                    .find(|p| p.key == "X-TRASHED-DATE")
                    && let Ok(dt) = DateTime::parse_from_rfc3339(&prop.value)
                {
                    let age_days = (now - dt.with_timezone(&Utc)).num_days();
                    if age_days >= retention_days {
                        tasks_to_purge.push(task.uid.clone());
                    }
                }
            }
        }

        let mut purged_tasks = Vec::new();
        for uid in tasks_to_purge {
            if let Some((task, _)) = store.delete_task(&uid) {
                purged_tasks.push(task);
            }
        }
        drop(store);

        let count = purged_tasks.len();
        let actions = purged_tasks.into_iter().map(Action::Delete).collect();
        let _ = self.persist_changes(actions).await;
        Ok(count)
    }
}