aboutsummaryrefslogtreecommitdiff
path: root/aero-proto/src/dav/resource.rs
blob: b5ae029ac938cec9c2b3eafb7da308ea87055ef8 (plain) (blame)
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
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
use std::sync::Arc;
type ArcUser = std::sync::Arc<User>;

use anyhow::{anyhow, Result};
use futures::io::AsyncReadExt;
use futures::stream::{StreamExt, TryStreamExt};
use futures::{future::BoxFuture, future::FutureExt};

use aero_collections::{
    calendar::Calendar,
    davdag::{BlobId, Etag, SyncChange, Token},
    user::User,
};
use aero_dav::acltypes as acl;
use aero_dav::caltypes as cal;
use aero_dav::realization::{self as all, All};
use aero_dav::synctypes as sync;
use aero_dav::types as dav;
use aero_dav::versioningtypes as vers;

use super::node::PropertyStream;
use crate::dav::node::{Content, DavNode, PutPolicy};

/// Why "https://aerogramme.0"?
/// Because tokens must be valid URI.
/// And numeric TLD are ~mostly valid in URI (check the .42 TLD experience)
/// and at the same time, they are not used sold by the ICANN and there is no plan to use them.
/// So I am sure that the URL remains invalid, avoiding leaking requests to an hardcoded URL in the
/// future.
/// The best option would be to make it configurable ofc, so someone can put a domain name
/// that they control, it would probably improve compatibility (maybe some WebDAV spec tells us
/// how to handle/resolve this URI but I am not aware of that...). But that's not the plan for
/// now. So here we are: https://aerogramme.0.
pub const BASE_TOKEN_URI: &str = "https://aerogramme.0/sync/";

#[derive(Clone)]
pub(crate) struct RootNode {}
impl DavNode for RootNode {
    fn fetch<'a>(
        &self,
        user: &'a ArcUser,
        path: &'a [&str],
        create: bool,
    ) -> BoxFuture<'a, Result<Box<dyn DavNode>>> {
        if path.len() == 0 {
            let this = self.clone();
            return async { Ok(Box::new(this) as Box<dyn DavNode>) }.boxed();
        }

        if path[0] == user.username {
            let child = Box::new(HomeNode {});
            return child.fetch(user, &path[1..], create);
        }

        //@NOTE: We can't create a node at this level
        async { Err(anyhow!("Not found")) }.boxed()
    }

    fn children<'a>(&self, user: &'a ArcUser) -> BoxFuture<'a, Vec<Box<dyn DavNode>>> {
        async { vec![Box::new(HomeNode {}) as Box<dyn DavNode>] }.boxed()
    }

    fn path(&self, user: &ArcUser) -> String {
        "/".into()
    }

    fn supported_properties(&self, user: &ArcUser) -> dav::PropName<All> {
        dav::PropName(vec![
            dav::PropertyRequest::DisplayName,
            dav::PropertyRequest::ResourceType,
            dav::PropertyRequest::GetContentType,
            dav::PropertyRequest::Extension(all::PropertyRequest::Acl(
                acl::PropertyRequest::CurrentUserPrincipal,
            )),
        ])
    }

    fn properties(&self, user: &ArcUser, prop: dav::PropName<All>) -> PropertyStream<'static> {
        let user = user.clone();
        futures::stream::iter(prop.0)
            .map(move |n| {
                let prop = match n {
                    dav::PropertyRequest::DisplayName => {
                        dav::Property::DisplayName("DAV Root".to_string())
                    }
                    dav::PropertyRequest::ResourceType => {
                        dav::Property::ResourceType(vec![dav::ResourceType::Collection])
                    }
                    dav::PropertyRequest::GetContentType => {
                        dav::Property::GetContentType("httpd/unix-directory".into())
                    }
                    dav::PropertyRequest::Extension(all::PropertyRequest::Acl(
                        acl::PropertyRequest::CurrentUserPrincipal,
                    )) => dav::Property::Extension(all::Property::Acl(
                        acl::Property::CurrentUserPrincipal(acl::User::Authenticated(dav::Href(
                            HomeNode {}.path(&user),
                        ))),
                    )),
                    v => return Err(v),
                };
                Ok(prop)
            })
            .boxed()
    }

    fn put<'a>(
        &'a self,
        _policy: PutPolicy,
        stream: Content<'a>,
    ) -> BoxFuture<'a, std::result::Result<Etag, std::io::Error>> {
        futures::future::err(std::io::Error::from(std::io::ErrorKind::Unsupported)).boxed()
    }

    fn content<'a>(&self) -> Content<'a> {
        futures::stream::once(futures::future::err(std::io::Error::from(
            std::io::ErrorKind::Unsupported,
        )))
        .boxed()
    }

    fn content_type(&self) -> &str {
        "text/plain"
    }

    fn etag(&self) -> BoxFuture<Option<Etag>> {
        async { None }.boxed()
    }

    fn delete(&self) -> BoxFuture<std::result::Result<(), std::io::Error>> {
        async { Err(std::io::Error::from(std::io::ErrorKind::PermissionDenied)) }.boxed()
    }

    fn diff<'a>(
        &self,
        _sync_token: Option<Token>,
    ) -> BoxFuture<
        'a,
        std::result::Result<(Token, Vec<Box<dyn DavNode>>, Vec<dav::Href>), std::io::Error>,
    > {
        async { Err(std::io::Error::from(std::io::ErrorKind::Unsupported)) }.boxed()
    }

    fn dav_header(&self) -> String {
        "1".into()
    }
}

#[derive(Clone)]
pub(crate) struct HomeNode {}
impl DavNode for HomeNode {
    fn fetch<'a>(
        &self,
        user: &'a ArcUser,
        path: &'a [&str],
        create: bool,
    ) -> BoxFuture<'a, Result<Box<dyn DavNode>>> {
        if path.len() == 0 {
            let node = Box::new(self.clone()) as Box<dyn DavNode>;
            return async { Ok(node) }.boxed();
        }

        if path[0] == "calendar" {
            return async move {
                let child = Box::new(CalendarListNode::new(user).await?);
                child.fetch(user, &path[1..], create).await
            }
            .boxed();
        }

        //@NOTE: we can't create a node at this level
        async { Err(anyhow!("Not found")) }.boxed()
    }

    fn children<'a>(&self, user: &'a ArcUser) -> BoxFuture<'a, Vec<Box<dyn DavNode>>> {
        async {
            CalendarListNode::new(user)
                .await
                .map(|c| vec![Box::new(c) as Box<dyn DavNode>])
                .unwrap_or(vec![])
        }
        .boxed()
    }

    fn path(&self, user: &ArcUser) -> String {
        format!("/{}/", user.username)
    }

    fn supported_properties(&self, user: &ArcUser) -> dav::PropName<All> {
        dav::PropName(vec![
            dav::PropertyRequest::DisplayName,
            dav::PropertyRequest::ResourceType,
            dav::PropertyRequest::GetContentType,
            dav::PropertyRequest::Extension(all::PropertyRequest::Cal(
                cal::PropertyRequest::CalendarHomeSet,
            )),
        ])
    }
    fn properties(&self, user: &ArcUser, prop: dav::PropName<All>) -> PropertyStream<'static> {
        let user = user.clone();

        futures::stream::iter(prop.0)
            .map(move |n| {
                let prop = match n {
                    dav::PropertyRequest::DisplayName => {
                        dav::Property::DisplayName(format!("{} home", user.username))
                    }
                    dav::PropertyRequest::ResourceType => dav::Property::ResourceType(vec![
                        dav::ResourceType::Collection,
                        dav::ResourceType::Extension(all::ResourceType::Acl(
                            acl::ResourceType::Principal,
                        )),
                    ]),
                    dav::PropertyRequest::GetContentType => {
                        dav::Property::GetContentType("httpd/unix-directory".into())
                    }
                    dav::PropertyRequest::Extension(all::PropertyRequest::Cal(
                        cal::PropertyRequest::CalendarHomeSet,
                    )) => dav::Property::Extension(all::Property::Cal(
                        cal::Property::CalendarHomeSet(dav::Href(
                            //@FIXME we are hardcoding the calendar path, instead we would want to use
                            //objects
                            format!("/{}/calendar/", user.username),
                        )),
                    )),
                    v => return Err(v),
                };
                Ok(prop)
            })
            .boxed()
    }

    fn put<'a>(
        &'a self,
        _policy: PutPolicy,
        stream: Content<'a>,
    ) -> BoxFuture<'a, std::result::Result<Etag, std::io::Error>> {
        futures::future::err(std::io::Error::from(std::io::ErrorKind::Unsupported)).boxed()
    }

    fn content<'a>(&self) -> Content<'a> {
        futures::stream::once(futures::future::err(std::io::Error::from(
            std::io::ErrorKind::Unsupported,
        )))
        .boxed()
    }

    fn content_type(&self) -> &str {
        "text/plain"
    }

    fn etag(&self) -> BoxFuture<Option<Etag>> {
        async { None }.boxed()
    }

    fn delete(&self) -> BoxFuture<std::result::Result<(), std::io::Error>> {
        async { Err(std::io::Error::from(std::io::ErrorKind::PermissionDenied)) }.boxed()
    }
    fn diff<'a>(
        &self,
        _sync_token: Option<Token>,
    ) -> BoxFuture<
        'a,
        std::result::Result<(Token, Vec<Box<dyn DavNode>>, Vec<dav::Href>), std::io::Error>,
    > {
        async { Err(std::io::Error::from(std::io::ErrorKind::Unsupported)) }.boxed()
    }

    fn dav_header(&self) -> String {
        "1, access-control, calendar-access".into()
    }
}

#[derive(Clone)]
pub(crate) struct CalendarListNode {
    list: Vec<String>,
}
impl CalendarListNode {
    async fn new(user: &ArcUser) -> Result<Self> {
        let list = user.calendars.list(user).await?;
        Ok(Self { list })
    }
}
impl DavNode for CalendarListNode {
    fn fetch<'a>(
        &self,
        user: &'a ArcUser,
        path: &'a [&str],
        create: bool,
    ) -> BoxFuture<'a, Result<Box<dyn DavNode>>> {
        if path.len() == 0 {
            let node = Box::new(self.clone()) as Box<dyn DavNode>;
            return async { Ok(node) }.boxed();
        }

        async move {
            //@FIXME: we should create a node if the open returns a "not found".
            let cal = user
                .calendars
                .open(user, path[0])
                .await?
                .ok_or(anyhow!("Not found"))?;
            let child = Box::new(CalendarNode {
                col: cal,
                calname: path[0].to_string(),
            });
            child.fetch(user, &path[1..], create).await
        }
        .boxed()
    }

    fn children<'a>(&self, user: &'a ArcUser) -> BoxFuture<'a, Vec<Box<dyn DavNode>>> {
        let list = self.list.clone();
        async move {
            //@FIXME maybe we want to be lazy here?!
            futures::stream::iter(list.iter())
                .filter_map(|name| async move {
                    user.calendars
                        .open(user, name)
                        .await
                        .ok()
                        .flatten()
                        .map(|v| (name, v))
                })
                .map(|(name, cal)| {
                    Box::new(CalendarNode {
                        col: cal,
                        calname: name.to_string(),
                    }) as Box<dyn DavNode>
                })
                .collect::<Vec<Box<dyn DavNode>>>()
                .await
        }
        .boxed()
    }

    fn path(&self, user: &ArcUser) -> String {
        format!("/{}/calendar/", user.username)
    }

    fn supported_properties(&self, user: &ArcUser) -> dav::PropName<All> {
        dav::PropName(vec![
            dav::PropertyRequest::DisplayName,
            dav::PropertyRequest::ResourceType,
            dav::PropertyRequest::GetContentType,
        ])
    }
    fn properties(&self, user: &ArcUser, prop: dav::PropName<All>) -> PropertyStream<'static> {
        let user = user.clone();

        futures::stream::iter(prop.0)
            .map(move |n| {
                let prop = match n {
                    dav::PropertyRequest::DisplayName => {
                        dav::Property::DisplayName(format!("{} calendars", user.username))
                    }
                    dav::PropertyRequest::ResourceType => {
                        dav::Property::ResourceType(vec![dav::ResourceType::Collection])
                    }
                    dav::PropertyRequest::GetContentType => {
                        dav::Property::GetContentType("httpd/unix-directory".into())
                    }
                    v => return Err(v),
                };
                Ok(prop)
            })
            .boxed()
    }

    fn put<'a>(
        &'a self,
        _policy: PutPolicy,
        stream: Content<'a>,
    ) -> BoxFuture<'a, std::result::Result<Etag, std::io::Error>> {
        futures::future::err(std::io::Error::from(std::io::ErrorKind::Unsupported)).boxed()
    }

    fn content<'a>(&self) -> Content<'a> {
        futures::stream::once(futures::future::err(std::io::Error::from(
            std::io::ErrorKind::Unsupported,
        )))
        .boxed()
    }

    fn content_type(&self) -> &str {
        "text/plain"
    }

    fn etag(&self) -> BoxFuture<Option<Etag>> {
        async { None }.boxed()
    }

    fn delete(&self) -> BoxFuture<std::result::Result<(), std::io::Error>> {
        async { Err(std::io::Error::from(std::io::ErrorKind::PermissionDenied)) }.boxed()
    }
    fn diff<'a>(
        &self,
        _sync_token: Option<Token>,
    ) -> BoxFuture<
        'a,
        std::result::Result<(Token, Vec<Box<dyn DavNode>>, Vec<dav::Href>), std::io::Error>,
    > {
        async { Err(std::io::Error::from(std::io::ErrorKind::Unsupported)) }.boxed()
    }

    fn dav_header(&self) -> String {
        "1, access-control, calendar-access".into()
    }
}

#[derive(Clone)]
pub(crate) struct CalendarNode {
    col: Arc<Calendar>,
    calname: String,
}
impl DavNode for CalendarNode {
    fn fetch<'a>(
        &self,
        user: &'a ArcUser,
        path: &'a [&str],
        create: bool,
    ) -> BoxFuture<'a, Result<Box<dyn DavNode>>> {
        if path.len() == 0 {
            let node = Box::new(self.clone()) as Box<dyn DavNode>;
            return async { Ok(node) }.boxed();
        }

        let col = self.col.clone();
        let calname = self.calname.clone();
        async move {
            match (col.dag().await.idx_by_filename.get(path[0]), create) {
                (Some(blob_id), _) => {
                    let child = Box::new(EventNode {
                        col: col.clone(),
                        calname,
                        filename: path[0].to_string(),
                        blob_id: *blob_id,
                    });
                    child.fetch(user, &path[1..], create).await
                }
                (None, true) => {
                    let child = Box::new(CreateEventNode {
                        col: col.clone(),
                        calname,
                        filename: path[0].to_string(),
                    });
                    child.fetch(user, &path[1..], create).await
                }
                _ => Err(anyhow!("Not found")),
            }
        }
        .boxed()
    }

    fn children<'a>(&self, user: &'a ArcUser) -> BoxFuture<'a, Vec<Box<dyn DavNode>>> {
        let col = self.col.clone();
        let calname = self.calname.clone();

        async move {
            col.dag()
                .await
                .idx_by_filename
                .iter()
                .map(|(filename, blob_id)| {
                    Box::new(EventNode {
                        col: col.clone(),
                        calname: calname.clone(),
                        filename: filename.to_string(),
                        blob_id: *blob_id,
                    }) as Box<dyn DavNode>
                })
                .collect()
        }
        .boxed()
    }

    fn path(&self, user: &ArcUser) -> String {
        format!("/{}/calendar/{}/", user.username, self.calname)
    }

    fn supported_properties(&self, user: &ArcUser) -> dav::PropName<All> {
        dav::PropName(vec![
            dav::PropertyRequest::DisplayName,
            dav::PropertyRequest::ResourceType,
            dav::PropertyRequest::GetContentType,
            dav::PropertyRequest::Extension(all::PropertyRequest::Cal(
                cal::PropertyRequest::SupportedCalendarComponentSet,
            )),
            dav::PropertyRequest::Extension(all::PropertyRequest::Sync(
                sync::PropertyRequest::SyncToken,
            )),
            dav::PropertyRequest::Extension(all::PropertyRequest::Vers(
                vers::PropertyRequest::SupportedReportSet,
            )),
        ])
    }
    fn properties(&self, _user: &ArcUser, prop: dav::PropName<All>) -> PropertyStream<'static> {
        let calname = self.calname.to_string();
        let col = self.col.clone();

        futures::stream::iter(prop.0)
            .then(move |n| {
                let calname = calname.clone();
                let col = col.clone();

                async move {
                    let prop = match n {
                        dav::PropertyRequest::DisplayName => {
                            dav::Property::DisplayName(format!("{} calendar", calname))
                        }
                        dav::PropertyRequest::ResourceType => dav::Property::ResourceType(vec![
                            dav::ResourceType::Collection,
                            dav::ResourceType::Extension(all::ResourceType::Cal(
                                cal::ResourceType::Calendar,
                            )),
                        ]),
                        //dav::PropertyRequest::GetContentType => dav::AnyProperty::Value(dav::Property::GetContentType("httpd/unix-directory".into())),
                        //@FIXME seems wrong but seems to be what Thunderbird expects...
                        dav::PropertyRequest::GetContentType => {
                            dav::Property::GetContentType("text/calendar".into())
                        }
                        dav::PropertyRequest::Extension(all::PropertyRequest::Cal(
                            cal::PropertyRequest::SupportedCalendarComponentSet,
                        )) => dav::Property::Extension(all::Property::Cal(
                            cal::Property::SupportedCalendarComponentSet(vec![
                                cal::CompSupport(cal::Component::VEvent),
                                cal::CompSupport(cal::Component::VTodo),
                                cal::CompSupport(cal::Component::VJournal),
                            ]),
                        )),
                        dav::PropertyRequest::Extension(all::PropertyRequest::Sync(
                            sync::PropertyRequest::SyncToken,
                        )) => match col.token().await {
                            Ok(token) => dav::Property::Extension(all::Property::Sync(
                                sync::Property::SyncToken(sync::SyncToken(format!(
                                    "{}{}",
                                    BASE_TOKEN_URI, token
                                ))),
                            )),
                            _ => return Err(n.clone()),
                        },
                        dav::PropertyRequest::Extension(all::PropertyRequest::Vers(
                            vers::PropertyRequest::SupportedReportSet,
                        )) => dav::Property::Extension(all::Property::Vers(
                            vers::Property::SupportedReportSet(vec![
                                vers::SupportedReport(vers::ReportName::Extension(
                                    all::ReportTypeName::Cal(cal::ReportTypeName::Multiget),
                                )),
                                vers::SupportedReport(vers::ReportName::Extension(
                                    all::ReportTypeName::Cal(cal::ReportTypeName::Query),
                                )),
                                vers::SupportedReport(vers::ReportName::Extension(
                                    all::ReportTypeName::Sync(sync::ReportTypeName::SyncCollection),
                                )),
                            ]),
                        )),
                        v => return Err(v),
                    };
                    Ok(prop)
                }
            })
            .boxed()
    }

    fn put<'a>(
        &'a self,
        _policy: PutPolicy,
        _stream: Content<'a>,
    ) -> BoxFuture<'a, std::result::Result<Etag, std::io::Error>> {
        futures::future::err(std::io::Error::from(std::io::ErrorKind::Unsupported)).boxed()
    }

    fn content<'a>(&self) -> Content<'a> {
        futures::stream::once(futures::future::err(std::io::Error::from(
            std::io::ErrorKind::Unsupported,
        )))
        .boxed()
    }

    fn content_type(&self) -> &str {
        "text/plain"
    }

    fn etag(&self) -> BoxFuture<Option<Etag>> {
        async { None }.boxed()
    }

    fn delete(&self) -> BoxFuture<std::result::Result<(), std::io::Error>> {
        async { Err(std::io::Error::from(std::io::ErrorKind::PermissionDenied)) }.boxed()
    }
    fn diff<'a>(
        &self,
        sync_token: Option<Token>,
    ) -> BoxFuture<
        'a,
        std::result::Result<(Token, Vec<Box<dyn DavNode>>, Vec<dav::Href>), std::io::Error>,
    > {
        let col = self.col.clone();
        let calname = self.calname.clone();
        async move {
            let sync_token = match sync_token {
                Some(v) => v,
                None => {
                    let token = col
                        .token()
                        .await
                        .or(Err(std::io::Error::from(std::io::ErrorKind::Interrupted)))?;
                    let ok_nodes = col
                        .dag()
                        .await
                        .idx_by_filename
                        .iter()
                        .map(|(filename, blob_id)| {
                            Box::new(EventNode {
                                col: col.clone(),
                                calname: calname.clone(),
                                filename: filename.to_string(),
                                blob_id: *blob_id,
                            }) as Box<dyn DavNode>
                        })
                        .collect();

                    return Ok((token, ok_nodes, vec![]));
                }
            };
            let (new_token, listed_changes) = match col.diff(sync_token).await {
                Ok(v) => v,
                Err(e) => {
                    tracing::info!(err=?e, "token resolution failed, maybe a forgotten token");
                    return Err(std::io::Error::from(std::io::ErrorKind::NotFound));
                }
            };

            let mut ok_nodes: Vec<Box<dyn DavNode>> = vec![];
            let mut rm_nodes: Vec<dav::Href> = vec![];
            for change in listed_changes.into_iter() {
                match change {
                    SyncChange::Ok((filename, blob_id)) => {
                        let child = Box::new(EventNode {
                            col: col.clone(),
                            calname: calname.clone(),
                            filename,
                            blob_id,
                        });
                        ok_nodes.push(child);
                    }
                    SyncChange::NotFound(filename) => {
                        rm_nodes.push(dav::Href(filename));
                    }
                }
            }

            Ok((new_token, ok_nodes, rm_nodes))
        }
        .boxed()
    }
    fn dav_header(&self) -> String {
        "1, access-control, calendar-access".into()
    }
}

#[derive(Clone)]
pub(crate) struct EventNode {
    col: Arc<Calendar>,
    calname: String,
    filename: String,
    blob_id: BlobId,
}

impl DavNode for EventNode {
    fn fetch<'a>(
        &self,
        user: &'a ArcUser,
        path: &'a [&str],
        create: bool,
    ) -> BoxFuture<'a, Result<Box<dyn DavNode>>> {
        if path.len() == 0 {
            let node = Box::new(self.clone()) as Box<dyn DavNode>;
            return async { Ok(node) }.boxed();
        }

        async {
            Err(anyhow!(
                "Not supported: can't create a child on an event node"
            ))
        }
        .boxed()
    }

    fn children<'a>(&self, user: &'a ArcUser) -> BoxFuture<'a, Vec<Box<dyn DavNode>>> {
        async { vec![] }.boxed()
    }

    fn path(&self, user: &ArcUser) -> String {
        format!(
            "/{}/calendar/{}/{}",
            user.username, self.calname, self.filename
        )
    }

    fn supported_properties(&self, user: &ArcUser) -> dav::PropName<All> {
        dav::PropName(vec![
            dav::PropertyRequest::DisplayName,
            dav::PropertyRequest::ResourceType,
            dav::PropertyRequest::GetEtag,
            dav::PropertyRequest::Extension(all::PropertyRequest::Cal(
                cal::PropertyRequest::CalendarData(cal::CalendarDataRequest::default()),
            )),
        ])
    }
    fn properties(&self, _user: &ArcUser, prop: dav::PropName<All>) -> PropertyStream<'static> {
        let this = self.clone();

        futures::stream::iter(prop.0)
            .then(move |n| {
                let this = this.clone();

                async move {
                    let prop = match &n {
                        dav::PropertyRequest::DisplayName => {
                            dav::Property::DisplayName(format!("{} event", this.filename))
                        }
                        dav::PropertyRequest::ResourceType => dav::Property::ResourceType(vec![]),
                        dav::PropertyRequest::GetContentType => {
                            dav::Property::GetContentType("text/calendar".into())
                        }
                        dav::PropertyRequest::GetEtag => {
                            let etag = this.etag().await.ok_or(n.clone())?;
                            dav::Property::GetEtag(etag)
                        }
                        dav::PropertyRequest::Extension(all::PropertyRequest::Cal(
                                cal::PropertyRequest::CalendarData(req),
                                )) => {
                            let ics = String::from_utf8(
                                this.col.get(this.blob_id).await.or(Err(n.clone()))?,
                                )
                                .or(Err(n.clone()))?;

                            let new_ics = match &req.comp {
                                None => ics,
                                Some(prune_comp) => {
                                    // parse content
                                    let ics = match icalendar::parser::read_calendar(&ics) {
                                        Ok(v) => v,
                                        Err(e) => {
                                            tracing::warn!(err=?e, "Unable to parse ICS in calendar-query");
                                            return Err(n.clone())
                                        }
                                    };

                                    // build a fake vcal component for caldav compat
                                    let fake_vcal_component = icalendar::parser::Component {
                                        name: cal::Component::VCalendar.as_str().into(),
                                        properties: ics.properties,
                                        components: ics.components,
                                    };

                                    // rebuild component
                                    let new_comp = match aero_ical::prune::component(&fake_vcal_component, prune_comp) {
                                        Some(v) => v,
                                        None => return Err(n.clone()),
                                    };

                                    // reserialize
                                    format!("{}", icalendar::parser::Calendar { properties: new_comp.properties, components: new_comp.components })
                                },
                            };



                            dav::Property::Extension(all::Property::Cal(
                                cal::Property::CalendarData(cal::CalendarDataPayload {
                                    mime: None,
                                    payload: new_ics,
                                }),
                            ))
                        }
                        _ => return Err(n),
                    };
                    Ok(prop)
                }
            })
            .boxed()
    }

    fn put<'a>(
        &'a self,
        policy: PutPolicy,
        stream: Content<'a>,
    ) -> BoxFuture<'a, std::result::Result<Etag, std::io::Error>> {
        async {
            let existing_etag = self
                .etag()
                .await
                .ok_or(std::io::Error::new(std::io::ErrorKind::Other, "Etag error"))?;
            match policy {
                PutPolicy::CreateOnly => {
                    return Err(std::io::Error::from(std::io::ErrorKind::AlreadyExists))
                }
                PutPolicy::ReplaceEtag(etag) if etag != existing_etag.as_str() => {
                    return Err(std::io::Error::from(std::io::ErrorKind::AlreadyExists))
                }
                _ => (),
            };

            //@FIXME for now, our storage interface does not allow streaming,
            // so we load everything in memory
            let mut evt = Vec::new();
            let mut reader = stream.into_async_read();
            reader
                .read_to_end(&mut evt)
                .await
                .or(Err(std::io::Error::from(std::io::ErrorKind::BrokenPipe)))?;
            let (_token, entry) = self
                .col
                .put(self.filename.as_str(), evt.as_ref())
                .await
                .or(Err(std::io::ErrorKind::Interrupted))?;
            self.col
                .opportunistic_sync()
                .await
                .or(Err(std::io::ErrorKind::ConnectionReset))?;
            Ok(entry.2)
        }
        .boxed()
    }

    fn content<'a>(&self) -> Content<'a> {
        //@FIXME for now, our storage interface does not allow streaming,
        // so we load everything in memory
        let calendar = self.col.clone();
        let blob_id = self.blob_id.clone();
        let calblob = async move {
            let raw_ics = calendar
                .get(blob_id)
                .await
                .or(Err(std::io::Error::from(std::io::ErrorKind::Interrupted)))?;

            Ok(hyper::body::Bytes::from(raw_ics))
        };
        futures::stream::once(Box::pin(calblob)).boxed()
    }

    fn content_type(&self) -> &str {
        "text/calendar"
    }

    fn etag(&self) -> BoxFuture<Option<Etag>> {
        let calendar = self.col.clone();

        async move {
            calendar
                .dag()
                .await
                .table
                .get(&self.blob_id)
                .map(|(_, _, etag)| etag.to_string())
        }
        .boxed()
    }

    fn delete(&self) -> BoxFuture<std::result::Result<(), std::io::Error>> {
        let calendar = self.col.clone();
        let blob_id = self.blob_id.clone();

        async move {
            let _token = match calendar.delete(blob_id).await {
                Ok(v) => v,
                Err(e) => {
                    tracing::error!(err=?e, "delete event node");
                    return Err(std::io::Error::from(std::io::ErrorKind::Interrupted));
                }
            };
            calendar
                .opportunistic_sync()
                .await
                .or(Err(std::io::ErrorKind::ConnectionReset))?;
            Ok(())
        }
        .boxed()
    }
    fn diff<'a>(
        &self,
        _sync_token: Option<Token>,
    ) -> BoxFuture<
        'a,
        std::result::Result<(Token, Vec<Box<dyn DavNode>>, Vec<dav::Href>), std::io::Error>,
    > {
        async { Err(std::io::Error::from(std::io::ErrorKind::Unsupported)) }.boxed()
    }

    fn dav_header(&self) -> String {
        "1, access-control".into()
    }
}

#[derive(Clone)]
pub(crate) struct CreateEventNode {
    col: Arc<Calendar>,
    calname: String,
    filename: String,
}
impl DavNode for CreateEventNode {
    fn fetch<'a>(
        &self,
        user: &'a ArcUser,
        path: &'a [&str],
        create: bool,
    ) -> BoxFuture<'a, Result<Box<dyn DavNode>>> {
        if path.len() == 0 {
            let node = Box::new(self.clone()) as Box<dyn DavNode>;
            return async { Ok(node) }.boxed();
        }

        async {
            Err(anyhow!(
                "Not supported: can't create a child on an event node"
            ))
        }
        .boxed()
    }

    fn children<'a>(&self, user: &'a ArcUser) -> BoxFuture<'a, Vec<Box<dyn DavNode>>> {
        async { vec![] }.boxed()
    }

    fn path(&self, user: &ArcUser) -> String {
        format!(
            "/{}/calendar/{}/{}",
            user.username, self.calname, self.filename
        )
    }

    fn supported_properties(&self, user: &ArcUser) -> dav::PropName<All> {
        dav::PropName(vec![])
    }

    fn properties(&self, _user: &ArcUser, prop: dav::PropName<All>) -> PropertyStream<'static> {
        futures::stream::iter(vec![]).boxed()
    }

    fn put<'a>(
        &'a self,
        _policy: PutPolicy,
        stream: Content<'a>,
    ) -> BoxFuture<'a, std::result::Result<Etag, std::io::Error>> {
        //@NOTE: policy might not be needed here: whatever we put, there is no known entries here

        async {
            //@FIXME for now, our storage interface does not allow for streaming
            let mut evt = Vec::new();
            let mut reader = stream.into_async_read();
            reader.read_to_end(&mut evt).await.unwrap();
            let (_token, entry) = self
                .col
                .put(self.filename.as_str(), evt.as_ref())
                .await
                .or(Err(std::io::ErrorKind::Interrupted))?;
            self.col
                .opportunistic_sync()
                .await
                .or(Err(std::io::ErrorKind::ConnectionReset))?;
            Ok(entry.2)
        }
        .boxed()
    }

    fn content<'a>(&self) -> Content<'a> {
        futures::stream::once(futures::future::err(std::io::Error::from(
            std::io::ErrorKind::Unsupported,
        )))
        .boxed()
    }

    fn content_type(&self) -> &str {
        "text/plain"
    }

    fn etag(&self) -> BoxFuture<Option<Etag>> {
        async { None }.boxed()
    }

    fn delete(&self) -> BoxFuture<std::result::Result<(), std::io::Error>> {
        // Nothing to delete
        async { Ok(()) }.boxed()
    }
    fn diff<'a>(
        &self,
        _sync_token: Option<Token>,
    ) -> BoxFuture<
        'a,
        std::result::Result<(Token, Vec<Box<dyn DavNode>>, Vec<dav::Href>), std::io::Error>,
    > {
        async { Err(std::io::Error::from(std::io::ErrorKind::Unsupported)) }.boxed()
    }

    fn dav_header(&self) -> String {
        "1, access-control".into()
    }
}