From 6a9f2d6c2e24640bd123fcd4f1b9433c1363513f Mon Sep 17 00:00:00 2001 From: veeso Date: Sat, 2 Mar 2024 18:08:17 +0100 Subject: [PATCH] fix: temporarly included webdav-xml into project to fix parsing issues --- CHANGELOG.md | 8 + Cargo.lock | 30 +-- Cargo.toml | 17 +- README.md | 2 +- src/lib.rs | 47 ++-- src/parser.rs | 120 +++++++++- src/webdav_xml/LICENSE-APACHE | 73 +++++++ src/webdav_xml/LICENSE-MIT | 9 + src/webdav_xml/element.rs | 56 +++++ src/webdav_xml/elements/href.rs | 46 ++++ src/webdav_xml/elements/mod.rs | 23 ++ src/webdav_xml/elements/multistatus.rs | 83 +++++++ src/webdav_xml/elements/prop.rs | 75 +++++++ src/webdav_xml/elements/propfind.rs | 99 +++++++++ src/webdav_xml/elements/propstat.rs | 55 +++++ src/webdav_xml/elements/response.rs | 97 +++++++++ .../elements/responsedescription.rs | 37 ++++ src/webdav_xml/elements/status.rs | 60 +++++ src/webdav_xml/error.rs | 36 +++ src/webdav_xml/mod.rs | 102 +++++++++ src/webdav_xml/properties/creationdate.rs | 34 +++ src/webdav_xml/properties/displayname.rs | 32 +++ .../properties/getcontentlanguage.rs | 32 +++ src/webdav_xml/properties/getcontentlength.rs | 30 +++ src/webdav_xml/properties/getcontenttype.rs | 32 +++ src/webdav_xml/properties/getetag.rs | 32 +++ src/webdav_xml/properties/getlastmodified.rs | 32 +++ src/webdav_xml/properties/lockdiscovery.rs | 32 +++ src/webdav_xml/properties/mod.rs | 21 ++ src/webdav_xml/properties/resourcetype.rs | 41 ++++ src/webdav_xml/properties/supportedlock.rs | 32 +++ src/webdav_xml/read.rs | 122 +++++++++++ src/webdav_xml/utils.rs | 52 +++++ src/webdav_xml/value.rs | 206 ++++++++++++++++++ src/webdav_xml/write.rs | 148 +++++++++++++ 35 files changed, 1911 insertions(+), 42 deletions(-) create mode 100644 src/webdav_xml/LICENSE-APACHE create mode 100644 src/webdav_xml/LICENSE-MIT create mode 100644 src/webdav_xml/element.rs create mode 100644 src/webdav_xml/elements/href.rs create mode 100644 src/webdav_xml/elements/mod.rs create mode 100644 src/webdav_xml/elements/multistatus.rs create mode 100644 src/webdav_xml/elements/prop.rs create mode 100644 src/webdav_xml/elements/propfind.rs create mode 100644 src/webdav_xml/elements/propstat.rs create mode 100644 src/webdav_xml/elements/response.rs create mode 100644 src/webdav_xml/elements/responsedescription.rs create mode 100644 src/webdav_xml/elements/status.rs create mode 100644 src/webdav_xml/error.rs create mode 100644 src/webdav_xml/mod.rs create mode 100644 src/webdav_xml/properties/creationdate.rs create mode 100644 src/webdav_xml/properties/displayname.rs create mode 100644 src/webdav_xml/properties/getcontentlanguage.rs create mode 100644 src/webdav_xml/properties/getcontentlength.rs create mode 100644 src/webdav_xml/properties/getcontenttype.rs create mode 100644 src/webdav_xml/properties/getetag.rs create mode 100644 src/webdav_xml/properties/getlastmodified.rs create mode 100644 src/webdav_xml/properties/lockdiscovery.rs create mode 100644 src/webdav_xml/properties/mod.rs create mode 100644 src/webdav_xml/properties/resourcetype.rs create mode 100644 src/webdav_xml/properties/supportedlock.rs create mode 100644 src/webdav_xml/read.rs create mode 100644 src/webdav_xml/utils.rs create mode 100644 src/webdav_xml/value.rs create mode 100644 src/webdav_xml/write.rs diff --git a/CHANGELOG.md b/CHANGELOG.md index 9ffc635..286ba6c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,10 +1,18 @@ # Changelog - [Changelog](#changelog) + - [0.1.1](#011) - [0.1.0](#010) --- +## 0.1.1 + +Released on 02/03/2024 + +- Temporarily included a custom version of webdav-xml inside the project to fix proplist response parser + - Follow up + ## 0.1.0 Released on 02/03/2024 diff --git a/Cargo.lock b/Cargo.lock index 10a8449..e91052c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -903,17 +903,25 @@ dependencies = [ [[package]] name = "remotefs-webdav" -version = "0.1.0" +version = "0.1.1" dependencies = [ + "bytes", + "bytestring", "env_logger", + "http 1.0.0", + "httpdate", + "indexmap", "log", + "mime", + "nonempty", "pretty_assertions", + "quick-xml", "remotefs", "rustydav", "serial_test", "thiserror", + "time 0.3.34", "uuid", - "webdav-xml", ] [[package]] @@ -1475,24 +1483,6 @@ dependencies = [ "wasm-bindgen", ] -[[package]] -name = "webdav-xml" -version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f1328bef48f2c5e3efdf5f42dff6734f495879508ab8cc0d041e33550750a4d1" -dependencies = [ - "bytes", - "bytestring", - "http 1.0.0", - "httpdate", - "indexmap", - "mime", - "nonempty", - "quick-xml", - "thiserror", - "time 0.3.34", -] - [[package]] name = "wildmatch" version = "2.3.0" diff --git a/Cargo.toml b/Cargo.toml index ebe78b5..1d93cf9 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "remotefs-webdav" -version = "0.1.0" +version = "0.1.1" authors = ["Christian Visintin "] edition = "2021" categories = ["network-programming"] @@ -14,11 +14,24 @@ repository = "https://github.com/veeso/remotefs-rs-webdav" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] +bytes = "1.5" log = "0.4" remotefs = "0.2" rustydav = "0.1.3" thiserror = "^1.0" -webdav-xml = "^0.1" +#webdav-xml = "^0.1" +#webdav-xml = { git = "https://github.com/veeso/webdav-rs.git", package = "webdav-xml" } + +# webdav-xml deps +bytestring = "1.3.1" +http = "1" +httpdate = "1.0.3" +indexmap = "2.2.3" +mime = "0.3.17" +nonempty = "0.9.0" +quick-xml = "0.31.0" +time = { version = "0.3.34", features = ["parsing", "formatting"] } + [dev-dependencies] env_logger = "^0.11.0" diff --git a/README.md b/README.md index 8c11c79..43d4a75 100644 --- a/README.md +++ b/README.md @@ -11,7 +11,7 @@

~ Remotefs WebDAV client ~

Developed by @veeso

-

Current version: 0.1.0 (02/03/2024)

+

Current version: 0.1.1 (02/03/2024)

String { + fn url(&self, path: &Path, force_dir: bool) -> String { let mut p = self.url.clone(); p.push_str(&self.path(path).to_string_lossy()); - if !p.ends_with('/') && path.is_dir() { + if !p.ends_with('/') && (path.is_dir() || force_dir) { p.push('/'); } p @@ -103,12 +104,15 @@ impl RemoteFs for WebDAVFs { self.list_dir(&new_dir)?; self.wrkdir = new_dir.to_string_lossy().to_string(); + if !self.wrkdir.ends_with('/') { + self.wrkdir.push('/'); + } debug!("Changed directory to: {}", self.wrkdir); Ok(new_dir) } fn list_dir(&mut self, path: &Path) -> RemoteResult> { - let url = self.url(path); + let url = self.url(path, true); debug!("Listing directory: {}", url); let response = self .client @@ -130,7 +134,7 @@ impl RemoteFs for WebDAVFs { } fn stat(&mut self, path: &Path) -> RemoteResult { - let url = self.url(path); + let url = self.url(path, false); debug!("Listing directory: {}", url); let response = self .client @@ -154,7 +158,7 @@ impl RemoteFs for WebDAVFs { } fn remove_file(&mut self, path: &Path) -> RemoteResult<()> { - let url = self.url(path); + let url = self.url(path, false); debug!("Removing file: {}", url); let response = self .client @@ -165,7 +169,14 @@ impl RemoteFs for WebDAVFs { } fn remove_dir(&mut self, path: &Path) -> RemoteResult<()> { - self.remove_file(path) + let url = self.url(path, true); + debug!("Removing directory: {}", url); + let response = self + .client + .delete(&url) + .map_err(|e| RemoteError::new_ex(RemoteErrorType::ProtocolError, e))?; + + ResponseParser::from(response).status() } fn remove_dir_all(&mut self, path: &Path) -> RemoteResult<()> { @@ -176,7 +187,7 @@ impl RemoteFs for WebDAVFs { if self.stat(path).is_ok() { return Err(RemoteError::new(RemoteErrorType::DirectoryAlreadyExists)); } - let url = self.url(path); + let url = self.url(path, true); // check if dir exists debug!("Creating directory: {}", url); let response = self @@ -196,8 +207,8 @@ impl RemoteFs for WebDAVFs { } fn mov(&mut self, src: &Path, dest: &Path) -> RemoteResult<()> { - let src_url = self.url(src); - let dest_url = self.url(dest); + let src_url = self.url(src, false); + let dest_url = self.url(dest, false); debug!("Moving file: {} to {}", src_url, dest_url); let response = self @@ -230,7 +241,7 @@ impl RemoteFs for WebDAVFs { _metadata: &Metadata, mut reader: Box, ) -> RemoteResult { - let url = self.url(path); + let url = self.url(path, false); debug!("Creating file: {}", url); let mut content = Vec::new(); reader @@ -252,7 +263,7 @@ impl RemoteFs for WebDAVFs { src: &Path, mut dest: Box, ) -> RemoteResult { - let url = self.url(src); + let url = self.url(src, false); debug!("Opening file: {}", url); let mut response = self .client @@ -283,6 +294,7 @@ mod test { use std::io::Cursor; use pretty_assertions::assert_eq; + #[cfg(feature = "with-containers")] use serial_test::serial; use super::*; @@ -299,20 +311,23 @@ mod test { fn test_should_get_url() { let mut client = WebDAVFs::new("user", "password", "http://localhost:3080"); let path = Path::new("a.txt"); - assert_eq!(client.url(path), "http://localhost:3080/a.txt"); + assert_eq!(client.url(path, false), "http://localhost:3080/a.txt"); let path = Path::new("/a.txt"); - assert_eq!(client.url(path), "http://localhost:3080/a.txt"); + assert_eq!(client.url(path, false), "http://localhost:3080/a.txt"); let path = Path::new("/"); - assert_eq!(client.url(path), "http://localhost:3080/"); + assert_eq!(client.url(path, false), "http://localhost:3080/"); client.wrkdir = "/test/".to_string(); let path = Path::new("a.txt"); - assert_eq!(client.url(path), "http://localhost:3080/test/a.txt"); + assert_eq!(client.url(path, false), "http://localhost:3080/test/a.txt"); let path = Path::new("/a.txt"); - assert_eq!(client.url(path), "http://localhost:3080/a.txt"); + assert_eq!(client.url(path, false), "http://localhost:3080/a.txt"); + + let path = Path::new("/gabibbo"); + assert_eq!(client.url(path, true), "http://localhost:3080/gabibbo/"); } #[test] diff --git a/src/parser.rs b/src/parser.rs index 95a5cfe..b139a1e 100644 --- a/src/parser.rs +++ b/src/parser.rs @@ -3,8 +3,9 @@ use std::path::PathBuf; use remotefs::fs::{FileType, Metadata}; use remotefs::{File, RemoteError, RemoteErrorType, RemoteResult}; use rustydav::prelude::Response; -use webdav_xml::elements::{Multistatus, Response as WebDAVResponse}; -use webdav_xml::FromXml; + +use super::webdav_xml::elements::{Multistatus, Response as WebDAVResponse}; +use super::webdav_xml::FromXml; pub struct ResponseParser { response: Response, @@ -45,6 +46,11 @@ impl ResponseParser { "parsing body: {}", String::from_utf8(bytes.to_vec()).unwrap() ); + + Self::parse_propfind(bytes) + } + + fn parse_propfind(bytes: impl Into) -> RemoteResult> { let multistatus = Multistatus::from_xml(bytes) .map_err(|e| RemoteError::new_ex(RemoteErrorType::ProtocolError, e))?; debug!("parsed multistatus: {:?}", multistatus); @@ -83,8 +89,9 @@ impl ResponseParser { debug!("size: {:?}", size.0); metadata.size = size.0; } + let file_name = path.0.to_string(); let path = PathBuf::from(path.0.to_string()); - if path.is_dir() { + if file_name.ends_with('/') || path.is_dir() { debug!("path {} is a directory", path.display()); metadata.file_type = FileType::Directory; } else { @@ -99,3 +106,110 @@ impl ResponseParser { Ok(files) } } + +#[cfg(test)] +mod test { + + use pretty_assertions::assert_eq; + + use super::*; + + #[test] + fn test_should_parse_dir_content() { + let response = r#" + + + + /ciao/ + + + + 2024-03-02T15:44:46Z + Sat, 02 Mar 2024 15:44:46 GMT + "1a-612af5f3d72b2" + + + + + + + + + + + + httpd/unix-directory + + HTTP/1.1 200 OK + + + + /ciao/pippo/ + + + + 2024-03-02T15:40:53Z + Sat, 02 Mar 2024 15:40:53 GMT + "0-612af5150498f" + + + + + + + + + + + + httpd/unix-directory + + HTTP/1.1 200 OK + + + + /ciao/build.rs + + + + 2024-03-02T15:44:46Z + 486 + Sat, 02 Mar 2024 15:44:46 GMT + "1e6-612af5f3d72b2" + F + + + + + + + + + + + + application/rls-services+xml + + HTTP/1.1 200 OK + + + + +"#; + + let files = ResponseParser::parse_propfind(response.as_bytes()).unwrap(); + assert_eq!(files.len(), 3); + let ciao_dir = &files[0]; + assert!(ciao_dir.is_dir()); + assert_eq!(ciao_dir.path, PathBuf::from("/ciao/")); + + let pippo_dir = &files[1]; + assert!(pippo_dir.is_dir()); + assert_eq!(pippo_dir.path, PathBuf::from("/ciao/pippo/")); + + let build_rs = &files[2]; + assert!(build_rs.is_file()); + assert_eq!(build_rs.path, PathBuf::from("/ciao/build.rs")); + assert_eq!(build_rs.metadata.size, 486); + } +} diff --git a/src/webdav_xml/LICENSE-APACHE b/src/webdav_xml/LICENSE-APACHE new file mode 100644 index 0000000..33666dd --- /dev/null +++ b/src/webdav_xml/LICENSE-APACHE @@ -0,0 +1,73 @@ +Apache License +Version 2.0, January 2004 +http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + +"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. + +"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. + +"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. + +"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. + +"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. + +"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. + +"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). + +"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. + +"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." + +"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: + + (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. + + You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + +To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. + +Copyright [yyyy] [name of copyright owner] + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. \ No newline at end of file diff --git a/src/webdav_xml/LICENSE-MIT b/src/webdav_xml/LICENSE-MIT new file mode 100644 index 0000000..3efa2de --- /dev/null +++ b/src/webdav_xml/LICENSE-MIT @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) 2024 d-k-bo + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/src/webdav_xml/element.rs b/src/webdav_xml/element.rs new file mode 100644 index 0000000..3389517 --- /dev/null +++ b/src/webdav_xml/element.rs @@ -0,0 +1,56 @@ +// SPDX-FileCopyrightText: d-k-bo +// +// SPDX-License-Identifier: MIT OR Apache-2.0 + +/// Declares an element's namespace and tag +pub trait Element { + /// XML namespace of the element, e.g. `DAV:` + const NAMESPACE: &'static str; + /// The prefix used to abbreviate the namespace, e.g. `d` + const PREFIX: &'static str; + /// The local name of the element (the name inside the namespace), e.g. + /// `multistatus` + const LOCAL_NAME: &'static str; +} + +pub(crate) trait ElementExt: Element { + fn element_name() -> ElementName + where + S: From<&'static str>, + { + ElementName { + namespace: Some(Self::NAMESPACE.into()), + prefix: Some(Self::PREFIX.into()), + local_name: Self::LOCAL_NAME.into(), + } + } +} + +impl ElementExt for T {} + +#[derive(Clone, Debug)] +pub struct ElementName { + pub namespace: Option, + pub prefix: Option, + pub local_name: S, +} + +impl indexmap::Equivalent> for ElementName<&str> { + fn equivalent(&self, key: &ElementName) -> bool { + self.namespace == key.namespace.as_deref() && self.local_name == &*key.local_name + } +} + +impl PartialEq> for ElementName { + fn eq(&self, other: &Self) -> bool { + self.namespace == other.namespace && self.local_name == other.local_name + } +} + +impl Eq for ElementName {} + +impl std::hash::Hash for ElementName { + fn hash(&self, state: &mut H) { + (&self.namespace, &self.local_name).hash(state) + } +} diff --git a/src/webdav_xml/elements/href.rs b/src/webdav_xml/elements/href.rs new file mode 100644 index 0000000..7bfd84b --- /dev/null +++ b/src/webdav_xml/elements/href.rs @@ -0,0 +1,46 @@ +// SPDX-FileCopyrightText: d-k-bo +// +// SPDX-License-Identifier: MIT OR Apache-2.0 + +use std::str::FromStr; + +use super::super::value::Value; +use super::super::{Element, Error, DAV_NAMESPACE, DAV_PREFIX}; + +/// The `href` XML element as defined in [RFC 4918](http://webdav.org/specs/rfc4918.html#ELEMENT_href). +#[derive(Clone, Debug, PartialEq)] +pub struct Href(pub http::Uri); + +impl Element for Href { + const NAMESPACE: &'static str = DAV_NAMESPACE; + const PREFIX: &'static str = DAV_PREFIX; + const LOCAL_NAME: &'static str = "href"; +} + +impl TryFrom<&Value> for Href { + type Error = Error; + + fn try_from(value: &Value) -> Result { + Ok(Self(value.to_str()?.parse().map_err(Error::other)?)) + } +} + +impl From for Value { + fn from(Href(uri): Href) -> Value { + Value::Text(uri.to_string().into()) + } +} + +impl From for Href { + fn from(uri: http::Uri) -> Self { + Href(uri) + } +} + +impl FromStr for Href { + type Err = ::Err; + + fn from_str(s: &str) -> Result { + http::Uri::from_str(s).map(Href) + } +} diff --git a/src/webdav_xml/elements/mod.rs b/src/webdav_xml/elements/mod.rs new file mode 100644 index 0000000..1b16597 --- /dev/null +++ b/src/webdav_xml/elements/mod.rs @@ -0,0 +1,23 @@ +// SPDX-FileCopyrightText: d-k-bo +// +// SPDX-License-Identifier: MIT OR Apache-2.0 + +//! XML element definitions based on +//! [RFC 4918](http://webdav.org/specs/rfc4918.html#xml.element.definitions). + +mod href; +mod multistatus; +mod prop; +mod propfind; +mod propstat; +mod response; +mod responsedescription; +mod status; + +pub use self::href::Href; +pub use self::multistatus::Multistatus; +pub use self::prop::Properties; +pub use self::propstat::Propstat; +pub use self::response::Response; +pub use self::responsedescription::ResponseDescription; +pub use self::status::Status; diff --git a/src/webdav_xml/elements/multistatus.rs b/src/webdav_xml/elements/multistatus.rs new file mode 100644 index 0000000..6d3b997 --- /dev/null +++ b/src/webdav_xml/elements/multistatus.rs @@ -0,0 +1,83 @@ +// SPDX-FileCopyrightText: d-k-bo +// +// SPDX-License-Identifier: MIT OR Apache-2.0 + +use nonempty::NonEmpty; + +use super::super::elements::response::Response; +use super::super::elements::ResponseDescription; +use super::super::value::ValueMap; +use super::super::{Element, Error, Value, DAV_NAMESPACE, DAV_PREFIX}; + +/// The `multistatus` XML element as defined in [RFC 4918](http://webdav.org/specs/rfc4918.html#ELEMENT_multistatus). +#[derive(Clone, Debug, Default, PartialEq)] +pub struct Multistatus { + pub response: Vec, + pub responsedescription: Option, +} + +impl Element for Multistatus { + const NAMESPACE: &'static str = DAV_NAMESPACE; + const PREFIX: &'static str = DAV_PREFIX; + const LOCAL_NAME: &'static str = "multistatus"; +} + +impl TryFrom<&Value> for Multistatus { + type Error = Error; + + fn try_from(value: &Value) -> Result { + let map = value.to_map()?; + + fn iter_response_items( + mut acc: Vec, + value: &Value, + ) -> Result, Error> { + if value.is_list() { + for item in value.to_list()? { + if item.is_list() { + acc = iter_response_items(acc, item)?; + } else { + acc.push(Response::try_from(item)?); + } + } + } else if value.is_map() { + acc.push(Response::try_from(value)?); + } + + Ok(acc) + } + + let mut response = Vec::new(); + for (_, value) in &map.0 { + response.extend(iter_response_items(vec![], value)?); + } + + Ok(Multistatus { + response, + responsedescription: map.get().transpose()?, + }) + } +} + +impl From for Value { + fn from( + Multistatus { + response, + responsedescription, + }: Multistatus, + ) -> Value { + let mut map = ValueMap::new(); + + map.insert::( + match NonEmpty::collect(response.into_iter().map(Value::from)) { + Some(responses) => Value::List(Box::new(responses)), + None => Value::Empty, + }, + ); + if let Some(responsedescription) = responsedescription { + map.insert::(responsedescription.into()) + } + + Value::Map(map) + } +} diff --git a/src/webdav_xml/elements/prop.rs b/src/webdav_xml/elements/prop.rs new file mode 100644 index 0000000..d044340 --- /dev/null +++ b/src/webdav_xml/elements/prop.rs @@ -0,0 +1,75 @@ +// SPDX-FileCopyrightText: d-k-bo +// +// SPDX-License-Identifier: MIT OR Apache-2.0 + +use super::super::element::Element; +use super::super::properties::{ContentLength, CreationDate, LastModified}; +use super::super::value::{Value, ValueMap}; +use super::super::{Error, DAV_NAMESPACE, DAV_PREFIX}; + +/// The `prop` XML element as defined in [RFC 4918](http://webdav.org/specs/rfc4918.html#ELEMENT_prop). +/// +/// This element can contain arbitrary child elements and supports extracting +/// them using [`Properties::get()`]. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct Properties(ValueMap); + +impl Properties { + /// Read a specific property from this `prop` element. + /// + /// Returns + /// - `None` if the property doesn't exist + /// - `Some(None)` if the property exists and is empty + /// - `Some(Some(Ok(_)))` if the property exists and was successfully + /// extracted + /// - `Some(Some(Err(_)))` if the property exists and extraction failed + pub fn get<'v, P>(&'v self) -> Option>> + where + P: Element + TryFrom<&'v Value, Error = Error>, + { + self.0.get_optional() + } +} + +impl Properties { + /// Read the `creationdate` property. + /// + /// See [`Properties::get()`] for an overview of the possible return values. + pub fn creationdate(&self) -> Option>> { + self.get() + } + + /// Read the `getcontentlength` property. + /// + /// See [`Properties::get()`] for an overview of the possible return values. + pub fn getcontentlength(&self) -> Option>> { + self.get() + } + + /// Read the `getlastmodified` property. + /// + /// See [`Properties::get()`] for an overview of the possible return values. + pub fn getlastmodified(&self) -> Option>> { + self.get() + } +} + +impl Element for Properties { + const NAMESPACE: &'static str = DAV_NAMESPACE; + const PREFIX: &'static str = DAV_PREFIX; + const LOCAL_NAME: &'static str = "prop"; +} + +impl TryFrom<&Value> for Properties { + type Error = Error; + + fn try_from(value: &Value) -> Result { + value.to_map().cloned().map(Self) + } +} + +impl From for Value { + fn from(Properties(map): Properties) -> Value { + Value::Map(map) + } +} diff --git a/src/webdav_xml/elements/propfind.rs b/src/webdav_xml/elements/propfind.rs new file mode 100644 index 0000000..e42601f --- /dev/null +++ b/src/webdav_xml/elements/propfind.rs @@ -0,0 +1,99 @@ +// SPDX-FileCopyrightText: d-k-bo +// +// SPDX-License-Identifier: MIT OR Apache-2.0 + +use bytestring::ByteString; + +use super::super::elements::Properties; +use super::super::{Element, Error, Value, DAV_NAMESPACE, DAV_PREFIX}; + +/// The `propfind` XML element as defined in [RFC 4918](http://webdav.org/specs/rfc4918.html#ELEMENT_propfind). +#[derive(Clone, Debug, PartialEq)] +pub enum Propfind { + Propname, + Allprop { include: Option }, + Prop(Properties), +} + +impl Element for Propfind { + const NAMESPACE: &'static str = DAV_NAMESPACE; + const PREFIX: &'static str = DAV_PREFIX; + const LOCAL_NAME: &'static str = "propfind"; +} + +impl TryFrom<&Value> for Propfind { + type Error = Error; + + fn try_from(value: &Value) -> Result { + let map = value.to_map()?; + + match ( + map.get::(), + map.get::(), + map.get::(), + ) { + (Some(_), None, None) => Ok(Propfind::Propname), + (None, Some(_), None) => Ok(Propfind::Allprop { + include: map.get().transpose()?, + }), + (None, None, Some(prop)) => Ok(Propfind::Prop(prop?)), + _ => Err(Error::ConflictingElements( + "`propname`, `allprop` and `include` must not be used at the same time", + )), + } + } +} + +/// The `propname` XML element as defined in [RFC 4918](http://webdav.org/specs/rfc4918.html#ELEMENT_propname). +#[derive(Clone, Debug, PartialEq)] +pub struct Propname; + +impl Element for Propname { + const NAMESPACE: &'static str = DAV_NAMESPACE; + const PREFIX: &'static str = DAV_PREFIX; + const LOCAL_NAME: &'static str = "propname"; +} + +impl TryFrom<&Value> for Propname { + type Error = Error; + + fn try_from(_: &Value) -> Result { + Ok(Propname) + } +} + +/// The `allprop` XML element as defined in [RFC 4918](http://webdav.org/specs/rfc4918.html#ELEMENT_allprop). +#[derive(Clone, Debug, PartialEq)] +pub struct Allprop; + +impl Element for Allprop { + const NAMESPACE: &'static str = DAV_NAMESPACE; + const PREFIX: &'static str = DAV_PREFIX; + const LOCAL_NAME: &'static str = "allprop"; +} + +impl TryFrom<&Value> for Allprop { + type Error = Error; + + fn try_from(_: &Value) -> Result { + Ok(Allprop) + } +} + +/// The `include` XML element as defined in [RFC 4918](http://webdav.org/specs/rfc4918.html#ELEMENT_include). +#[derive(Clone, Debug, PartialEq)] +pub struct Include(Vec); + +impl Element for Include { + const NAMESPACE: &'static str = DAV_NAMESPACE; + const PREFIX: &'static str = DAV_PREFIX; + const LOCAL_NAME: &'static str = "include"; +} + +impl TryFrom<&Value> for Include { + type Error = Error; + + fn try_from(_: &Value) -> Result { + todo!() + } +} diff --git a/src/webdav_xml/elements/propstat.rs b/src/webdav_xml/elements/propstat.rs new file mode 100644 index 0000000..458ebc6 --- /dev/null +++ b/src/webdav_xml/elements/propstat.rs @@ -0,0 +1,55 @@ +// SPDX-FileCopyrightText: d-k-bo +// +// SPDX-License-Identifier: MIT OR Apache-2.0 + +use super::super::elements::{Properties, ResponseDescription, Status}; +use super::super::value::ValueMap; +use super::super::{Element, Error, OptionExt, Value, DAV_NAMESPACE, DAV_PREFIX}; + +/// The `propstat` XML element as defined in [RFC 4918](http://webdav.org/specs/rfc4918.html#ELEMENT_propstat). +#[derive(Clone, Debug, PartialEq)] +pub struct Propstat { + pub prop: Properties, + pub status: Status, + // pub error: Option, + pub responsedescription: Option, +} + +impl Element for Propstat { + const NAMESPACE: &'static str = DAV_NAMESPACE; + const PREFIX: &'static str = DAV_PREFIX; + const LOCAL_NAME: &'static str = "propstat"; +} + +impl TryFrom<&Value> for Propstat { + type Error = Error; + + fn try_from(value: &Value) -> Result { + let map = value.to_map()?; + Ok(Self { + prop: map.get().required::()??, + status: map.get().required::()??, + responsedescription: map.get().transpose()?, + }) + } +} + +impl From for Value { + fn from( + Propstat { + prop, + status, + responsedescription, + }: Propstat, + ) -> Value { + let mut map = ValueMap::new(); + + map.insert::(prop.into()); + map.insert::(status.into()); + if let Some(responsedescription) = responsedescription { + map.insert::(responsedescription.into()) + } + + Value::Map(map) + } +} diff --git a/src/webdav_xml/elements/response.rs b/src/webdav_xml/elements/response.rs new file mode 100644 index 0000000..5433f88 --- /dev/null +++ b/src/webdav_xml/elements/response.rs @@ -0,0 +1,97 @@ +// SPDX-FileCopyrightText: d-k-bo +// +// SPDX-License-Identifier: MIT OR Apache-2.0 + +use nonempty::NonEmpty; + +use super::super::elements::{Href, Propstat, ResponseDescription, Status}; +use super::super::utils::NonEmptyExt; +use super::super::value::ValueMap; +use super::super::{Element, Error, OptionExt, Value, DAV_NAMESPACE, DAV_PREFIX}; + +/// The `response` XML element as defined in [RFC 4918](http://webdav.org/specs/rfc4918.html#ELEMENT_response). +#[derive(Clone, Debug, PartialEq)] +pub enum Response { + Propstat { + href: Href, + propstat: NonEmpty, + // error: Option, + responsedescription: Option, + // location: Option, + }, + Status { + href: NonEmpty, + status: Status, + // error: Option, + responsedescription: Option, + // location: Option, + }, +} + +impl Element for Response { + const NAMESPACE: &'static str = DAV_NAMESPACE; + const PREFIX: &'static str = DAV_PREFIX; + const LOCAL_NAME: &'static str = "response"; +} + +impl TryFrom<&Value> for Response { + type Error = Error; + + fn try_from(value: &Value) -> Result { + let map = value.to_map()?; + + match NonEmpty::try_collect(map.iter_all::())? { + Some(propstat) => Ok(Self::Propstat { + href: map.get().required::()??, + propstat, + responsedescription: map.get().transpose()?, + }), + None => Ok(Self::Status { + href: NonEmpty::try_collect(map.iter_all())?.required::()?, + status: map.get().required::()??, + responsedescription: map.get().transpose()?, + }), + } + } +} + +impl From for Value { + fn from(response: Response) -> Value { + let mut map = ValueMap::new(); + + match response { + Response::Propstat { + href, + propstat, + responsedescription, + } => { + map.insert::(href.into()); + map.insert::(Value::List(Box::new( + NonEmpty::collect(propstat.into_iter().map(Value::from)).expect( + "iterator is created from a `NonEmpty` and is guaranteed to be nonempty", + ), + ))); + if let Some(responsedescription) = responsedescription { + map.insert::(responsedescription.into()) + } + } + Response::Status { + href, + status, + responsedescription, + } => { + map.insert::(Value::List(Box::new( + NonEmpty::collect(href.into_iter().map(Value::from)).expect( + "iterator is created from a `NonEmpty` and is guaranteed to be nonempty", + ), + ))); + map.insert::(status.into()); + if let Some(responsedescription) = responsedescription { + map.insert::(responsedescription.into()) + } + } + } + + Value::Map(map) + } +} diff --git a/src/webdav_xml/elements/responsedescription.rs b/src/webdav_xml/elements/responsedescription.rs new file mode 100644 index 0000000..5b2f557 --- /dev/null +++ b/src/webdav_xml/elements/responsedescription.rs @@ -0,0 +1,37 @@ +// SPDX-FileCopyrightText: d-k-bo +// +// SPDX-License-Identifier: MIT OR Apache-2.0 + +use bytestring::ByteString; + +use super::super::{Element, Error, Value, DAV_NAMESPACE, DAV_PREFIX}; + +/// The `responsedescription` XML element as defined in [RFC 4918](http://webdav.org/specs/rfc4918.html#ELEMENT_responsedescription). +#[derive(Clone, Debug, PartialEq)] +pub struct ResponseDescription(pub ByteString); + +impl Element for ResponseDescription { + const NAMESPACE: &'static str = DAV_NAMESPACE; + const PREFIX: &'static str = DAV_PREFIX; + const LOCAL_NAME: &'static str = "responsedescription"; +} + +impl TryFrom<&Value> for ResponseDescription { + type Error = Error; + + fn try_from(value: &Value) -> Result { + Ok(Self(value.to_str()?.to_owned())) + } +} + +impl From for Value { + fn from(ResponseDescription(s): ResponseDescription) -> Value { + Value::Text(s) + } +} + +impl> From for ResponseDescription { + fn from(s: S) -> Self { + ResponseDescription(s.into()) + } +} diff --git a/src/webdav_xml/elements/status.rs b/src/webdav_xml/elements/status.rs new file mode 100644 index 0000000..39a1992 --- /dev/null +++ b/src/webdav_xml/elements/status.rs @@ -0,0 +1,60 @@ +// SPDX-FileCopyrightText: d-k-bo +// +// SPDX-License-Identifier: MIT OR Apache-2.0 + +use std::fmt::Display; +use std::str::FromStr; + +use super::super::{Element, Error, Value, DAV_NAMESPACE, DAV_PREFIX}; + +/// The `status` XML element as defined in [RFC 4918](http://webdav.org/specs/rfc4918.html#ELEMENT_status). +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Status(pub http::StatusCode); + +impl Element for Status { + const NAMESPACE: &'static str = DAV_NAMESPACE; + const PREFIX: &'static str = DAV_PREFIX; + const LOCAL_NAME: &'static str = "status"; +} + +impl From for Status { + fn from(code: http::StatusCode) -> Self { + Self(code) + } +} + +impl FromStr for Status { + type Err = InvalidStatus; + + fn from_str(s: &str) -> Result { + let mut parts = s.split(' '); + parts.next().ok_or_else(|| InvalidStatus(s.into()))?; + let status_code = parts + .next() + .and_then(|code| code.parse().ok()) + .ok_or_else(|| InvalidStatus(s.into()))?; + Ok(Self(status_code)) + } +} + +impl Display for Status { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_fmt(format_args!("HTTP/1.1 {}", self.0)) + } +} +impl TryFrom<&Value> for Status { + type Error = Error; + + fn try_from(value: &Value) -> Result { + value.to_str()?.parse().map_err(Error::other) + } +} +impl From for Value { + fn from(status: Status) -> Value { + status.to_string().into() + } +} + +#[derive(Debug, thiserror::Error)] +#[error("invalid status: {0}")] +pub struct InvalidStatus(String); diff --git a/src/webdav_xml/error.rs b/src/webdav_xml/error.rs new file mode 100644 index 0000000..8daaaad --- /dev/null +++ b/src/webdav_xml/error.rs @@ -0,0 +1,36 @@ +// SPDX-FileCopyrightText: d-k-bo +// +// SPDX-License-Identifier: MIT OR Apache-2.0 + +use bytes::Bytes; + +/// Alias for the result type that is used in this crate. +pub type Result = std::result::Result; + +/// Error type to wrap all errors that might occur when (de)serializing. +#[derive(Debug, thiserror::Error)] +#[non_exhaustive] +pub enum Error { + #[error("unexpected value type: {0}")] + InvalidValueType(&'static str), + #[error("missing `{0}` element")] + MissingElement(&'static str), + #[error("conflicting elements: {0}")] + ConflictingElements(&'static str), + #[error("invalid namespace declaration: {0:?}")] + InvalidNamespace(Bytes), + #[error(transparent)] + Xml(#[from] quick_xml::Error), + #[error("unexpected tag")] + UnexpectedTag, + #[error(transparent)] + Utf8(#[from] std::str::Utf8Error), + #[error(transparent)] + Other(#[from] Box), +} + +impl Error { + pub fn other(e: impl Into>) -> Self { + Self::Other(e.into()) + } +} diff --git a/src/webdav_xml/mod.rs b/src/webdav_xml/mod.rs new file mode 100644 index 0000000..63a1215 --- /dev/null +++ b/src/webdav_xml/mod.rs @@ -0,0 +1,102 @@ +// SPDX-FileCopyrightText: d-k-bo +// +// SPDX-License-Identifier: MIT OR Apache-2.0 + +#![allow(rustdoc::redundant_explicit_links)] + +//! Definitions and (de)serialization for WebDAV XML elements as defined +//! in [RFC 4918](http://webdav.org/specs/rfc4918.html#xml.element.definitions). +//! +//! Since WebDAV uses XML namespaces and supports custom elements in the +//! `` element, we can't rely on e. g. `serde` to (de)serialize +//! XML elements. +//! +//! Instead, this crate uses the [`Element`](crate::Element) trait to define an +//! element and [`FromXml`](crate::FromXml)/[`IntoXml`](crate::IntoXml) for +//! (de)serialization. + +mod element; +pub mod elements; +mod error; +pub mod properties; +mod read; +mod utils; +mod value; +mod write; + +use bytes::{BufMut, Bytes}; + +pub use self::element::Element; +pub use self::error::{Error, Result}; +pub use self::value::Value; + +/// The default WebDAV namespace +pub const DAV_NAMESPACE: &str = "DAV:"; +/// The default WebDAV namespace prefix +pub const DAV_PREFIX: &str = "d"; + +/// Performs deserialization from XML. +/// +/// This trait is automatically implemented for any type which implements the +/// `Element + for<'v> TryFrom<&'v Value, Error = Error>` traits. +/// As such, `FromXml` shouldn't be implemented directly: [`Element`] and +/// [`TryFrom<&Value>`] should be implemented instead, and you get the `FromXml` +/// implementation for free. +pub trait FromXml: Sized { + fn from_xml(xml: impl Into) -> Result; +} + +impl FromXml for Value { + fn from_xml(xml: impl Into) -> Result { + read::read_xml(xml) + } +} + +impl FromXml for E +where + E: Element + for<'v> TryFrom<&'v Value, Error = Error>, +{ + fn from_xml(xml: impl Into) -> Result { + Value::from_xml(xml)?.to_map()?.get::().required::()? + } +} + +/// Performs serialization to XML. +/// +/// This trait is automatically implemented for any type which implements the +/// `Element + Into` traits. +/// As such, `IntoXml` shouldn't be implemented directly: [`Element`] and +/// [`Into`] should be implemented instead, and you get the `IntoXml` +/// implementation for free. +pub trait IntoXml: Sized { + fn write_xml(self, writer: impl std::io::Write) -> Result<()>; + fn into_xml(self) -> Result { + let mut xml = bytes::BytesMut::new().writer(); + self.write_xml(&mut xml)?; + Ok(xml.into_inner().freeze()) + } +} + +impl IntoXml for T +where + T: Element + Into, +{ + fn write_xml(self, writer: impl std::io::Write) -> Result<()> { + write::write_xml::(writer, self.into()) + } +} + +/// A type that can't be instantiated. +/// +/// Prevents not yet implemented types from being instantiated. +#[derive(Clone, Debug, PartialEq)] +enum Todo {} + +pub(crate) trait OptionExt { + fn required(self) -> Result; +} +impl OptionExt for Option { + fn required(self) -> Result { + self.ok_or(Error::MissingElement(E::LOCAL_NAME)) + } +} diff --git a/src/webdav_xml/properties/creationdate.rs b/src/webdav_xml/properties/creationdate.rs new file mode 100644 index 0000000..9d2c09b --- /dev/null +++ b/src/webdav_xml/properties/creationdate.rs @@ -0,0 +1,34 @@ +// SPDX-FileCopyrightText: d-k-bo +// +// SPDX-License-Identifier: MIT OR Apache-2.0 + +use time::format_description::well_known::Rfc3339; +use time::OffsetDateTime; + +use super::super::{Element, Error, Value, DAV_NAMESPACE, DAV_PREFIX}; + +/// The `creationdate` property as defined in [RFC 4918](http://webdav.org/specs/rfc4918.html#PROPERTY_creationdate). +#[derive(Clone, Debug, PartialEq)] +pub struct CreationDate(pub OffsetDateTime); + +impl Element for CreationDate { + const NAMESPACE: &'static str = DAV_NAMESPACE; + const PREFIX: &'static str = DAV_PREFIX; + const LOCAL_NAME: &'static str = "creationdate"; +} + +impl TryFrom<&Value> for CreationDate { + type Error = Error; + + fn try_from(value: &Value) -> Result { + OffsetDateTime::parse(value.to_str()?, &Rfc3339) + .map(Self) + .map_err(Error::other) + } +} + +impl From for Value { + fn from(CreationDate(datetime): CreationDate) -> Value { + datetime.format(&Rfc3339).unwrap().into() + } +} diff --git a/src/webdav_xml/properties/displayname.rs b/src/webdav_xml/properties/displayname.rs new file mode 100644 index 0000000..6207b60 --- /dev/null +++ b/src/webdav_xml/properties/displayname.rs @@ -0,0 +1,32 @@ +// SPDX-FileCopyrightText: d-k-bo +// +// SPDX-License-Identifier: MIT OR Apache-2.0 + +use bytestring::ByteString; + +use super::super::{Element, Error, Value, DAV_NAMESPACE, DAV_PREFIX}; + +/// The `displayname` property as defined in +/// [RFC 4918](http://webdav.org/specs/rfc4918.html#PROPERTY_displayname). +#[derive(Clone, Debug, PartialEq)] +pub struct DisplayName(pub ByteString); + +impl Element for DisplayName { + const NAMESPACE: &'static str = DAV_NAMESPACE; + const PREFIX: &'static str = DAV_PREFIX; + const LOCAL_NAME: &'static str = "displayname"; +} + +impl TryFrom<&Value> for DisplayName { + type Error = Error; + + fn try_from(value: &Value) -> Result { + Ok(Self(value.to_str()?.clone())) + } +} + +impl From for Value { + fn from(DisplayName(s): DisplayName) -> Value { + Value::Text(s) + } +} diff --git a/src/webdav_xml/properties/getcontentlanguage.rs b/src/webdav_xml/properties/getcontentlanguage.rs new file mode 100644 index 0000000..f1e21cf --- /dev/null +++ b/src/webdav_xml/properties/getcontentlanguage.rs @@ -0,0 +1,32 @@ +// SPDX-FileCopyrightText: d-k-bo +// +// SPDX-License-Identifier: MIT OR Apache-2.0 + +use bytestring::ByteString; + +use super::super::{Element, Error, Value, DAV_NAMESPACE, DAV_PREFIX}; + +/// The `getcontentlanguage` property as defined in +/// [RFC 4918](http://webdav.org/specs/rfc4918.html#PROPERTY_getcontentlanguage). +#[derive(Clone, Debug, PartialEq)] +pub struct ContentLanguage(pub ByteString); + +impl Element for ContentLanguage { + const NAMESPACE: &'static str = DAV_NAMESPACE; + const PREFIX: &'static str = DAV_PREFIX; + const LOCAL_NAME: &'static str = "getcontentlanguage"; +} + +impl TryFrom<&Value> for ContentLanguage { + type Error = Error; + + fn try_from(value: &Value) -> Result { + Ok(Self(value.to_str()?.clone())) + } +} + +impl From for Value { + fn from(ContentLanguage(s): ContentLanguage) -> Value { + Value::Text(s) + } +} diff --git a/src/webdav_xml/properties/getcontentlength.rs b/src/webdav_xml/properties/getcontentlength.rs new file mode 100644 index 0000000..85f973a --- /dev/null +++ b/src/webdav_xml/properties/getcontentlength.rs @@ -0,0 +1,30 @@ +// SPDX-FileCopyrightText: d-k-bo +// +// SPDX-License-Identifier: MIT OR Apache-2.0 + +use super::super::{Element, Error, Value, DAV_NAMESPACE, DAV_PREFIX}; + +/// The `getcontentlength` property as defined in +/// [RFC 4918](http://webdav.org/specs/rfc4918.html#PROPERTY_getcontentlength). +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct ContentLength(pub u64); + +impl Element for ContentLength { + const NAMESPACE: &'static str = DAV_NAMESPACE; + const PREFIX: &'static str = DAV_PREFIX; + const LOCAL_NAME: &'static str = "getcontentlength"; +} + +impl TryFrom<&Value> for ContentLength { + type Error = Error; + + fn try_from(value: &Value) -> Result { + value.to_str()?.parse().map(Self).map_err(Error::other) + } +} + +impl From for Value { + fn from(ContentLength(len): ContentLength) -> Value { + len.to_string().into() + } +} diff --git a/src/webdav_xml/properties/getcontenttype.rs b/src/webdav_xml/properties/getcontenttype.rs new file mode 100644 index 0000000..f0a7d2d --- /dev/null +++ b/src/webdav_xml/properties/getcontenttype.rs @@ -0,0 +1,32 @@ +// SPDX-FileCopyrightText: d-k-bo +// +// SPDX-License-Identifier: MIT OR Apache-2.0 + +use mime::Mime; + +use super::super::{Element, Error, Value, DAV_NAMESPACE, DAV_PREFIX}; + +/// The `getcontenttype` property as defined in +/// [RFC 4918](http://webdav.org/specs/rfc4918.html#PROPERTY_getcontenttype). +#[derive(Clone, Debug, PartialEq)] +pub struct ContentType(pub Mime); + +impl Element for ContentType { + const NAMESPACE: &'static str = DAV_NAMESPACE; + const PREFIX: &'static str = DAV_PREFIX; + const LOCAL_NAME: &'static str = "getcontenttype"; +} + +impl TryFrom<&Value> for ContentType { + type Error = Error; + + fn try_from(value: &Value) -> Result { + value.to_str()?.parse().map(Self).map_err(Error::other) + } +} + +impl From for Value { + fn from(ContentType(content_type): ContentType) -> Value { + content_type.to_string().into() + } +} diff --git a/src/webdav_xml/properties/getetag.rs b/src/webdav_xml/properties/getetag.rs new file mode 100644 index 0000000..f4976d7 --- /dev/null +++ b/src/webdav_xml/properties/getetag.rs @@ -0,0 +1,32 @@ +// SPDX-FileCopyrightText: d-k-bo +// +// SPDX-License-Identifier: MIT OR Apache-2.0 + +use bytestring::ByteString; + +use super::super::{Element, Error, Value, DAV_NAMESPACE, DAV_PREFIX}; + +/// The `getetag` property as defined in +/// [RFC 4918](http://webdav.org/specs/rfc4918.html#PROPERTY_getetag). +#[derive(Clone, Debug, PartialEq)] +pub struct ETag(pub ByteString); + +impl Element for ETag { + const NAMESPACE: &'static str = DAV_NAMESPACE; + const PREFIX: &'static str = DAV_PREFIX; + const LOCAL_NAME: &'static str = "getetag"; +} + +impl TryFrom<&Value> for ETag { + type Error = Error; + + fn try_from(value: &Value) -> Result { + Ok(Self(value.to_str()?.clone())) + } +} + +impl From for Value { + fn from(ETag(s): ETag) -> Value { + Value::Text(s) + } +} diff --git a/src/webdav_xml/properties/getlastmodified.rs b/src/webdav_xml/properties/getlastmodified.rs new file mode 100644 index 0000000..12a74dc --- /dev/null +++ b/src/webdav_xml/properties/getlastmodified.rs @@ -0,0 +1,32 @@ +// SPDX-FileCopyrightText: d-k-bo +// +// SPDX-License-Identifier: MIT OR Apache-2.0 + +use httpdate::HttpDate; + +use super::super::{Element, Error, Value, DAV_NAMESPACE, DAV_PREFIX}; + +/// The `getlastmodified` property as defined in +/// [RFC 4918](http://webdav.org/specs/rfc4918.html#PROPERTY_getlastmodified). +#[derive(Clone, Debug, PartialEq)] +pub struct LastModified(pub HttpDate); + +impl Element for LastModified { + const NAMESPACE: &'static str = DAV_NAMESPACE; + const PREFIX: &'static str = DAV_PREFIX; + const LOCAL_NAME: &'static str = "getlastmodified"; +} + +impl TryFrom<&Value> for LastModified { + type Error = Error; + + fn try_from(value: &Value) -> Result { + value.to_str()?.parse().map(Self).map_err(Error::other) + } +} + +impl From for Value { + fn from(LastModified(date): LastModified) -> Value { + date.to_string().into() + } +} diff --git a/src/webdav_xml/properties/lockdiscovery.rs b/src/webdav_xml/properties/lockdiscovery.rs new file mode 100644 index 0000000..0c0a734 --- /dev/null +++ b/src/webdav_xml/properties/lockdiscovery.rs @@ -0,0 +1,32 @@ +// SPDX-FileCopyrightText: d-k-bo +// +// SPDX-License-Identifier: MIT OR Apache-2.0 + +use super::super::{Element, Error, Todo, Value, DAV_NAMESPACE, DAV_PREFIX}; + +/// Not yet implemented. +/// +/// The `lockdiscovery` property as defined in +/// [RFC 4918](http://webdav.org/specs/rfc4918.html#PROPERTY_lockdiscovery). +#[derive(Clone, Debug, PartialEq)] +pub struct LockDiscovery(Todo); + +impl Element for LockDiscovery { + const NAMESPACE: &'static str = DAV_NAMESPACE; + const PREFIX: &'static str = DAV_PREFIX; + const LOCAL_NAME: &'static str = "lockdiscovery"; +} + +impl TryFrom<&Value> for LockDiscovery { + type Error = Error; + + fn try_from(_: &Value) -> Result { + todo!() + } +} + +impl From for Value { + fn from(_: LockDiscovery) -> Value { + todo!() + } +} diff --git a/src/webdav_xml/properties/mod.rs b/src/webdav_xml/properties/mod.rs new file mode 100644 index 0000000..00c1743 --- /dev/null +++ b/src/webdav_xml/properties/mod.rs @@ -0,0 +1,21 @@ +// SPDX-FileCopyrightText: d-k-bo +// +// SPDX-License-Identifier: MIT OR Apache-2.0 + +//! XML property definitions based on +//! [RFC 4918](http://webdav.org/specs/rfc4918.html#dav.properties). + +mod creationdate; +mod displayname; +mod getcontentlanguage; +mod getcontentlength; +mod getcontenttype; +mod getetag; +mod getlastmodified; +mod lockdiscovery; +mod resourcetype; +mod supportedlock; + +pub use self::creationdate::CreationDate; +pub use self::getcontentlength::ContentLength; +pub use self::getlastmodified::LastModified; diff --git a/src/webdav_xml/properties/resourcetype.rs b/src/webdav_xml/properties/resourcetype.rs new file mode 100644 index 0000000..b728b11 --- /dev/null +++ b/src/webdav_xml/properties/resourcetype.rs @@ -0,0 +1,41 @@ +// SPDX-FileCopyrightText: d-k-bo +// +// SPDX-License-Identifier: MIT OR Apache-2.0 + +use super::super::value::ValueMap; +use super::super::{Element, Error, Value, DAV_NAMESPACE, DAV_PREFIX}; + +/// The `resourcetype` property as defined in +/// [RFC 4918](http://webdav.org/specs/rfc4918.html#PROPERTY_resourcetype). +#[derive(Clone, Debug, PartialEq)] +pub struct ResourceType(ValueMap); + +impl Element for ResourceType { + const NAMESPACE: &'static str = DAV_NAMESPACE; + const PREFIX: &'static str = DAV_PREFIX; + const LOCAL_NAME: &'static str = "resourcetype"; +} + +impl TryFrom<&Value> for ResourceType { + type Error = Error; + + fn try_from(value: &Value) -> Result { + value.to_map().cloned().map(Self) + } +} + +impl From for Value { + fn from(ResourceType(map): ResourceType) -> Value { + Value::Map(map) + } +} + +/// The `collection` XML element as defined in +/// [RFC 4918](http://webdav.org/specs/rfc4918.html#ELEMENT_collection). +pub struct Collection; + +impl Element for Collection { + const NAMESPACE: &'static str = DAV_NAMESPACE; + const PREFIX: &'static str = DAV_PREFIX; + const LOCAL_NAME: &'static str = "collection"; +} diff --git a/src/webdav_xml/properties/supportedlock.rs b/src/webdav_xml/properties/supportedlock.rs new file mode 100644 index 0000000..0354611 --- /dev/null +++ b/src/webdav_xml/properties/supportedlock.rs @@ -0,0 +1,32 @@ +// SPDX-FileCopyrightText: d-k-bo +// +// SPDX-License-Identifier: MIT OR Apache-2.0 + +use super::super::{Element, Error, Todo, Value, DAV_NAMESPACE, DAV_PREFIX}; + +/// Not yet implemented. +/// +/// The `supportedlock` property as defined in +/// [RFC 4918](http://webdav.org/specs/rfc4918.html#PROPERTY_supportedlock). +#[derive(Clone, Debug, PartialEq)] +pub struct SupportedLock(Todo); + +impl Element for SupportedLock { + const NAMESPACE: &'static str = DAV_NAMESPACE; + const PREFIX: &'static str = DAV_PREFIX; + const LOCAL_NAME: &'static str = "supportedlock"; +} + +impl TryFrom<&Value> for SupportedLock { + type Error = Error; + + fn try_from(_: &Value) -> Result { + todo!() + } +} + +impl From for Value { + fn from(_: SupportedLock) -> Value { + todo!() + } +} diff --git a/src/webdav_xml/read.rs b/src/webdav_xml/read.rs new file mode 100644 index 0000000..59df764 --- /dev/null +++ b/src/webdav_xml/read.rs @@ -0,0 +1,122 @@ +// SPDX-FileCopyrightText: d-k-bo +// +// SPDX-License-Identifier: MIT OR Apache-2.0 + +use std::borrow::Cow; + +use bytestring::ByteString; + +use super::element::ElementName; +use super::utils::BytesExt; +use super::value::ValueMap; +use super::{Error, Result, Value}; + +pub(crate) fn read_xml(xml: impl Into) -> Result { + let xml = xml.into(); + let mut reader = XmlReader::new(&xml); + reader.read_into_value(&xml) +} +struct XmlReader<'x> { + reader: quick_xml::NsReader<&'x [u8]>, + last: Option>, +} + +impl<'x> XmlReader<'x> { + fn new(xml: &'x [u8]) -> Self { + Self { + reader: quick_xml::NsReader::from_reader(xml), + last: None, + } + } + fn last(&self) -> Option<&quick_xml::events::Event<'x>> { + self.last.as_ref() + } + fn read_resolved_event( + &mut self, + ) -> quick_xml::Result<( + quick_xml::name::ResolveResult<'_>, + quick_xml::events::Event<'_>, + )> { + let (resolve_result, event) = self.reader.read_resolved_event()?; + self.last = Some(event.clone()); + Ok((resolve_result, event)) + } + + fn read_into_value(&mut self, xml: &bytes::Bytes) -> Result { + use quick_xml::events::{BytesStart, Event}; + use quick_xml::name::ResolveResult; + + fn key( + xml: &bytes::Bytes, + resolve_result: &ResolveResult, + tag: &BytesStart<'_>, + ) -> Result> { + match resolve_result { + ResolveResult::Bound(ns) => { + if ns.as_ref().is_empty() { + return Err(Error::InvalidNamespace(xml.maybe_slice_ref(ns.as_ref()))); + } + + Ok(ElementName { + namespace: Some(xml.maybe_slice_ref(ns.as_ref()).try_into()?), + prefix: None, + local_name: xml.maybe_slice_ref(tag.local_name().as_ref()).try_into()?, + }) + } + ResolveResult::Unbound | ResolveResult::Unknown(_) => Ok(ElementName { + namespace: None, + prefix: None, + local_name: xml.maybe_slice_ref(tag.name().as_ref()).try_into()?, + }), + } + } + + let mut map = ValueMap::new(); + + loop { + let (resolve_result, event) = self.read_resolved_event()?; + // dbg!(&event); + match event { + Event::Text(text) + if std::str::from_utf8(&text) + .is_ok_and(|s| s.chars().all(char::is_whitespace)) => + { + continue + } + Event::Text(text) => { + // TODO: use ByteString and only reallocate when something was escaped + let value = Value::Text(match text.unescape()? { + Cow::Borrowed(s) => xml + .maybe_slice_ref(s.as_bytes()) + .try_into() + .expect("string is checked by text.unescape() to be valid"), + Cow::Owned(s) => s.into(), + }); + let _ = self.read_resolved_event()?; + return Ok(value); + } + Event::Start(start) => { + let key = key(xml, &resolve_result, &start)?; + let start_name = xml.maybe_slice_ref(start.name().as_ref()); + drop(resolve_result); + drop(start); + + map.insert_raw(key, self.read_into_value(xml)?); + + if !matches!(self.last(), Some(Event::End(end)) if end.name().as_ref() == start_name) + { + return Err(Error::UnexpectedTag); + } + } + Event::Empty(tag) => { + map.insert_raw(key(xml, &resolve_result, &tag)?, Value::Empty); + } + Event::End(_) | Event::Eof => break, + Event::Comment(_) | Event::Decl(_) | Event::PI(_) | Event::DocType(_) => continue, + Event::CData(_) => todo!(), + } + } + + Ok(Value::Map(map)) + } +} diff --git a/src/webdav_xml/utils.rs b/src/webdav_xml/utils.rs new file mode 100644 index 0000000..39d09bf --- /dev/null +++ b/src/webdav_xml/utils.rs @@ -0,0 +1,52 @@ +// SPDX-FileCopyrightText: d-k-bo +// +// SPDX-License-Identifier: MIT OR Apache-2.0 + +use bytes::Bytes; +use nonempty::{nonempty, NonEmpty}; + +pub(crate) trait NonEmptyExt: Sized { + fn try_collect(iter: impl IntoIterator>) -> Result, E>; +} +impl NonEmptyExt for NonEmpty { + /// Since [`NonEmpty`] can't implement [`FromIterator`], this provides + /// something equivalent to [`Iterator::collect::>>()`]. + fn try_collect(iter: impl IntoIterator>) -> Result, E> { + let mut list: Option> = None; + for item in iter { + match &mut list { + Some(list) => list.push(item?), + None => list = Some(nonempty![item?]), + } + } + Ok(list) + } +} + +pub(crate) trait BytesExt { + fn maybe_slice_ref(&self, subset: &[u8]) -> Bytes; +} +impl BytesExt for Bytes { + /// Similar to [`Bytes::slice_ref`], but creates a new allocation if + /// `subset` is out of bounds. + fn maybe_slice_ref(&self, subset: &[u8]) -> Bytes { + if subset.is_empty() { + return Bytes::new(); + } + + let bytes_p = self.as_ptr() as usize; + let bytes_len = self.len(); + + let sub_p = subset.as_ptr() as usize; + let sub_len = subset.len(); + + if sub_p >= bytes_p && sub_p + sub_len <= bytes_p + bytes_len { + let sub_offset = sub_p - bytes_p; + + self.slice(sub_offset..(sub_offset + sub_len)) + } else { + Bytes::copy_from_slice(subset) + } + } +} diff --git a/src/webdav_xml/value.rs b/src/webdav_xml/value.rs new file mode 100644 index 0000000..0bad513 --- /dev/null +++ b/src/webdav_xml/value.rs @@ -0,0 +1,206 @@ +// SPDX-FileCopyrightText: d-k-bo +// +// SPDX-License-Identifier: MIT OR Apache-2.0 + +use bytestring::ByteString; +use indexmap::IndexMap; +use nonempty::{nonempty, NonEmpty}; + +use super::element::{Element, ElementExt, ElementName}; +use super::Error; + +/// Represents the content of an XML element. +/// +/// This data structure is intended to be similar to +/// [`serde_json::Value`](https://docs.rs/serde_json/latest/serde_json/enum.Value.html). +/// Unlike when deserializing JSON, which has explicit arrays, we have to +/// manually group multiple adjacent elements into an array-like structure. +#[derive(Clone, Debug, Default, PartialEq)] +pub enum Value { + /// The element is empty, e.g. `` + #[default] + Empty, + /// The element contains a text node, e.g. `bar` + Text(ByteString), + /// The element contains other elements, e.g. `` + Map(ValueMap), + /// The parent element contains multiple elements of this type, e.g. `` + List(Box>), +} + +impl Value { + pub fn to_str(&self) -> Result<&ByteString, Error> { + match self { + Self::Text(s) => Ok(s), + _ => Err(Error::InvalidValueType("expected text")), + } + } + pub fn to_map(&self) -> Result<&ValueMap, Error> { + match self { + Self::Map(map) => Ok(map), + _ => Err(Error::InvalidValueType("expected a map")), + } + } + + pub fn to_list(&self) -> Result<&NonEmpty, Error> { + match self { + Self::List(list) => Ok(list), + _ => Err(Error::InvalidValueType("expected a list")), + } + } + + pub fn is_list(&self) -> bool { + matches!(self, Self::List(_)) + } + + pub fn is_map(&self) -> bool { + matches!(self, Self::Map(_)) + } +} + +impl From for Value { + fn from(s: String) -> Self { + Value::Text(s.into()) + } +} + +type InnerValueMap = IndexMap, Value>; + +/// A mapping from tag names to [`Value`]s. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct ValueMap(pub(crate) InnerValueMap); + +impl ValueMap { + pub fn new() -> Self { + Self(IndexMap::new()) + } + /// Extract a child element of a specific type. + /// + /// # Returns + /// + /// - `None` if the element doesn't exist + /// - `Some(Ok(_))` if the element exists and was successfully extracted + /// - `Some(Err(_))` if the element exists and extraction failed + pub fn get<'v, E>(&'v self) -> Option> + where + E: Element + TryFrom<&'v Value, Error = Error>, + { + self.0 + .get(&E::element_name::<&'static str>()) + .map(E::try_from) + } + /// Extract a non-empty child element of a specific type. + /// + /// # Returns + /// + /// - `None` if the element doesn't exist + /// - `Some(None)` if the element exists and is empty + /// - `Some(Some(Ok(_)))` if the element exists, is not empty and was + /// successfully extracted + /// - `Some(Some(Err(_)))` if the element exists, is not empty and + /// extraction failed + pub fn get_optional<'v, E>(&'v self) -> Option>> + where + E: Element + TryFrom<&'v Value, Error = Error>, + { + self.0 + .get(&E::element_name::<&'static str>()) + .map(|value| match value { + Value::Empty => None, + v => Some(v.try_into()), + }) + } + /// Insert a child value into the map. + pub fn insert(&mut self, value: Value) { + let key = E::element_name(); + self.insert_raw(key, value) + } +} + +impl ValueMap { + pub(crate) fn iter_all<'v, E>(&'v self) -> impl Iterator> + 'v + where + E: Element + TryFrom<&'v Value, Error = Error> + 'v, + { + enum ElementIter<'a> { + List(nonempty::Iter<'a, Value>), + Single(std::iter::Once<&'a Value>), + Empty, + } + + impl<'a> Iterator for ElementIter<'a> { + type Item = &'a Value; + + fn next(&mut self) -> Option { + match self { + Self::List(inner) => inner.next(), + Self::Single(value) => value.next(), + Self::Empty => None, + } + } + } + + match self.0.get(&E::element_name::<&'static str>()) { + Some(Value::List(list)) => ElementIter::List(list.iter()), + Some(value) => ElementIter::Single(std::iter::once(value)), + None => ElementIter::Empty, + } + .map(E::try_from) + } + // pub(crate) fn iter_all_nonempty<'v, E>(&'v self) -> impl Iterator> + 'v where + // E: Element + TryFrom<&'v Value, Error = Error>, + // { + // self.iter_all() + // .map(|v| v.ok_or(Error::EmptyElement(E::LOCAL_NAME))?) + // } + // pub(crate) fn get_all_nonempty<'v, E>(&'v self) -> + // Result>, Error> where + // E: Element + TryFrom<&'v Value, Error = Error>, + // { + // NonEmpty::try_collect( + // self.iter_all() + // .map(|v| v.ok_or(Error::EmptyElement(E::LOCAL_NAME))?), + // ) + // } + // pub(crate) fn get_all_required<'v, E>(&'v self) -> Result, Error> + // where + // E: Element + TryFrom<&'v Value, Error = Error>, + // { + // NonEmpty::try_collect( + // self.iter_all() + // .map(|v| v.ok_or(Error::EmptyElement(E::LOCAL_NAME))?), + // ) + // .transpose() + // .ok_or(Error::MissingElement(E::LOCAL_NAME))? + // } + pub(crate) fn insert_raw(&mut self, key: ElementName, value: Value) { + match self.0.get_mut(&key) { + Some(old_value) => { + *old_value = Value::List(Box::new(nonempty![std::mem::take(old_value), value])); + } + None => { + self.0.insert(key, value); + } + } + } +} + +impl AsRef for ValueMap { + fn as_ref(&self) -> &InnerValueMap { + &self.0 + } +} + +impl AsMut for ValueMap { + fn as_mut(&mut self) -> &mut InnerValueMap { + &mut self.0 + } +} + +impl From for ValueMap { + fn from(map: InnerValueMap) -> Self { + Self(map) + } +} diff --git a/src/webdav_xml/write.rs b/src/webdav_xml/write.rs new file mode 100644 index 0000000..46a7877 --- /dev/null +++ b/src/webdav_xml/write.rs @@ -0,0 +1,148 @@ +// SPDX-FileCopyrightText: d-k-bo +// +// SPDX-License-Identifier: MIT OR Apache-2.0 + +use std::borrow::Cow; +use std::collections::HashMap; + +use bytestring::ByteString; + +use super::element::{Element, ElementExt, ElementName}; +use super::{Result, Value}; + +pub(crate) fn write_xml(writer: impl std::io::Write, value: Value) -> Result<()> { + let mut writer = XmlWriter { + inner: quick_xml::Writer::new_with_indent(writer, b' ', 2), + namespaces: HashMap::new(), + }; + writer.inner.write_event(quick_xml::events::Event::Decl( + quick_xml::events::BytesDecl::new("1.0", Some("utf-8"), None), + ))?; + + let name = E::element_name(); + writer.resolve_namespaces(&name, &value); + writer.write_toplevel(&name, value) +} + +struct XmlWriter +where + W: std::io::Write, +{ + inner: quick_xml::Writer, + namespaces: HashMap, +} + +impl XmlWriter +where + W: std::io::Write, +{ + fn add_namespace(&mut self, name: &ElementName) { + if let Some(namespace) = &name.namespace { + if !self.namespaces.contains_key(namespace) { + self.namespaces.insert( + namespace.clone(), + name.prefix.as_ref().cloned().unwrap_or_else(|| "NS".into()), + ); + // TODO: handle collisions + } + } + } + fn resolve_namespaces(&mut self, name: &ElementName, value: &Value) { + match value { + Value::Text(_) | Value::Empty => self.add_namespace(name), + Value::List(list) => { + for value in list.as_ref() { + self.resolve_namespaces(name, value); + } + } + Value::Map(map) => { + self.add_namespace(name); + for (name, value) in &map.0 { + self.resolve_namespaces(name, value); + } + } + } + } +} + +impl XmlWriter +where + W: std::io::Write, +{ + fn name<'n>(&self, name: &'n ElementName) -> Cow<'n, str> { + match &name.namespace { + Some(namespace) => Cow::Owned(format!( + "{prefix}:{local_name}", + prefix = self + .namespaces + .get(namespace) + .expect("all namespaces should be resolved in the first pass"), + local_name = name.local_name + )), + None => Cow::Borrowed(&name.local_name), + } + } + fn write_toplevel(&mut self, name: &ElementName, value: Value) -> Result<()> { + use quick_xml::events::attributes::Attribute; + use quick_xml::events::{BytesEnd, BytesStart, Event}; + + let raw_name = self.name(name); + + match value { + Value::Map(map) => { + let mut start = BytesStart::new(&*raw_name); + for (namespace, prefix) in &self.namespaces { + start.push_attribute(Attribute::from(( + &*format!("xmlns:{prefix}"), + &**namespace, + ))); + } + + self.inner.write_event(Event::Start(start))?; + for (tag, value) in map.0 { + self.write_value(&tag, value)?; + } + self.inner + .write_event(Event::End(BytesEnd::new(raw_name)))?; + + Ok(()) + } + _ => unimplemented!(), + } + } + fn write_value(&mut self, name: &ElementName, value: Value) -> Result<()> { + use quick_xml::events::{BytesEnd, BytesStart, BytesText, Event}; + + let raw_name = self.name(name); + + match value { + Value::Empty => { + self.inner + .write_event(Event::Empty(BytesStart::new(raw_name)))?; + } + Value::Text(text) => { + self.inner + .write_event(Event::Start(BytesStart::new(&*raw_name)))?; + self.inner.write_event(Event::Text(BytesText::new(&text)))?; + self.inner + .write_event(Event::End(BytesEnd::new(raw_name)))?; + } + Value::List(list) => { + for value in *list { + self.write_value(name, value)?; + } + } + Value::Map(map) => { + self.inner + .write_event(Event::Start(BytesStart::new(&*raw_name)))?; + for (tag, value) in map.0 { + self.write_value(&tag, value)?; + } + self.inner + .write_event(Event::End(BytesEnd::new(raw_name)))?; + } + } + + Ok(()) + } +}