cfait 1.1.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
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
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
// 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>,
    pub undo_history: Arc<Mutex<crate::journal::UndoHistory>>,
}

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

    /// 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();

        enum LocalOp {
            Upsert(Box<Task>),
            Delete(String),
        }

        let mut local_ops_by_href: std::collections::HashMap<String, Vec<LocalOp>> =
            std::collections::HashMap::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());
            }

            match action {
                Action::Create(t) => {
                    if t.calendar_href.starts_with("local://") {
                        local_ops_by_href
                            .entry(t.calendar_href.clone())
                            .or_default()
                            .push(LocalOp::Upsert(Box::new(t)));
                    } else {
                        remote_actions.push(Action::Create(t));
                    }
                }
                Action::Update(t) => {
                    if t.calendar_href.starts_with("local://") {
                        local_ops_by_href
                            .entry(t.calendar_href.clone())
                            .or_default()
                            .push(LocalOp::Upsert(Box::new(t)));
                    } else {
                        remote_actions.push(Action::Update(t));
                    }
                }
                Action::Delete(t) => {
                    if t.calendar_href.starts_with("local://") {
                        local_ops_by_href
                            .entry(t.calendar_href.clone())
                            .or_default()
                            .push(LocalOp::Delete(t.uid.clone()));
                    } else {
                        remote_actions.push(Action::Delete(t));
                    }
                }
                Action::Move(t, target_href) => {
                    if t.calendar_href.starts_with("local://") {
                        local_ops_by_href
                            .entry(t.calendar_href.clone())
                            .or_default()
                            .push(LocalOp::Delete(t.uid.clone()));
                    } else {
                        remote_actions.push(Action::Move(t.clone(), target_href.clone()));
                    }

                    if target_href.starts_with("local://") {
                        let mut moved = t.clone();
                        moved.calendar_href = target_href.clone();
                        local_ops_by_href
                            .entry(target_href)
                            .or_default()
                            .push(LocalOp::Upsert(Box::new(moved)));
                    }
                }
            }
        }

        for (href, ops) in local_ops_by_href {
            let _ = LocalStorage::modify_for_href(self.ctx.as_ref(), &href, |all| {
                for op in ops {
                    match op {
                        LocalOp::Upsert(task) => {
                            if let Some(idx) = all.iter().position(|item| item.uid == task.uid) {
                                all[idx] = *task;
                            } else {
                                all.push(*task);
                            }
                        }
                        LocalOp::Delete(uid) => {
                            all.retain(|item| item.uid != uid);
                        }
                    }
                }
            });
        }

        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";

        // Load from disk cache first to get the freshest settings task
        // The background worker uses an isolated TaskStore which might be stale.
        let mut existing_task_from_disk = None;
        if let Ok(cals) = crate::cache::Cache::load_calendars(self.ctx.as_ref()) {
            for cal in cals {
                if let Ok((tasks, _)) = crate::cache::Cache::load(self.ctx.as_ref(), &cal.href)
                    && let Some(t) = tasks.into_iter().find(|t| t.uid == settings_uid)
                {
                    existing_task_from_disk = Some(t);
                    break;
                }
            }
        }

        // Now acquire the store lock to check in-memory state
        let mut store = self.store.lock().await;
        let mut existing_task = store.get_task_ref(settings_uid).cloned();

        // Prefer the disk version if it's newer
        if let Some(ref disk_task) = existing_task_from_disk
            && (existing_task.is_none()
                || existing_task.as_ref().unwrap().sequence < disk_task.sequence)
        {
            existing_task = existing_task_from_disk;
        }

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

        match existing_task {
            Some(mut task) => {
                let parsed_payload =
                    serde_json::from_str::<crate::config::SettingsPayload>(&task.description);
                if parsed_payload.is_err() {
                    log::warn!(
                        "Settings sync failed: Invalid JSON in settings task. Overwriting with local. Error: {:?}. Raw description: {}",
                        parsed_payload.as_ref().err(),
                        task.description
                    );
                }

                if let Ok(remote_payload) = parsed_payload {
                    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());

                        // Drop the store lock before applying aliases (which may need to load from disk)
                        drop(store);

                        // Re-acquire the lock for alias application and task updates
                        let mut store = self.store.lock().await;
                        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 {
                            // Ensure the isolated store caches the latest task
                            store.update_or_add_task(task.clone());
                            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;
                        return Ok(true);
                    }
                } 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;
                    return Ok(true);
                }
            }
            None => {
                // Drop the store lock before loading from disk
                drop(store);

                // 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;

                // Re-acquire the lock to add the task to the store
                let mut store = self.store.lock().await;
                store.add_task(new_task.clone());
                drop(store);
                let _ = self.persist_changes(vec![Action::Create(new_task)]).await;
                return Ok(true);
            }
        }
        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> {
        // 1. 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 mut config_changed = self.sync_settings().await.unwrap_or(false);

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

        let (warns, actual_synced) = if let Some(ref 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());
                        } else {
                            // Catch-all: Ensure entirely new tasks fetched from server (like settings) enter the store
                            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;
                    }

                    // Update Cache to reflect successful uploads, preventing 3-way merge failures
                    // if the user edits the task again before a full sync.
                    let mut by_calendar: std::collections::HashMap<String, Vec<Task>> =
                        std::collections::HashMap::new();
                    for t in &actual {
                        if !t.calendar_href.starts_with("local://") {
                            by_calendar
                                .entry(t.calendar_href.clone())
                                .or_default()
                                .push(t.clone());
                        }
                    }

                    for (href, tasks) in by_calendar {
                        if let Ok((mut cached, token)) =
                            crate::cache::Cache::load(self.ctx.as_ref(), &href)
                        {
                            let mut changed = false;
                            for t in tasks {
                                if let Some(idx) = cached.iter().position(|x| x.uid == t.uid) {
                                    cached[idx] = t;
                                    changed = true;
                                } else {
                                    cached.push(t);
                                    changed = true;
                                }
                            }
                            if changed {
                                let _ = crate::cache::Cache::save(
                                    self.ctx.as_ref(),
                                    &href,
                                    &cached,
                                    token,
                                );
                            }
                        }
                    }

                    (w, actual)
                }
                Err(e) => return Err(e),
            }
        } else {
            (
                vec![rust_i18n::t!("offline_changes_queued").to_string()],
                vec![],
            )
        };

        // 2. Run settings synchronization AGAIN so we instantly pick up any remote changes
        // downloaded during the sync_journal pass.
        let q_len_before = Journal::load(self.ctx.as_ref()).queue.len();

        if self.sync_settings().await.unwrap_or(false) {
            config_changed = true;
        }

        let q_len_after = Journal::load(self.ctx.as_ref()).queue.len();
        if q_len_after > q_len_before {
            // sync_settings pushed a new action (likely Action::Update for the settings task).
            // We must flush the journal again immediately so it doesn't get stuck!
            if let Some(client) = client_opt
                && let Ok((_w, s)) = client.sync_journal().await
            {
                let mut st = self.store.lock().await;
                for sync_task in &s {
                    if let Some((existing, _)) = st.get_task_mut(&sync_task.uid) {
                        existing.etag = sync_task.etag.clone();
                        existing.href = sync_task.href.clone();
                    }
                }
            }
        }

        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;
        }

        // Persist to disk FIRST to guarantee data integrity. If this fails,
        // we return an error and the UI will NOT clear the text input.
        self.persist_changes(vec![Action::Create(task.clone())])
            .await?;

        self.store.lock().await.add_task(task.clone());
        Ok(task.uid)
    }

    pub async fn update_task(&self, mut task: Task) -> Result<Vec<String>, String> {
        task.sequence += 1;

        // Persist to disk FIRST to guarantee data integrity.
        self.persist_changes(vec![Action::Update(task.clone())])
            .await?;

        let mut store = self.store.lock().await;
        store.update_or_add_task(task);
        drop(store);
        Ok(vec![])
    }

    pub async fn empty_trash(&self) -> Result<usize, String> {
        let mut store = self.store.lock().await;
        let mut tasks_to_purge = Vec::new();

        if let Some(trash_map) = store.calendars.get(crate::storage::LOCAL_TRASH_HREF) {
            for task in trash_map.values() {
                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)
    }

    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)
    }
}