aboutsummaryrefslogtreecommitdiff
path: root/src/dav/encoder.rs
blob: 9e907dc4c02cefe58867b782512596aac285c817 (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
use std::io::Cursor;

use quick_xml::Error as QError;
use quick_xml::events::{Event, BytesEnd, BytesStart, BytesText};
use quick_xml::writer::{ElementWriter, Writer};
use quick_xml::name::PrefixDeclaration;
use tokio::io::AsyncWrite;
use super::types::*;


//-------------- TRAITS ----------------------

/// Basic encode trait to make a type encodable
pub trait QuickWritable<C: Context> {
    async fn write(&self, xml: &mut Writer<impl AsyncWrite+Unpin>, ctx: C) -> Result<(), QError>; 
}

/// Encoding context
pub trait Context: Extension {
    fn child(&self) -> Self;
    fn create_dav_element(&self, name: &str) -> BytesStart;
    async fn hook_error(&self, err: &Self::Error, xml: &mut Writer<impl AsyncWrite+Unpin>) -> Result<(), QError>;
    async fn hook_property(&self, prop: &Self::Property, xml: &mut Writer<impl AsyncWrite+Unpin>) -> Result<(), QError>;
    async fn hook_propertyrequest(&self, prop: &Self::PropertyRequest, xml: &mut Writer<impl AsyncWrite+Unpin>) -> Result<(), QError>;
    async fn hook_resourcetype(&self, prop: &Self::ResourceType, xml: &mut Writer<impl AsyncWrite+Unpin>) -> Result<(), QError>;
}

/// -------------- NoExtension Encoding Context
impl Context for NoExtension {
    fn child(&self) -> Self {
        Self { root: false }
    }
    fn create_dav_element(&self, name: &str) -> BytesStart {
        let mut start = BytesStart::new(format!("D:{}", name));
        if self.root {
            start.push_attribute(("xmlns:D", "DAV:"));
        }
        start
    }
    async fn hook_error(&self, err: &Disabled, xml: &mut Writer<impl AsyncWrite+Unpin>) -> Result<(), QError> {
        unreachable!();
    }
    async fn hook_property(&self, prop: &Disabled, xml: &mut Writer<impl AsyncWrite+Unpin>) -> Result<(), QError> {
        unreachable!();
    }
    async fn hook_propertyrequest(&self, prop: &Disabled, xml: &mut Writer<impl AsyncWrite+Unpin>) -> Result<(), QError> {
        unreachable!();
    }
    async fn hook_resourcetype(&self, restype: &Disabled, xml: &mut Writer<impl AsyncWrite+Unpin>) -> Result<(), QError> {
        unreachable!();
    }
}


//--------------------- ENCODING --------------------

// --- XML ROOTS

/// PROPFIND REQUEST
impl<C: Context> QuickWritable<C> for PropFind<C> {
    async fn write(&self, xml: &mut Writer<impl AsyncWrite+Unpin>, ctx: C) -> Result<(), QError> {
        let start = ctx.create_dav_element("propfind");
        let end = start.to_end();
        let ctx = ctx.child();

        xml.write_event_async(Event::Start(start.clone())).await?;
        match self {
            Self::PropName => xml.write_event_async(Event::Empty(ctx.create_dav_element("propname"))).await?,
            Self::AllProp(maybe_include) => {
                xml.write_event_async(Event::Empty(ctx.create_dav_element("allprop"))).await?;
                if let Some(include) = maybe_include {
                    include.write(xml, ctx.child()).await?;
                }
            },
            Self::Prop(many_propreq) => {
                let start = ctx.create_dav_element("prop");
                let end = start.to_end();

                xml.write_event_async(Event::Start(start.clone())).await?;
                for propreq in many_propreq.iter() {
                    propreq.write(xml, ctx.child()).await?;
                }
                xml.write_event_async(Event::End(end)).await?;
            },
        }
        xml.write_event_async(Event::End(end)).await
    }
}

/// PROPFIND RESPONSE, PROPPATCH RESPONSE, COPY RESPONSE, MOVE RESPONSE
/// DELETE RESPONSE, 
impl<C: Context> QuickWritable<C> for Multistatus<C> {
    async fn write(&self, xml: &mut Writer<impl AsyncWrite+Unpin>, ctx: C) -> Result<(), QError> {
        let start = ctx.create_dav_element("multistatus");
        let end = start.to_end();

        xml.write_event_async(Event::Start(start.clone())).await?;
        for response in self.responses.iter() {
            response.write(xml, ctx.child()).await?;
        }
        if let Some(description) = &self.responsedescription {
            description.write(xml, ctx.child()).await?;
        }

        xml.write_event_async(Event::End(end)).await?;
        Ok(())
    }
}

/// LOCK REQUEST
impl<C: Context> QuickWritable<C> for LockInfo {
    async fn write(&self, xml: &mut Writer<impl AsyncWrite+Unpin>, ctx: C) -> Result<(), QError> {
        let start = ctx.create_dav_element("lockinfo");
        let end = start.to_end();

        xml.write_event_async(Event::Start(start.clone())).await?;
        self.lockscope.write(xml, ctx.child()).await?;
        self.locktype.write(xml, ctx.child()).await?;
        if let Some(owner) = &self.owner {
            owner.write(xml, ctx.child()).await?;
        }
        xml.write_event_async(Event::End(end)).await
    }
}

/// SOME LOCK RESPONSES
impl<C: Context> QuickWritable<C> for Prop<C> {
    async fn write(&self, xml: &mut Writer<impl AsyncWrite+Unpin>, ctx: C) -> Result<(), QError> {
        let start = ctx.create_dav_element("prop");
        let end = start.to_end();

        xml.write_event_async(Event::Start(start.clone())).await?;
        match self {
            Self::Name(many_names) => {
                for propname in many_names {
                    propname.write(xml, ctx.child()).await?;
                }
            },
            Self::Value(many_values) => {
                for propval in many_values {
                    propval.write(xml, ctx.child()).await?;
                }
            }
        };
        xml.write_event_async(Event::End(end)).await?;

        Ok(())
    }
}

// --- XML inner elements
impl<C: Context> QuickWritable<C> for Href {
    async fn write(&self, xml: &mut Writer<impl AsyncWrite+Unpin>, ctx: C) -> Result<(), QError> {
        let start = ctx.create_dav_element("href");
        let end = start.to_end();

        xml.write_event_async(Event::Start(start.clone())).await?;
        xml.write_event_async(Event::Text(BytesText::new(&self.0))).await?;
        xml.write_event_async(Event::End(end)).await?;

        Ok(())
    }
}

impl<C: Context> QuickWritable<C> for Response<C> {
    async fn write(&self, xml: &mut Writer<impl AsyncWrite+Unpin>, ctx: C) -> Result<(), QError> {
        let start = ctx.create_dav_element("response");
        let end = start.to_end();

        xml.write_event_async(Event::Start(start.clone())).await?;
        self.href.write(xml, ctx.child()).await?; 
        self.status_or_propstat.write(xml, ctx.child()).await?;
        if let Some(error) = &self.error {
            error.write(xml, ctx.child()).await?;
        }
        if let Some(responsedescription) = &self.responsedescription {
            responsedescription.write(xml, ctx.child()).await?;
        }
        if let Some(location) = &self.location {
            location.write(xml, ctx.child()).await?;
        }
        xml.write_event_async(Event::End(end)).await?;

        Ok(())
    }
}

impl<C: Context> QuickWritable<C> for StatusOrPropstat<C> {
    async fn write(&self, xml: &mut Writer<impl AsyncWrite+Unpin>, ctx: C) -> Result<(), QError> {
        match self {
            Self::Status(status) => status.write(xml, ctx.child()).await,
            Self::PropStat(propstat_list) => {
                for propstat in propstat_list.iter() {
                    propstat.write(xml, ctx.child()).await?;
                }

                Ok(())
            }
        }
    }
}

impl<C: Context> QuickWritable<C> for Status {
    async fn write(&self, xml: &mut Writer<impl AsyncWrite+Unpin>, ctx: C) -> Result<(), QError> {
        let start = ctx.create_dav_element("status");
        let end = start.to_end();

        xml.write_event_async(Event::Start(start.clone())).await?;

        let txt = format!("HTTP/1.1 {} {}", self.0.as_str(), self.0.canonical_reason().unwrap_or("No reason"));
        xml.write_event_async(Event::Text(BytesText::new(&txt))).await?;

        xml.write_event_async(Event::End(end)).await?;

        Ok(())
    }
}

impl<C: Context> QuickWritable<C> for ResponseDescription {
    async fn write(&self, xml: &mut Writer<impl AsyncWrite+Unpin>, ctx: C) -> Result<(), QError> {
        let start = ctx.create_dav_element("responsedescription");
        let end = start.to_end();

        xml.write_event_async(Event::Start(start.clone())).await?;
        xml.write_event_async(Event::Text(BytesText::new(&self.0))).await?;
        xml.write_event_async(Event::End(end)).await?;

        Ok(())
    }
}

impl<C: Context> QuickWritable<C> for Location {
    async fn write(&self, xml: &mut Writer<impl AsyncWrite+Unpin>, ctx: C) -> Result<(), QError> {
        let start = ctx.create_dav_element("location");
        let end = start.to_end();

        xml.write_event_async(Event::Start(start.clone())).await?;
        self.0.write(xml, ctx.child()).await?;
        xml.write_event_async(Event::End(end)).await?;

        Ok(())
    }
}

impl<C: Context> QuickWritable<C> for PropStat<C> {
    async fn write(&self, xml: &mut Writer<impl AsyncWrite+Unpin>, ctx: C) -> Result<(), QError> {
        let start = ctx.create_dav_element("propstat");
        let end = start.to_end();

        xml.write_event_async(Event::Start(start.clone())).await?;
        self.prop.write(xml, ctx.child()).await?;
        self.status.write(xml, ctx.child()).await?;
        if let Some(error) = &self.error {
            error.write(xml, ctx.child()).await?;
        }
        if let Some(description) = &self.responsedescription {
            description.write(xml, ctx.child()).await?;
        }
        xml.write_event_async(Event::End(end)).await?;

        Ok(())
    }
}

impl<C: Context> QuickWritable<C> for Property<C> {
    async fn write(&self, xml: &mut Writer<impl AsyncWrite+Unpin>, ctx: C) -> Result<(), QError> {
        use Property::*;
        match self {
            CreationDate(date) => {
                // <D:creationdate>1997-12-01T17:42:21-08:00</D:creationdate>
                let start = ctx.create_dav_element("creationdate");
                let end = start.to_end();

                xml.write_event_async(Event::Start(start.clone())).await?;
                xml.write_event_async(Event::Text(BytesText::new(&date.to_rfc3339()))).await?;
                xml.write_event_async(Event::End(end)).await?;
            },
            DisplayName(name) => {
                // <D:displayname>Example collection</D:displayname>
                let start = ctx.create_dav_element("displayname");
                let end = start.to_end();

                xml.write_event_async(Event::Start(start.clone())).await?;
                xml.write_event_async(Event::Text(BytesText::new(name))).await?;
                xml.write_event_async(Event::End(end)).await?;
            },
            GetContentLanguage(lang) => {
                let start = ctx.create_dav_element("getcontentlanguage");
                let end = start.to_end();

                xml.write_event_async(Event::Start(start.clone())).await?;
                xml.write_event_async(Event::Text(BytesText::new(lang))).await?;
                xml.write_event_async(Event::End(end)).await?;
            },
            GetContentLength(len) => {
                // <D:getcontentlength>4525</D:getcontentlength>
                let start = ctx.create_dav_element("getcontentlength");
                let end = start.to_end();

                xml.write_event_async(Event::Start(start.clone())).await?;
                xml.write_event_async(Event::Text(BytesText::new(&len.to_string()))).await?;
                xml.write_event_async(Event::End(end)).await?;
            },
            GetContentType(ct) => {
                // <D:getcontenttype>text/html</D:getcontenttype>
                let start = ctx.create_dav_element("getcontenttype");
                let end = start.to_end();

                xml.write_event_async(Event::Start(start.clone())).await?;
                xml.write_event_async(Event::Text(BytesText::new(&ct))).await?;
                xml.write_event_async(Event::End(end)).await?;
            },
            GetEtag(et) => {
                // <D:getetag>"zzyzx"</D:getetag>
                let start = ctx.create_dav_element("getetag");
                let end = start.to_end();

                xml.write_event_async(Event::Start(start.clone())).await?;
                xml.write_event_async(Event::Text(BytesText::new(et))).await?;
                xml.write_event_async(Event::End(end)).await?;
            },
            GetLastModified(date) => {
                // <D:getlastmodified>Mon, 12 Jan 1998 09:25:56 GMT</D:getlastmodified>
                let start = ctx.create_dav_element("getlastmodified");
                let end = start.to_end();

                xml.write_event_async(Event::Start(start.clone())).await?;
                xml.write_event_async(Event::Text(BytesText::new(&date.to_rfc2822()))).await?;
                xml.write_event_async(Event::End(end)).await?;
            },
            LockDiscovery(many_locks) => {
                // <D:lockdiscovery><D:activelock> ... </D:activelock></D:lockdiscovery>
                let start = ctx.create_dav_element("lockdiscovery");
                let end = start.to_end();

                xml.write_event_async(Event::Start(start.clone())).await?;
                for lock in many_locks.iter() {
                    lock.write(xml, ctx.child()).await?;
                }
                xml.write_event_async(Event::End(end)).await?;
            },
            ResourceType(many_types) => {
                // <D:resourcetype><D:collection/></D:resourcetype>
                
                // <D:resourcetype/>
                
                // <x:resourcetype xmlns:x="DAV:">
                //   <x:collection/>
                //   <f:search-results xmlns:f="http://www.example.com/ns"/>
                // </x:resourcetype>
    
                let start = ctx.create_dav_element("resourcetype");
                if many_types.is_empty() {
                    xml.write_event_async(Event::Empty(start)).await?;
                } else {
                    let end = start.to_end();
                    xml.write_event_async(Event::Start(start.clone())).await?;
                    for restype in many_types.iter() {
                        restype.write(xml, ctx.child()).await?;
                    }
                    xml.write_event_async(Event::End(end)).await?;
                }
            },
            SupportedLock(many_entries) => {
                // <D:supportedlock/>

                //  <D:supportedlock> <D:lockentry> ... </D:lockentry> </D:supportedlock>

                let start = ctx.create_dav_element("supportedlock");
                if many_entries.is_empty() {
                    xml.write_event_async(Event::Empty(start)).await?;
                } else {
                    let end = start.to_end();
                    xml.write_event_async(Event::Start(start.clone())).await?;
                    for entry in many_entries.iter() {
                        entry.write(xml, ctx.child()).await?;
                    }
                    xml.write_event_async(Event::End(end)).await?;
                }
            },
            Extension(inner) => {
                ctx.hook_property(inner, xml).await?;
            },
        };
        Ok(())
    }
}

impl<C: Context> QuickWritable<C> for ResourceType<C> {
    async fn write(&self, xml: &mut Writer<impl AsyncWrite+Unpin>, ctx: C) -> Result<(), QError> {
        match self {
            Self::Collection => xml.write_event_async(Event::Empty(ctx.create_dav_element("collection"))).await,
            Self::Extension(inner) => ctx.hook_resourcetype(inner, xml).await,
        }
    }
}

impl<C: Context> QuickWritable<C> for Include<C> {
    async fn write(&self, xml: &mut Writer<impl AsyncWrite+Unpin>, ctx: C) -> Result<(), QError> {
        let start = ctx.create_dav_element("include");
        let end = start.to_end();

        xml.write_event_async(Event::Start(start.clone())).await?;  
        for prop in self.0.iter() {
            prop.write(xml, ctx.child()).await?;
        }
        xml.write_event_async(Event::End(end)).await
    }
}

impl<C: Context> QuickWritable<C> for PropertyRequest<C> {
    async fn write(&self, xml: &mut Writer<impl AsyncWrite+Unpin>, ctx: C) -> Result<(), QError> {
        use PropertyRequest::*;
        let mut atom = (async |c| xml.write_event_async(Event::Empty(ctx.create_dav_element(c))).await);

        match self {
            CreationDate => atom("creationdate").await,
            DisplayName => atom("displayname").await,
            GetContentLanguage => atom("getcontentlanguage").await,
            GetContentLength => atom("getcontentlength").await,
            GetContentType => atom("getcontenttype").await,
            GetEtag => atom("getetag").await,
            GetLastModified => atom("getlastmodified").await,
            LockDiscovery => atom("lockdiscovery").await,
            ResourceType => atom("resourcetype").await,
            SupportedLock => atom("supportedlock").await,
            Extension(inner) => ctx.hook_propertyrequest(inner, xml).await,
        }
    }
}

impl<C: Context> QuickWritable<C> for ActiveLock {
    async fn write(&self, xml: &mut Writer<impl AsyncWrite+Unpin>, ctx: C) -> Result<(), QError> {
        // <D:activelock>
        //   <D:locktype><D:write/></D:locktype>
        //   <D:lockscope><D:exclusive/></D:lockscope>
        //   <D:depth>infinity</D:depth>
        //   <D:owner>
        //     <D:href>http://example.org/~ejw/contact.html</D:href>
        //   </D:owner>
        //   <D:timeout>Second-604800</D:timeout>
        //   <D:locktoken>
        //     <D:href>urn:uuid:e71d4fae-5dec-22d6-fea5-00a0c91e6be4</D:href>
        //   </D:locktoken>
        //   <D:lockroot>
        //     <D:href>http://example.com/workspace/webdav/proposal.doc</D:href>
        //   </D:lockroot>
        // </D:activelock>
        let start = ctx.create_dav_element("activelock");
        let end = start.to_end();

        xml.write_event_async(Event::Start(start.clone())).await?;
        self.locktype.write(xml, ctx.child()).await?;
        self.lockscope.write(xml, ctx.child()).await?;
        self.depth.write(xml, ctx.child()).await?;
        if let Some(owner) = &self.owner {
            owner.write(xml, ctx.child()).await?;
        }
        if let Some(timeout) = &self.timeout {
            timeout.write(xml, ctx.child()).await?;
        }
        if let Some(locktoken) = &self.locktoken {
            locktoken.write(xml, ctx.child()).await?;
        }
        self.lockroot.write(xml, ctx.child()).await?;
        xml.write_event_async(Event::End(end)).await?;

        Ok(())
    }
}

impl<C: Context> QuickWritable<C> for LockType {
    async fn write(&self, xml: &mut Writer<impl AsyncWrite+Unpin>, ctx: C) -> Result<(), QError> {
        let start = ctx.create_dav_element("locktype");
        let end = start.to_end();
        let ctx = ctx.child();

        xml.write_event_async(Event::Start(start.clone())).await?;
        match self {
            Self::Write => xml.write_event_async(Event::Empty(ctx.create_dav_element("write"))).await?,
        }; 
        xml.write_event_async(Event::End(end)).await
    }
}

impl<C: Context> QuickWritable<C> for LockScope {
    async fn write(&self, xml: &mut Writer<impl AsyncWrite+Unpin>, ctx: C) -> Result<(), QError> {
        let start = ctx.create_dav_element("lockscope");
        let end = start.to_end();
        let ctx = ctx.child();

        xml.write_event_async(Event::Start(start.clone())).await?;
        match self {
            Self::Exclusive => xml.write_event_async(Event::Empty(ctx.create_dav_element("exclusive"))).await?,
            Self::Shared => xml.write_event_async(Event::Empty(ctx.create_dav_element("shared"))).await?,
        }; 
        xml.write_event_async(Event::End(end)).await
    }
}

impl<C: Context> QuickWritable<C> for Owner {
    async fn write(&self, xml: &mut Writer<impl AsyncWrite+Unpin>, ctx: C) -> Result<(), QError> {
        let start = ctx.create_dav_element("owner");
        let end = start.to_end();

        xml.write_event_async(Event::Start(start.clone())).await?;
        if let Some(txt) = &self.txt {
            xml.write_event_async(Event::Text(BytesText::new(&txt))).await?;
        }
        if let Some(href) = &self.url {
            href.write(xml, ctx.child()).await?;
        }
        xml.write_event_async(Event::End(end)).await
    }
}

impl<C: Context> QuickWritable<C> for Depth {
    async fn write(&self, xml: &mut Writer<impl AsyncWrite+Unpin>, ctx: C) -> Result<(), QError> {
        let start = ctx.create_dav_element("depth");
        let end = start.to_end();

        xml.write_event_async(Event::Start(start.clone())).await?;
        match self {
            Self::Zero => xml.write_event_async(Event::Text(BytesText::new("0"))).await?,
            Self::One => xml.write_event_async(Event::Text(BytesText::new("1"))).await?,
            Self::Infinity => xml.write_event_async(Event::Text(BytesText::new("infinity"))).await?,
        };
        xml.write_event_async(Event::End(end)).await
    }
}

impl<C: Context> QuickWritable<C> for Timeout {
    async fn write(&self, xml: &mut Writer<impl AsyncWrite+Unpin>, ctx: C) -> Result<(), QError> {
        let start = ctx.create_dav_element("timeout");
        let end = start.to_end();

        xml.write_event_async(Event::Start(start.clone())).await?;
        match self {
            Self::Seconds(count) => {
                let txt = format!("Second-{}", count);
                xml.write_event_async(Event::Text(BytesText::new(&txt))).await?
            },
            Self::Infinite => xml.write_event_async(Event::Text(BytesText::new("Infinite"))).await?
        };
        xml.write_event_async(Event::End(end)).await
    }
}

impl<C: Context> QuickWritable<C> for LockToken {
    async fn write(&self, xml: &mut Writer<impl AsyncWrite+Unpin>, ctx: C) -> Result<(), QError> {
        let start = ctx.create_dav_element("locktoken");
        let end = start.to_end();

        xml.write_event_async(Event::Start(start.clone())).await?;
        self.0.write(xml, ctx.child()).await?;
        xml.write_event_async(Event::End(end)).await
    }
}

impl<C: Context> QuickWritable<C> for LockRoot {
    async fn write(&self, xml: &mut Writer<impl AsyncWrite+Unpin>, ctx: C) -> Result<(), QError> {
        let start = ctx.create_dav_element("lockroot");
        let end = start.to_end();

        xml.write_event_async(Event::Start(start.clone())).await?;
        self.0.write(xml, ctx.child()).await?;
        xml.write_event_async(Event::End(end)).await
    }
}

impl<C: Context> QuickWritable<C> for LockEntry {
    async fn write(&self, xml: &mut Writer<impl AsyncWrite+Unpin>, ctx: C) -> Result<(), QError> {
        let start = ctx.create_dav_element("lockentry");
        let end = start.to_end();

        xml.write_event_async(Event::Start(start.clone())).await?;
        self.lockscope.write(xml, ctx.child()).await?;
        self.locktype.write(xml, ctx.child()).await?;
        xml.write_event_async(Event::End(end)).await
    }
}

impl<C: Context> QuickWritable<C> for Error<C> {
    async fn write(&self, xml: &mut Writer<impl AsyncWrite+Unpin>, ctx: C) -> Result<(), QError> {
        let start = ctx.create_dav_element("error");
        let end = start.to_end();

        xml.write_event_async(Event::Start(start.clone())).await?;
        for violation in &self.0 {
            violation.write(xml, ctx.child()).await?;
        }
        xml.write_event_async(Event::End(end)).await?;

        Ok(())
    }
}

impl<C: Context> QuickWritable<C> for Violation<C> {
    async fn write(&self, xml: &mut Writer<impl AsyncWrite+Unpin>, ctx: C) -> Result<(), QError> {
        match self {
            Violation::LockTokenMatchesRequestUri => xml.write_event_async(Event::Empty(ctx.create_dav_element("lock-token-matches-request-uri"))).await?, 
            Violation::LockTokenSubmitted(hrefs) => {
                let start = ctx.create_dav_element("lock-token-submitted");
                let end = start.to_end();

                xml.write_event_async(Event::Start(start.clone())).await?;
                for href in hrefs {
                    href.write(xml, ctx.child()).await?;
                }
                xml.write_event_async(Event::End(end)).await?;
            },
            Violation::NoConflictingLock(hrefs) => {
                let start = ctx.create_dav_element("no-conflicting-lock");
                let end = start.to_end();

                xml.write_event_async(Event::Start(start.clone())).await?;
                for href in hrefs {
                    href.write(xml, ctx.child()).await?;
                }
                xml.write_event_async(Event::End(end)).await?;
            },
            Violation::NoExternalEntities => xml.write_event_async(Event::Empty(ctx.create_dav_element("no-external-entities"))).await?,
            Violation::PreservedLiveProperties => xml.write_event_async(Event::Empty(ctx.create_dav_element("preserved-live-properties"))).await?,
            Violation::PropfindFiniteDepth => xml.write_event_async(Event::Empty(ctx.create_dav_element("propfind-finite-depth"))).await?,
            Violation::CannotModifyProtectedProperty => xml.write_event_async(Event::Empty(ctx.create_dav_element("cannot-modify-protected-property"))).await?,
            Violation::Extension(inner) => {
                ctx.hook_error(inner, xml).await?;
            },
        };
        Ok(())
    }
}

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

    /// To run only the unit tests and avoid the behavior ones:
    /// cargo test --bin aerogramme
    
    async fn serialize<C: Context, Q: QuickWritable<C>>(ctx: C, elem: &Q) -> String {
        let mut buffer = Vec::new();
        let mut tokio_buffer = tokio::io::BufWriter::new(&mut buffer);
        let mut writer = Writer::new_with_indent(&mut tokio_buffer, b' ', 4);
        elem.write(&mut writer, ctx).await.expect("xml serialization");
        tokio_buffer.flush().await.expect("tokio buffer flush");
        let got = std::str::from_utf8(buffer.as_slice()).unwrap();

        return got.into()
    }

    #[tokio::test]
    async fn basic_href() {

        let got = serialize(
            NoExtension { root: false },
            &Href("/SOGo/dav/so/".into())
        ).await;
        let expected = "<D:href>/SOGo/dav/so/</D:href>";

        assert_eq!(&got, expected);
    }


    #[tokio::test]
    async fn basic_multistatus() {
        let got = serialize(
            NoExtension { root: true },
            &Multistatus { 
                responses: vec![], 
                responsedescription: Some(ResponseDescription("Hello world".into())) 
            },
        ).await;

        let expected = r#"<D:multistatus xmlns:D="DAV:">
    <D:responsedescription>Hello world</D:responsedescription>
</D:multistatus>"#;

        assert_eq!(&got, expected);
    }


    #[tokio::test]
    async fn rfc_error_delete_locked() {
        let got = serialize(
            NoExtension { root: true },
            &Error(vec![
                Violation::LockTokenSubmitted(vec![
                    Href("/locked/".into())
                ])
            ]),
        ).await;

        let expected = r#"<D:error xmlns:D="DAV:">
    <D:lock-token-submitted>
        <D:href>/locked/</D:href>
    </D:lock-token-submitted>
</D:error>"#;

        assert_eq!(&got, expected);
    }

    #[tokio::test]
    async fn rfc_propname_req() {
        let got = serialize(
            NoExtension { root: true },
            &PropFind::PropName,
        ).await;

        let expected = r#"<D:propfind xmlns:D="DAV:">
    <D:propname/>
</D:propfind>"#;

        assert_eq!(&got, expected);
    }

    #[tokio::test]
    async fn rfc_propname_res() {
        let got = serialize(
            NoExtension { root: true },
            &Multistatus {
                responses: vec![
                    Response {
                        href: Href("http://www.example.com/container/".into()),
                        status_or_propstat: StatusOrPropstat::PropStat(vec![PropStat {
                            prop: Prop::Name(vec![
                                PropertyRequest::CreationDate,
                                PropertyRequest::DisplayName,
                                PropertyRequest::ResourceType,
                                PropertyRequest::SupportedLock,
                            ]),
                            status: Status(http::status::StatusCode::OK),
                            error: None,
                            responsedescription: None,
                        }]),
                        error: None,
                        responsedescription: None,
                        location: None,
                    },
                    Response {
                        href: Href("http://www.example.com/container/front.html".into()),
                        status_or_propstat: StatusOrPropstat::PropStat(vec![PropStat {
                            prop: Prop::Name(vec![
                                PropertyRequest::CreationDate,
                                PropertyRequest::DisplayName,
                                PropertyRequest::GetContentLength,
                                PropertyRequest::GetContentType,
                                PropertyRequest::GetEtag,
                                PropertyRequest::GetLastModified,
                                PropertyRequest::ResourceType,
                                PropertyRequest::SupportedLock,
                            ]),
                            status: Status(http::status::StatusCode::OK),
                            error: None,
                            responsedescription: None,
                        }]),
                        error: None,
                        responsedescription: None,
                        location: None,
                    },
                ],
                responsedescription: None,
            },
        ).await;

        let expected = r#"<D:multistatus xmlns:D="DAV:">
    <D:response>
        <D:href>http://www.example.com/container/</D:href>
        <D:propstat>
            <D:prop>
                <D:creationdate/>
                <D:displayname/>
                <D:resourcetype/>
                <D:supportedlock/>
            </D:prop>
            <D:status>HTTP/1.1 200 OK</D:status>
        </D:propstat>
    </D:response>
    <D:response>
        <D:href>http://www.example.com/container/front.html</D:href>
        <D:propstat>
            <D:prop>
                <D:creationdate/>
                <D:displayname/>
                <D:getcontentlength/>
                <D:getcontenttype/>
                <D:getetag/>
                <D:getlastmodified/>
                <D:resourcetype/>
                <D:supportedlock/>
            </D:prop>
            <D:status>HTTP/1.1 200 OK</D:status>
        </D:propstat>
    </D:response>
</D:multistatus>"#;


        assert_eq!(&got, expected, "\n---GOT---\n{got}\n---EXP---\n{expected}\n");
    }

    #[tokio::test]
    async fn rfc_allprop_req() {
        let got = serialize(
            NoExtension { root: true },
            &PropFind::AllProp(None),
        ).await;

    let expected = r#"<D:propfind xmlns:D="DAV:">
    <D:allprop/>
</D:propfind>"#;

        assert_eq!(&got, expected, "\n---GOT---\n{got}\n---EXP---\n{expected}\n");
    }

    #[tokio::test]
    async fn rfc_allprop_res() {
        use chrono::{DateTime,FixedOffset,TimeZone};
        let got = serialize(
            NoExtension { root: true },
            &Multistatus {
                responses: vec![
                    Response {
                        href: Href("/container/".into()),
                        status_or_propstat: StatusOrPropstat::PropStat(vec![PropStat {
                            prop: Prop::Value(vec![
                                Property::CreationDate(FixedOffset::west_opt(8 * 3600)
                                                       .unwrap()
                                                       .with_ymd_and_hms(1997, 12, 1, 17, 42, 21)
                                                       .unwrap()),
                                Property::DisplayName("Example collection".into()),
                                Property::ResourceType(vec![ResourceType::Collection]),
                                Property::SupportedLock(vec![
                                    LockEntry {
                                        lockscope: LockScope::Exclusive,
                                        locktype: LockType::Write,
                                    },
                                    LockEntry {
                                        lockscope: LockScope::Shared,
                                        locktype: LockType::Write,
                                    },
                                ]),
                            ]),
                            status: Status(http::status::StatusCode::OK),
                            error: None,
                            responsedescription: None,
                        }]),
                        error: None,
                        responsedescription: None,
                        location: None,
                    },
                    Response {
                        href: Href("/container/front.html".into()),
                        status_or_propstat: StatusOrPropstat::PropStat(vec![PropStat {
                            prop: Prop::Value(vec![
                                Property::CreationDate(FixedOffset::west_opt(8 * 3600)
                                    .unwrap()
                                    .with_ymd_and_hms(1997, 12, 1, 18, 27, 21)
                                    .unwrap()),
                                Property::DisplayName("Example HTML resource".into()),
                                Property::GetContentLength(4525),
                                Property::GetContentType("text/html".into()),
                                Property::GetEtag(r#""zzyzx""#.into()),
                                Property::GetLastModified(FixedOffset::east_opt(0)
                                    .unwrap()
                                    .with_ymd_and_hms(1998, 1, 12, 9, 25, 56)
                                    .unwrap()),
                                Property::ResourceType(vec![]),
                                Property::SupportedLock(vec![
                                    LockEntry {
                                        lockscope: LockScope::Exclusive,
                                        locktype: LockType::Write,
                                    },
                                    LockEntry {
                                        lockscope: LockScope::Shared,
                                        locktype: LockType::Write,
                                    },
                                ]),
                            ]),
                            status: Status(http::status::StatusCode::OK),
                            error: None,
                            responsedescription: None,
                        }]),
                        error: None,
                        responsedescription: None,
                        location: None,
                    },
                ],
                responsedescription: None,
            }
        ).await;

        let expected = r#"<D:multistatus xmlns:D="DAV:">
    <D:response>
        <D:href>/container/</D:href>
        <D:propstat>
            <D:prop>
                <D:creationdate>1997-12-01T17:42:21-08:00</D:creationdate>
                <D:displayname>Example collection</D:displayname>
                <D:resourcetype>
                    <D:collection/>
                </D:resourcetype>
                <D:supportedlock>
                    <D:lockentry>
                        <D:lockscope>
                            <D:exclusive/>
                        </D:lockscope>
                        <D:locktype>
                            <D:write/>
                        </D:locktype>
                    </D:lockentry>
                    <D:lockentry>
                        <D:lockscope>
                            <D:shared/>
                        </D:lockscope>
                        <D:locktype>
                            <D:write/>
                        </D:locktype>
                    </D:lockentry>
                </D:supportedlock>
            </D:prop>
            <D:status>HTTP/1.1 200 OK</D:status>
        </D:propstat>
    </D:response>
    <D:response>
        <D:href>/container/front.html</D:href>
        <D:propstat>
            <D:prop>
                <D:creationdate>1997-12-01T18:27:21-08:00</D:creationdate>
                <D:displayname>Example HTML resource</D:displayname>
                <D:getcontentlength>4525</D:getcontentlength>
                <D:getcontenttype>text/html</D:getcontenttype>
                <D:getetag>&quot;zzyzx&quot;</D:getetag>
                <D:getlastmodified>Mon, 12 Jan 1998 09:25:56 +0000</D:getlastmodified>
                <D:resourcetype/>
                <D:supportedlock>
                    <D:lockentry>
                        <D:lockscope>
                            <D:exclusive/>
                        </D:lockscope>
                        <D:locktype>
                            <D:write/>
                        </D:locktype>
                    </D:lockentry>
                    <D:lockentry>
                        <D:lockscope>
                            <D:shared/>
                        </D:lockscope>
                        <D:locktype>
                            <D:write/>
                        </D:locktype>
                    </D:lockentry>
                </D:supportedlock>
            </D:prop>
            <D:status>HTTP/1.1 200 OK</D:status>
        </D:propstat>
    </D:response>
</D:multistatus>"#;

        assert_eq!(&got, expected, "\n---GOT---\n{got}\n---EXP---\n{expected}\n");
    }


    #[tokio::test]
    async fn rfc_allprop_include() {
        let got = serialize(
            NoExtension { root: true },
            &PropFind::AllProp(Some(Include(vec![
               PropertyRequest::DisplayName,
               PropertyRequest::ResourceType,
            ]))),
        ).await;

        let expected = r#"<D:propfind xmlns:D="DAV:">
    <D:allprop/>
    <D:include>
        <D:displayname/>
        <D:resourcetype/>
    </D:include>
</D:propfind>"#;

        assert_eq!(&got, expected, "\n---GOT---\n{got}\n---EXP---\n{expected}\n");
    }
}