1use crate::{Id, ValidationError};
14use std::fmt;
15use std::str::FromStr;
16
17#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
38pub struct JmapUri {
39 data_type: String,
40 account_id: Id,
41 object_id: Id,
42}
43
44#[non_exhaustive]
46#[derive(Debug, Clone, PartialEq, Eq)]
47pub enum JmapUriError {
48 NotJmapScheme,
50 ReservedForm,
53 InvalidDataType,
56 InvalidAccountId(Option<ValidationError>),
58 MissingObjectId,
60 InvalidObjectId(ValidationError),
63}
64
65impl fmt::Display for JmapUriError {
66 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
67 match self {
68 Self::NotJmapScheme => f.write_str("URI scheme is not `jmap`"),
69 Self::ReservedForm => {
70 f.write_str("jmap:// URI is a reserved form, not a JMAP object URI")
71 }
72 Self::InvalidDataType => {
73 f.write_str("jmap: URI type is not a lowercased JMAP data type name")
74 }
75 Self::InvalidAccountId(_) => f.write_str("jmap: URI accountId is missing or invalid"),
76 Self::MissingObjectId => f.write_str("jmap: URI has no objectId"),
77 Self::InvalidObjectId(_) => f.write_str("jmap: URI objectId is invalid"),
78 }
79 }
80}
81
82impl std::error::Error for JmapUriError {
83 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
84 match self {
85 Self::InvalidAccountId(Some(e)) | Self::InvalidObjectId(e) => Some(e),
86 _ => None,
87 }
88 }
89}
90
91impl JmapUri {
92 pub fn new(
101 data_type: impl Into<String>,
102 account_id: Id,
103 object_id: Id,
104 ) -> Result<Self, JmapUriError> {
105 let data_type = data_type.into();
106 validate_data_type(&data_type)?;
107 Id::new_validated(account_id.as_ref())
108 .map_err(|e| JmapUriError::InvalidAccountId(Some(e)))?;
109 Id::new_validated(object_id.as_ref()).map_err(JmapUriError::InvalidObjectId)?;
110 Ok(Self {
111 data_type,
112 account_id,
113 object_id,
114 })
115 }
116
117 pub fn data_type(&self) -> &str {
119 &self.data_type
120 }
121
122 pub fn account_id(&self) -> &Id {
124 &self.account_id
125 }
126
127 pub fn object_id(&self) -> &Id {
129 &self.object_id
130 }
131}
132
133fn validate_data_type(s: &str) -> Result<(), JmapUriError> {
134 if !s.is_empty()
137 && s.len() <= 255
138 && s.bytes()
139 .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit())
140 {
141 Ok(())
142 } else {
143 Err(JmapUriError::InvalidDataType)
144 }
145}
146
147impl FromStr for JmapUri {
148 type Err = JmapUriError;
149
150 fn from_str(s: &str) -> Result<Self, Self::Err> {
153 let mut parts = s.splitn(4, ':');
156 let scheme = parts.next().unwrap_or_default();
157 let Some(data_type) = parts.next().filter(|_| scheme.eq_ignore_ascii_case("jmap")) else {
159 return Err(JmapUriError::NotJmapScheme);
160 };
161 if data_type.starts_with("//") {
162 return Err(JmapUriError::ReservedForm);
163 }
164 validate_data_type(data_type)?;
165 let account_id = parts.next().ok_or(JmapUriError::InvalidAccountId(None))?;
166 let account_id =
167 Id::new_validated(account_id).map_err(|e| JmapUriError::InvalidAccountId(Some(e)))?;
168 let object_id = parts.next().ok_or(JmapUriError::MissingObjectId)?;
169 let object_id = Id::new_validated(object_id).map_err(JmapUriError::InvalidObjectId)?;
170 Self::new(data_type, account_id, object_id)
171 }
172}
173
174impl fmt::Display for JmapUri {
175 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
176 write!(
177 f,
178 "jmap:{}:{}:{}",
179 self.data_type, self.account_id, self.object_id
180 )
181 }
182}
183
184impl serde::Serialize for JmapUri {
185 fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
186 serializer.collect_str(self)
187 }
188}
189
190impl<'de> serde::Deserialize<'de> for JmapUri {
191 fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
192 let s = <std::borrow::Cow<'de, str>>::deserialize(deserializer)?;
193 s.parse().map_err(serde::de::Error::custom)
194 }
195}