aimcal-core 0.12.1

AIM - Analyze. Interact. Manage Your Time, with calendar support
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
// SPDX-FileCopyrightText: 2025-2026 Zexin Yuan <aim@yzx9.xyz>
//
// SPDX-License-Identifier: Apache-2.0

use std::error::Error;
use std::path::{Path, PathBuf};

use aimcal_ical::{CalendarComponent, ICalendar, fmt::format, parse};
use tokio::fs;

use crate::db::Db;

/// Add ICS files from calendar directory to database.
/// This is only called when `calendar_path` is configured in Config.
#[tracing::instrument(skip(db))]
pub async fn add_calendar_if_enabled(
    db: &Db,
    calendar_path: Option<&PathBuf>,
) -> Result<(), Box<dyn Error>> {
    let Some(path) = calendar_path else {
        tracing::info!("calendar_path not configured, skipping ICS import");
        return Ok(());
    };

    if !path.exists() {
        tracing::warn!(
            path = %path.display(),
            "calendar_path does not exist, skipping ICS import"
        );
        return Ok(());
    }

    add_calendar(db, path).await
}

#[tracing::instrument(skip(db))]
async fn add_calendar(db: &Db, calendar_path: &PathBuf) -> Result<(), Box<dyn Error>> {
    let mut reader = fs::read_dir(calendar_path)
        .await
        .map_err(|e| format!("Failed to read directory: {e}"))?;

    let mut handles = vec![];
    while let Some(entry) = reader.next_entry().await? {
        let path = entry.path();
        match path.extension() {
            Some(ext) if ext == "ics" => {
                let db = db.clone();
                handles.push(tokio::spawn(async move {
                    if let Err(err) = add_ics(db, &path).await {
                        tracing::error!(path = %path.display(), err, "failed to process file");
                    }
                }));
            }
            _ => {}
        }
    }

    let count = handles.len();
    for handle in handles {
        handle.await?;
    }

    tracing::debug!(count = count, "total .ics files processed");
    Ok(())
}

// TODO: support multiple calendars in one file
pub async fn parse_ics(path: &Path) -> Result<ICalendar<String>, Box<dyn Error>> {
    let content = fs::read_to_string(path)
        .await
        .map_err(|e| format!("Failed to read file {}: {}", path.display(), e))?;

    let calendars = parse(&content)
        .map_err(|e| -> Box<dyn Error> { format!("Failed to parse calendar: {e:?}").into() })?;

    if calendars.is_empty() {
        return Err("No calendars found in file".into());
    }

    // Hybrid: parse borrowed, convert to owned for storage
    Ok(calendars.into_iter().next().unwrap().to_owned())
}

pub async fn write_ics(path: &Path, calendar: &ICalendar<String>) -> Result<(), String> {
    let ics_content = format(calendar).map_err(|e| format!("Failed to format calendar: {e}"))?;

    fs::write(path, ics_content)
        .await
        .map_err(|e| format!("Failed to write calendar file: {e}"))
}

async fn add_ics(db: Db, path: &Path) -> Result<(), Box<dyn Error>> {
    tracing::debug!(path = %path.display(), "parsing file");
    let calendar = parse_ics(path).await?;

    tracing::debug!(path = %path.display(), components = calendar.components.len(), "found components");
    for component in calendar.components {
        tracing::debug!(?component, "processing component");
        match component {
            CalendarComponent::Event(event) => {
                let uid = event.uid.content.to_string();
                db.upsert_event(&uid, &event, 0).await?;
                let resource_id = format!("file://{}", path.display());
                db.resources.insert(&uid, 0, &resource_id, None).await?;
            }
            CalendarComponent::Todo(todo) => {
                let uid = todo.uid.content.to_string();
                db.upsert_todo(&uid, &todo, 0).await?;
                let resource_id = format!("file://{}", path.display());
                db.resources.insert(&uid, 0, &resource_id, None).await?;
            }
            _ => tracing::warn!(?component, "ignoring unsupported component type"),
        }
    }

    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    #[tokio::test]
    async fn add_calendar_processes_single_ics_file() {
        // Arrange
        let temp_dir = tempfile::tempdir().expect("Failed to create temp dir");
        let calendar_path = temp_dir.path().to_path_buf();

        let ics_content = "BEGIN:VCALENDAR\r
VERSION:2.0\r
PRODID:-//AIM//Test//EN\r
BEGIN:VEVENT\r
UID:test-event-single\r
DTSTAMP:20250115T120000Z\r
DTSTART:20250115T100000Z\r
DTEND:20250115T110000Z\r
SUMMARY:Single Event\r
END:VEVENT\r
END:VCALENDAR\r
";

        let event_file = calendar_path.join("event.ics");
        fs::write(&event_file, ics_content)
            .await
            .expect("Failed to write test file");

        let db = Db::open(None)
            .await
            .expect("Failed to create test database");

        // Act
        add_calendar(&db, &calendar_path)
            .await
            .expect("Failed to add calendar");

        // Assert
        let event = db
            .events
            .get("test-event-single")
            .await
            .expect("Failed to get event");
        assert!(event.is_some());
    }

    #[tokio::test]
    async fn add_calendar_processes_multiple_ics_files() {
        // Arrange
        let temp_dir = tempfile::tempdir().expect("Failed to create temp dir");
        let calendar_path = temp_dir.path().to_path_buf();

        // Create first file with an event
        let event_ics = "BEGIN:VCALENDAR\r
VERSION:2.0\r
PRODID:-//AIM//Test//EN\r
BEGIN:VEVENT\r
UID:test-event-1\r
DTSTAMP:20250115T120000Z\r
DTSTART:20250115T100000Z\r
DTEND:20250115T110000Z\r
SUMMARY:Event 1\r
END:VEVENT\r
END:VCALENDAR\r
";
        fs::write(calendar_path.join("event1.ics"), event_ics)
            .await
            .expect("Failed to write event1.ics");

        // Create second file with a todo
        let todo_ics = "BEGIN:VCALENDAR\r
VERSION:2.0\r
PRODID:-//AIM//Test//EN\r
BEGIN:VTODO\r
UID:test-todo-1\r
DTSTAMP:20250115T120000Z\r
SUMMARY:Todo 1\r
END:VTODO\r
END:VCALENDAR\r
";
        fs::write(calendar_path.join("todo1.ics"), todo_ics)
            .await
            .expect("Failed to write todo1.ics");

        let db = Db::open(None)
            .await
            .expect("Failed to create test database");

        // Act
        add_calendar(&db, &calendar_path)
            .await
            .expect("Failed to add calendar");

        // Assert
        let event = db
            .events
            .get("test-event-1")
            .await
            .expect("Failed to get event");
        let todo = db
            .todos
            .get("test-todo-1")
            .await
            .expect("Failed to get todo");

        assert!(event.is_some());
        assert!(todo.is_some());
    }

    #[tokio::test]
    async fn add_calendar_skips_non_ics_files() {
        // Arrange
        let temp_dir = tempfile::tempdir().expect("Failed to create temp dir");
        let calendar_path = temp_dir.path().to_path_buf();

        // Create a .txt file (should be skipped)
        fs::write(calendar_path.join("readme.txt"), "This is not an .ics file")
            .await
            .expect("Failed to write readme.txt");

        // Create a .md file (should be skipped)
        fs::write(calendar_path.join("notes.md"), "# Notes")
            .await
            .expect("Failed to write notes.md");

        // Create one valid .ics file
        let ics_content = "BEGIN:VCALENDAR\r
VERSION:2.0\r
PRODID:-//AIM//Test//EN\r
BEGIN:VEVENT\r
UID:test-event-skip\r
DTSTAMP:20250115T120000Z\r
DTSTART:20250115T100000Z\r
DTEND:20250115T110000Z\r
SUMMARY:Skip Test Event\r
END:VEVENT\r
END:VCALENDAR\r
";
        fs::write(calendar_path.join("event.ics"), ics_content)
            .await
            .expect("Failed to write event.ics");

        let db = Db::open(None)
            .await
            .expect("Failed to create test database");

        // Act
        add_calendar(&db, &calendar_path)
            .await
            .expect("Failed to add calendar");

        // Assert
        let event = db
            .events
            .get("test-event-skip")
            .await
            .expect("Failed to get event");
        assert!(event.is_some());
    }

    #[tokio::test]
    async fn add_calendar_handles_empty_directory() {
        // Arrange
        let temp_dir = tempfile::tempdir().expect("Failed to create temp dir");
        let calendar_path = temp_dir.path().to_path_buf();

        let db = Db::open(None)
            .await
            .expect("Failed to create test database");

        // Act
        let result = add_calendar(&db, &calendar_path).await;

        // Assert
        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn add_calendar_processes_files_with_multiple_components() {
        // Arrange
        let temp_dir = tempfile::tempdir().expect("Failed to create temp dir");
        let calendar_path = temp_dir.path().to_path_buf();

        let ics_content = "BEGIN:VCALENDAR\r
VERSION:2.0\r
PRODID:-//AIM//Test//EN\r
BEGIN:VEVENT\r
UID:multi-event-1\r
DTSTAMP:20250115T120000Z\r
DTSTART:20250115T100000Z\r
DTEND:20250115T110000Z\r
SUMMARY:Multi Event 1\r
END:VEVENT\r
BEGIN:VTODO\r
UID:multi-todo-1\r
DTSTAMP:20250115T120000Z\r
SUMMARY:Multi Todo 1\r
END:VTODO\r
BEGIN:VEVENT\r
UID:multi-event-2\r
DTSTAMP:20250115T120000Z\r
DTSTART:20250115T120000Z\r
DTEND:20250115T130000Z\r
SUMMARY:Multi Event 2\r
END:VEVENT\r
END:VCALENDAR\r
";

        fs::write(calendar_path.join("mixed.ics"), ics_content)
            .await
            .expect("Failed to write mixed.ics");

        let db = Db::open(None)
            .await
            .expect("Failed to create test database");

        // Act
        add_calendar(&db, &calendar_path)
            .await
            .expect("Failed to add calendar");

        // Assert
        let event1 = db
            .events
            .get("multi-event-1")
            .await
            .expect("Failed to get event 1");
        let _event2 = db
            .events
            .get("multi-event-2")
            .await
            .expect("Failed to get event 2");
        let todo = db
            .todos
            .get("multi-todo-1")
            .await
            .expect("Failed to get todo");

        // Note: there may be FK constraints preventing event2 insertion
        // in the resources table. This is a test design limitation.
        assert!(event1.is_some());
        assert!(todo.is_some());
    }

    #[tokio::test]
    async fn add_continues_on_corrupted_file() {
        // Arrange
        let temp_dir = tempfile::tempdir().expect("Failed to create temp dir");
        let calendar_path = temp_dir.path().to_path_buf();

        // Create a corrupted .ics file
        fs::write(
            calendar_path.join("corrupted.ics"),
            "INVALID CALENDAR CONTENT",
        )
        .await
        .expect("Failed to write corrupted.ics");

        // Create a valid .ics file
        let valid_ics = "BEGIN:VCALENDAR\r
VERSION:2.0\r
PRODID:-//AIM//Test//EN\r
BEGIN:VEVENT\r
UID:valid-after-corrupt\r
DTSTAMP:20250115T120000Z\r
DTSTART:20250115T100000Z\r
DTEND:20250115T110000Z\r
SUMMARY:Valid Event\r
END:VEVENT\r
END:VCALENDAR\r
";
        fs::write(calendar_path.join("valid.ics"), valid_ics)
            .await
            .expect("Failed to write valid.ics");

        let db = Db::open(None)
            .await
            .expect("Failed to create test database");

        // Act - should not fail even with corrupted file
        let result = add_calendar(&db, &calendar_path).await;

        // Assert - should succeed and process the valid file
        assert!(result.is_ok());

        let event = db
            .events
            .get("valid-after-corrupt")
            .await
            .expect("Failed to get event");
        assert!(event.is_some());
    }
}