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
// Copyright 2023-2024 Hugo Osvaldo Barrera
//
// SPDX-License-Identifier: EUPL-1.2

use anyhow::{bail, ensure, Context};
use http::StatusCode;
use libdav::{
    dav::{mime_types, WebDavError},
    names,
};
use std::fmt::Write;

use crate::{random_string, TestData};

pub(crate) async fn test_create_and_delete_collection(test_data: &TestData) -> anyhow::Result<()> {
    let orig_calendar_count = test_data.calendar_count().await?;

    let new_collection = format!(
        "{}{}/",
        test_data.first_calendar_home_set()?,
        &random_string(16)
    );
    test_data.caldav.create_calendar(&new_collection).await?;

    let new_calendar_count = test_data.calendar_count().await?;

    ensure!(orig_calendar_count + 1 == new_calendar_count);

    // Get the etag of the newly created calendar:
    // ASSERTION: this validates that a collection with a matching href was created.
    let calendars = test_data
        .caldav
        .find_calendars(test_data.first_calendar_home_set()?)
        .await?;
    let etag = calendars
        .into_iter()
        .find(|collection| collection.href == new_collection)
        .context("created calendar was not returned when finding calendars")?
        .etag;

    // Try deleting with the wrong etag.
    test_data
        .caldav
        .delete(&new_collection, "wrong-etag")
        .await
        .unwrap_err();

    let Some(etag) = etag else {
        bail!("deletion is only supported on servers which provide etags")
    };

    // Delete the calendar
    test_data.caldav.delete(new_collection, etag).await?;

    let third_calendar_count = test_data.calendar_count().await?;
    ensure!(orig_calendar_count == third_calendar_count);

    Ok(())
}

pub(crate) async fn test_create_and_force_delete_collection(
    test_data: &TestData,
) -> anyhow::Result<()> {
    let orig_calendar_count = test_data.calendar_count().await?;

    let new_collection = format!(
        "{}{}/",
        test_data.first_calendar_home_set()?.path(),
        &random_string(16)
    );
    test_data.caldav.create_calendar(&new_collection).await?;

    let after_creationg_calendar_count = test_data.calendar_count().await?;
    ensure!(orig_calendar_count + 1 == after_creationg_calendar_count);

    // Force-delete the collection
    test_data.caldav.force_delete(&new_collection).await?;

    let after_deletion_calendar_count = test_data.calendar_count().await?;
    ensure!(orig_calendar_count == after_deletion_calendar_count);

    Ok(())
}

pub(crate) async fn test_setting_and_getting_displayname(
    test_data: &TestData,
) -> anyhow::Result<()> {
    let new_collection = format!(
        "{}{}/",
        test_data.first_calendar_home_set()?.path(),
        &random_string(16)
    );
    test_data.caldav.create_calendar(&new_collection).await?;

    let first_name = "panda-events";
    test_data
        .caldav
        .set_property(&new_collection, &names::DISPLAY_NAME, Some(first_name))
        .await
        .context("setting collection displayname")?;

    let value = test_data
        .caldav
        .get_property(&new_collection, &names::DISPLAY_NAME)
        .await
        .context("getting collection displayname")?;

    ensure!(value == Some(String::from(first_name)));

    let new_name = "🔥🔥🔥<lol>";
    test_data
        .caldav
        .set_property(&new_collection, &names::DISPLAY_NAME, Some(new_name))
        .await
        .context("setting collection displayname")?;

    let value = test_data
        .caldav
        .get_property(&new_collection, &names::DISPLAY_NAME)
        .await
        .context("getting collection displayname")?;

    ensure!(value == Some(String::from(new_name)));

    test_data.caldav.force_delete(&new_collection).await?;

    Ok(())
}

pub(crate) async fn test_setting_and_getting_colour(test_data: &TestData) -> anyhow::Result<()> {
    let new_collection = format!(
        "{}{}/",
        test_data.first_calendar_home_set()?.path(),
        &random_string(16)
    );
    test_data.caldav.create_calendar(&new_collection).await?;

    let colour = "#ff00ff";
    test_data
        .caldav
        .set_property(&new_collection, &names::CALENDAR_COLOUR, Some(colour))
        .await
        .context("setting collection colour")?;

    let value = test_data
        .caldav
        .get_property(&new_collection, &names::CALENDAR_COLOUR)
        .await
        .context("getting collection colour")?;

    match value {
        Some(c) => ensure!(c.eq_ignore_ascii_case(colour) || c.eq_ignore_ascii_case("#FF00FFFF")),
        None => bail!("Set a colour but then got colour None"),
    }

    test_data.caldav.force_delete(&new_collection).await?;

    Ok(())
}

pub(crate) async fn test_get_properties(test_data: &TestData) -> anyhow::Result<()> {
    let new_collection = format!(
        "{}{}/",
        test_data.first_calendar_home_set()?.path(),
        &random_string(16)
    );
    test_data.caldav.create_calendar(&new_collection).await?;

    let colour = "#ff00ff";
    let colour_alpha = "#FF00FFFF"; // Some servers normalise to this value.
    test_data
        .caldav
        .set_property(&new_collection, &names::CALENDAR_COLOUR, Some(colour))
        .await
        .context("setting collection colour")?;

    let name = "panda-events";
    test_data
        .caldav
        .set_property(&new_collection, &names::DISPLAY_NAME, Some(name))
        .await
        .context("setting collection displayname")?;

    let values = test_data
        .caldav
        .get_properties(
            &new_collection,
            &[
                &names::CALENDAR_COLOUR,
                &names::DISPLAY_NAME,
                &names::CALENDAR_ORDER,
            ],
        )
        .await
        .context("getting collection properties")?;

    for value in values {
        match value.0 {
            names::CALENDAR_COLOUR => match value.1 {
                Some(c) => {
                    ensure!(c.eq_ignore_ascii_case(colour) || c.eq_ignore_ascii_case(colour_alpha));
                }
                None => bail!("Set a colour but then got colour None"),
            },
            names::DISPLAY_NAME => ensure!(value.1 == Some("panda-events".into())),
            names::CALENDAR_ORDER => ensure!(value.1 == None),
            _ => bail!("got unexpected property"),
        }
    }

    test_data.caldav.force_delete(&new_collection).await?;

    Ok(())
}

fn minimal_icalendar() -> anyhow::Result<Vec<u8>> {
    let mut entry = String::new();
    let uid = random_string(12);

    entry.push_str("BEGIN:VCALENDAR\r\n");
    entry.push_str("VERSION:2.0\r\n");
    entry.push_str("PRODID:-//hacksw/handcal//NONSGML v1.0//EN\r\n");
    entry.push_str("BEGIN:VEVENT\r\n");
    write!(entry, "UID:{uid}\r\n")?;
    entry.push_str("DTSTAMP:19970610T172345Z\r\n");
    entry.push_str("DTSTART:19970714T170000Z\r\n");
    entry.push_str("SUMMARY:hello\\, testing\r\n");
    entry.push_str("END:VEVENT\r\n");
    entry.push_str("END:VCALENDAR\r\n");

    Ok(entry.into())
}

fn funky_calendar_event() -> anyhow::Result<Vec<u8>> {
    let mut entry = String::new();
    let uid = random_string(12);

    entry.push_str("BEGIN:VCALENDAR\r\n");
    entry.push_str("VERSION:2.0\r\n");
    entry.push_str("PRODID:-//hacksw/handcal//NONSGML v1.0//EN\r\n");
    entry.push_str("BEGIN:VEVENT\r\n");
    write!(entry, "UID:{uid}\r\n")?;
    entry.push_str("DTSTAMP:19970610T172345Z\r\n");
    entry.push_str("DTSTART:19970714T170000Z\r\n");
    entry.push_str("SUMMARY:eine Testparty mit Bären\r\n");
    entry.push_str("END:VEVENT\r\n");
    entry.push_str("END:VCALENDAR\r\n");

    Ok(entry.into())
}

pub(crate) async fn test_create_and_delete_resource(test_data: &TestData) -> anyhow::Result<()> {
    let collection = format!(
        "{}{}/",
        test_data.first_calendar_home_set()?.path(),
        &random_string(16)
    );
    test_data.caldav.create_calendar(&collection).await?;

    let resource = format!("{}{}.ics", collection, &random_string(12));
    let content = minimal_icalendar()?;

    test_data
        .caldav
        .create_resource(&resource, content.clone(), mime_types::CALENDAR)
        .await?;

    let items = test_data.caldav.list_resources(&collection).await?;
    ensure!(items.len() == 1);

    let updated_entry = String::from_utf8(content)?
        .replace("hello", "goodbye")
        .as_bytes()
        .to_vec();

    // ASSERTION: deleting with a wrong etag fails.
    test_data
        .caldav
        .delete(&resource, "wrong-lol")
        .await
        .unwrap_err();

    // ASSERTION: creating conflicting resource fails.
    test_data
        .caldav
        .create_resource(&resource, updated_entry.clone(), mime_types::CALENDAR)
        .await
        .unwrap_err();

    // ASSERTION: item with matching href exists.
    let etag = items
        .into_iter()
        .find_map(|i| {
            if i.href == resource {
                Some(i.details.etag)
            } else {
                None
            }
        })
        .context("todo")?
        .context("todo")?;

    // ASSERTION: updating with wrong etag fails
    match test_data
        .caldav
        .update_resource(
            &resource,
            updated_entry.clone(),
            &resource,
            mime_types::CALENDAR,
        )
        .await
        .unwrap_err()
    {
        WebDavError::BadStatusCode(StatusCode::PRECONDITION_FAILED) => {}
        _ => panic!("updating entry with the wrong etag did not return the wrong error type"),
    }

    // ASSERTION: updating with correct etag work
    test_data
        .caldav
        .update_resource(&resource, updated_entry, &etag, mime_types::CALENDAR)
        .await?;

    // ASSERTION: deleting with outdated etag fails
    test_data.caldav.delete(&resource, &etag).await.unwrap_err();

    let items = test_data.caldav.list_resources(&collection).await?;
    ensure!(items.len() == 1);

    let etag = items
        .into_iter()
        .find_map(|i| {
            if i.href == resource {
                Some(i.details.etag)
            } else {
                None
            }
        })
        .context("todo")?
        .context("todo")?;

    // ASSERTION: deleting with correct etag works
    test_data.caldav.delete(&resource, &etag).await?;

    let items = test_data.caldav.list_resources(&collection).await?;
    ensure!(items.len() == 0);
    Ok(())
}

pub(crate) async fn test_create_and_fetch_resource(test_data: &TestData) -> anyhow::Result<()> {
    let collection = format!(
        "{}{}/",
        test_data.first_calendar_home_set()?.path(),
        &random_string(16)
    );
    test_data.caldav.create_calendar(&collection).await?;

    let resource = format!("{}{}.ics", collection, &random_string(12));
    let event_data = minimal_icalendar()?;
    test_data
        .caldav
        .create_resource(&resource, event_data.clone(), mime_types::CALENDAR)
        .await?;

    let items = test_data.caldav.list_resources(&collection).await?;
    ensure!(items.len() == 1);

    let fetched = test_data
        .caldav
        .get_calendar_resources(&collection, &[&items[0].href])
        .await?;
    ensure!(fetched.len() == 1);
    assert_eq!(fetched[0].href, resource);

    let fetched_data = &fetched[0].content.as_ref().unwrap().data;
    // TODO: compare normalised items here!
    ensure!(fetched_data.starts_with("BEGIN:VCALENDAR\r\nVERSION:2.0\r\n"));
    ensure!(fetched_data.contains("SUMMARY:hello\\, testing\r\n"));
    Ok(())
}

pub(crate) async fn test_create_and_fetch_resource_with_non_ascii_data(
    test_data: &TestData,
) -> anyhow::Result<()> {
    let collection = format!(
        "{}{}/",
        test_data.first_calendar_home_set()?.path(),
        &random_string(16)
    );
    test_data.caldav.create_calendar(&collection).await?;

    let resource = format!("{}{}.ics", collection, &random_string(12));
    let event_data = funky_calendar_event()?;
    test_data
        .caldav
        .create_resource(&resource, event_data.clone(), mime_types::CALENDAR)
        .await?;

    let items = test_data.caldav.list_resources(&collection).await?;
    ensure!(items.len() == 1);

    let mut fetched = test_data
        .caldav
        .get_calendar_resources(&collection, &[&items[0].href])
        .await?;
    ensure!(fetched.len() == 1);
    assert_eq!(fetched[0].href, resource);

    let fetched_data = fetched.pop().unwrap().content.unwrap().data;

    ensure!(fetched_data.starts_with("BEGIN:VCALENDAR\r\nVERSION:2.0\r\n"));
    ensure!(fetched_data.contains("SUMMARY:eine Testparty mit Bären"));

    // TODO: compare normalised items here!
    // Need to do a semantic comparison of the send data vs fetched data. E.g.: to items should be
    // considered the same if only the order of its properties has changed.

    // This only compares length until the above is implemented.
    // Some servers move around the UID:, but the total length ends up being the same.
    assert_eq!(
        fetched_data.len(),
        String::from_utf8(event_data).unwrap().len()
    );
    Ok(())
}

pub(crate) async fn test_create_and_fetch_resource_with_weird_characters(
    test_data: &TestData,
) -> anyhow::Result<()> {
    let collection = format!(
        "{}{}/",
        test_data.first_calendar_home_set()?.path(),
        &random_string(16)
    );
    test_data.caldav.create_calendar(&collection).await?;

    let mut count = 0;
    for symbol in ":?# []@!$&'()*+,;=<>".chars() {
        let resource = format!("{}weird-{}-{}.ics", collection, symbol, &random_string(6));
        test_data
            .caldav
            .create_resource(&resource, minimal_icalendar()?, mime_types::CALENDAR)
            .await
            .context(format!("failed to create resource with '{symbol}'"))?;
        count += 1;

        let items = test_data
            .caldav
            .list_resources(&collection)
            .await
            .context(format!("failed listing resource (when testing '{symbol}')"))?;
        ensure!(items.len() == count);
        ensure!(
            items.iter().any(|i| i.href == resource),
            format!("created item must be present when listing (testing '{symbol}')")
        );

        let fetched = test_data
            .caldav
            .get_calendar_resources(&collection, &[&resource])
            .await
            .context(format!("failed to get resource with '{symbol}'"))?;
        ensure!(fetched.len() == 1);
        assert_eq!(fetched[0].href, resource);
    }

    Ok(())
}

pub(crate) async fn test_fetch_missing(test_data: &TestData) -> anyhow::Result<()> {
    let collection = format!(
        "{}{}/",
        test_data.first_calendar_home_set()?.path(),
        &random_string(16)
    );
    test_data.caldav.create_calendar(&collection).await?;

    let resource = format!("{}{}.ics", collection, &random_string(12));
    test_data
        .caldav
        .create_resource(&resource, minimal_icalendar()?, mime_types::CALENDAR)
        .await?;

    let missing = format!("{}{}.ics", collection, &random_string(8));
    let fetched = test_data
        .caldav
        .get_calendar_resources(&collection, &[&resource, &missing])
        .await?;
    log::debug!("{:?}", &fetched);
    // Nextcloud omits missing entries, rather than return 404, so we might have just one result.
    match fetched.len() {
        1 => {}
        2 => {
            // ASSERTION: one of the two entries is the 404 one
            fetched
                .iter()
                .find(|r| r.content == Err(StatusCode::NOT_FOUND))
                .context("no entry was missing, but one was expected")?;
        }
        _ => bail!("bogus amount of resources found"),
    }
    // ASSERTION: one entry is the matching resource
    fetched
        .iter()
        .find(|r| r.content.is_ok())
        .context("no entry was found, but one was expected")?;
    Ok(())
}

pub(crate) async fn test_check_caldav_support(test_data: &TestData) -> anyhow::Result<()> {
    test_data
        .caldav
        .check_support(test_data.caldav.base_url())
        .await?;

    Ok(())
}