1use std::{fmt::Display, str::FromStr};
4
5#[cfg(feature = "serde")]
6use serde::Deserialize;
7
8#[cfg(feature = "utoipa")]
9use utoipa::ToSchema;
10
11pub mod binary;
12pub mod color;
13pub mod duration;
14pub mod hashes;
15pub mod metadata;
16pub mod time;
17
18pub use color::Color;
19pub use time::Time;
20
21use super::error::ApiError;
22use super::{ApplicationId, SessionId, UserId};
23use crate::util::is_valid_hostname;
24use crate::v1::routes::{PathParam, PathParamError};
25use crate::v1::types::error::{ApiResult, ErrorCode};
26use crate::v1::types::federation::Hostname;
27use crate::v1::types::{InviteCode, MediaId, MessageId};
28
29#[derive(Debug, Clone)]
32#[cfg_attr(feature = "serde", derive(Deserialize), serde(untagged))]
33#[cfg_attr(feature = "utoipa", derive(ToSchema))]
34pub enum UserIdReq {
35 #[cfg_attr(feature = "serde", serde(deserialize_with = "const_self"))]
36 UserSelf,
37
38 RemoteUser(UserId, Hostname),
40
41 UserId(UserId),
42}
43
44#[derive(Debug, Clone)]
51#[cfg_attr(feature = "serde", derive(Deserialize), serde(untagged))]
52#[cfg_attr(feature = "utoipa", derive(ToSchema))]
53pub enum MediaIdReq {
54 MediaRemote(MediaId, Hostname),
55 MediaId(MediaId),
56}
57
58#[derive(Debug, Clone, Deserialize, ToSchema)]
59#[cfg_attr(feature = "serde", serde(untagged))]
60pub enum ApplicationIdReq {
61 #[cfg_attr(feature = "serde", serde(deserialize_with = "const_self"))]
62 AppSelf,
63 ApplicationId(ApplicationId),
64}
65
66#[derive(Debug, Clone)]
67#[cfg_attr(
68 feature = "serde",
69 derive(Deserialize, serde::Serialize),
70 serde(untagged)
71)]
72#[cfg_attr(feature = "utoipa", derive(ToSchema))]
73pub enum SessionIdReq {
74 #[cfg_attr(feature = "serde", serde(deserialize_with = "const_self"))]
75 SessionSelf,
76 SessionId(SessionId),
77}
78
79#[derive(Debug, Clone, Deserialize, serde::Serialize)]
80#[cfg_attr(feature = "serde", serde(untagged))]
81#[cfg_attr(feature = "utoipa", derive(ToSchema))]
82pub enum InviteCodeReq {
83 Remote(InviteCode, Hostname),
84 Local(InviteCode),
85}
86
87impl Display for InviteCodeReq {
88 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
89 match self {
90 InviteCodeReq::Remote(code, host) => write!(f, "{code}:{host}"),
91 InviteCodeReq::Local(code) => write!(f, "{code}"),
92 }
93 }
94}
95
96impl FromStr for InviteCodeReq {
97 type Err = String;
98
99 fn from_str(s: &str) -> Result<Self, Self::Err> {
100 if let Some((code_str, host_str)) = s.split_once(':') {
101 if !is_valid_hostname(host_str) {
102 return Err(format!("invalid hostname: {}", host_str));
103 }
104 Ok(InviteCodeReq::Remote(
105 InviteCode(code_str.to_string()),
106 Hostname(host_str.to_string()),
107 ))
108 } else {
109 Ok(InviteCodeReq::Local(InviteCode(s.to_string())))
110 }
111 }
112}
113
114impl Display for SessionIdReq {
115 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
116 match self {
117 SessionIdReq::SessionSelf => write!(f, "@self"),
118 SessionIdReq::SessionId(id) => write!(f, "{}", id),
119 }
120 }
121}
122
123#[derive(Debug, Clone, Deserialize, ToSchema)]
124#[cfg_attr(feature = "serde", serde(untagged))]
125pub enum ServerReq {
126 #[cfg_attr(feature = "serde", serde(deserialize_with = "const_host"))]
128 ServerHost,
129
130 #[cfg_attr(feature = "serde", serde(deserialize_with = "const_client"))]
134 ServerClient,
135
136 #[cfg_attr(feature = "serde", serde(deserialize_with = "deserialize_server_name"))]
138 ServerName(String),
139}
140
141#[derive(Debug, Clone)]
142#[cfg_attr(feature = "serde", derive(Deserialize), serde(untagged))]
143#[cfg_attr(feature = "utoipa", derive(ToSchema))]
144pub enum InteractionMessageReq {
145 #[cfg_attr(feature = "serde", serde(deserialize_with = "const_original"))]
146 MessageOriginal,
147
148 MessageId(MessageId),
149}
150
151#[cfg(feature = "serde")]
152mod serde_helpers {
153 use serde::Deserialize;
154
155 use crate::util::is_valid_hostname;
156
157 pub fn deserialize_server_name<'de, D>(deserializer: D) -> Result<String, D::Error>
158 where
159 D: serde::Deserializer<'de>,
160 {
161 let s = String::deserialize(deserializer)?;
162 if is_valid_hostname(&s) {
163 Ok(s)
164 } else {
165 Err(serde::de::Error::custom(format!("invalid hostname: {}", s)))
166 }
167 }
168
169 pub fn const_self<'de, D>(deserializer: D) -> std::result::Result<(), D::Error>
170 where
171 D: serde::Deserializer<'de>,
172 {
173 #[derive(Deserialize)]
174 enum Helper {
175 #[serde(rename = "@self")]
176 Variant,
177 }
178
179 Helper::deserialize(deserializer).map(|_| ())
180 }
181
182 pub fn const_original<'de, D>(deserializer: D) -> std::result::Result<(), D::Error>
183 where
184 D: serde::Deserializer<'de>,
185 {
186 #[derive(Deserialize)]
187 enum Helper {
188 #[serde(rename = "@original")]
189 Variant,
190 }
191
192 Helper::deserialize(deserializer).map(|_| ())
193 }
194
195 pub fn const_host<'de, D>(deserializer: D) -> std::result::Result<(), D::Error>
196 where
197 D: serde::Deserializer<'de>,
198 {
199 #[derive(Deserialize)]
200 enum Helper {
201 #[serde(rename = "@host")]
202 Variant,
203 }
204
205 Helper::deserialize(deserializer).map(|_| ())
206 }
207
208 pub fn const_client<'de, D>(deserializer: D) -> std::result::Result<(), D::Error>
209 where
210 D: serde::Deserializer<'de>,
211 {
212 #[derive(Deserialize)]
213 enum Helper {
214 #[cfg_attr(feature = "serde", serde(rename = "@client"))]
215 Variant,
216 }
217
218 Helper::deserialize(deserializer).map(|_| ())
219 }
220
221 }
234
235#[cfg(feature = "serde")]
236use serde_helpers::*;
237
238impl UserIdReq {
239 pub fn unwrap_or(self, self_id: UserId) -> UserId {
243 match self {
244 UserIdReq::UserSelf => self_id,
245 UserIdReq::RemoteUser(user_id, _) => user_id,
246 UserIdReq::UserId(user_id) => user_id,
247 }
248 }
249
250 pub fn local_unwrap_or(self, self_id: UserId) -> ApiResult<UserId> {
252 match self {
253 UserIdReq::UserSelf => Ok(self_id),
254 UserIdReq::RemoteUser(_, _) => {
255 Err(ApiError::from_code(ErrorCode::CannotManageRemoteUser))
256 }
257 UserIdReq::UserId(user_id) => Ok(user_id),
258 }
259 }
260}
261
262impl Display for UserIdReq {
263 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
264 match self {
265 UserIdReq::UserSelf => write!(f, "@self"),
266 UserIdReq::RemoteUser(user_id, host) => write!(f, "{user_id}:{host}"),
267 UserIdReq::UserId(user_id) => write!(f, "{user_id}"),
268 }
269 }
270}
271
272impl PathParam for UserIdReq {
273 fn from_path_param(s: &str) -> Result<Self, PathParamError> {
274 if s == "@self" {
275 Ok(UserIdReq::UserSelf)
276 } else if let Some((uuid_str, host_str)) = s.split_once(':') {
277 let user_id = UserId::from_str(uuid_str).map_err(|_| {
278 PathParamError(format!("invalid remote user id uuid: {}", uuid_str))
279 })?;
280 if !is_valid_hostname(host_str) {
281 return Err(PathParamError(format!(
282 "invalid hostname in remote user id: {}",
283 host_str
284 )));
285 }
286 Ok(UserIdReq::RemoteUser(
287 user_id,
288 Hostname(host_str.to_string()),
289 ))
290 } else {
291 UserId::from_str(s)
292 .map(UserIdReq::UserId)
293 .map_err(|_| PathParamError(format!("invalid user id: {}", s)))
294 }
295 }
296}
297
298impl PathParam for ApplicationIdReq {
299 fn from_path_param(s: &str) -> Result<Self, PathParamError> {
300 if s == "@self" {
301 Ok(ApplicationIdReq::AppSelf)
302 } else {
303 ApplicationId::from_str(s)
304 .map(ApplicationIdReq::ApplicationId)
305 .map_err(|_| PathParamError(format!("invalid application id: {}", s)))
306 }
307 }
308}
309
310impl PathParam for SessionIdReq {
311 fn from_path_param(s: &str) -> Result<Self, PathParamError> {
312 if s == "@self" {
313 Ok(SessionIdReq::SessionSelf)
314 } else {
315 SessionId::from_str(s)
316 .map(SessionIdReq::SessionId)
317 .map_err(|_| PathParamError(format!("invalid session id: {}", s)))
318 }
319 }
320}
321
322impl PathParam for ServerReq {
323 fn from_path_param(s: &str) -> Result<Self, PathParamError> {
324 if s == "@host" {
325 Ok(ServerReq::ServerHost)
326 } else if s == "@client" {
327 Ok(ServerReq::ServerClient)
328 } else if is_valid_hostname(s) {
329 Ok(ServerReq::ServerName(s.to_owned()))
330 } else {
331 Err(PathParamError(format!("invalid hostname: {}", s)))
332 }
333 }
334}
335
336impl Display for InteractionMessageReq {
337 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
338 match self {
339 InteractionMessageReq::MessageOriginal => write!(f, "@original"),
340 InteractionMessageReq::MessageId(id) => write!(f, "{id}"),
341 }
342 }
343}
344
345impl PathParam for InteractionMessageReq {
346 fn from_path_param(s: &str) -> Result<Self, PathParamError> {
347 if s == "@original" {
348 Ok(InteractionMessageReq::MessageOriginal)
349 } else {
350 MessageId::from_str(s)
351 .map(InteractionMessageReq::MessageId)
352 .map_err(|_| PathParamError(format!("invalid message id: {}", s)))
353 }
354 }
355}
356
357impl Display for ApplicationIdReq {
358 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
359 match self {
360 ApplicationIdReq::AppSelf => write!(f, "@self"),
361 ApplicationIdReq::ApplicationId(app_id) => write!(f, "{app_id}"),
362 }
363 }
364}
365
366impl Display for ServerReq {
367 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
368 match self {
369 ServerReq::ServerHost => write!(f, "@host"),
370 ServerReq::ServerClient => write!(f, "@client"),
371 ServerReq::ServerName(fqdn) => write!(f, "{fqdn}"),
372 }
373 }
374}
375
376impl From<UserId> for UserIdReq {
377 fn from(id: UserId) -> Self {
378 Self::UserId(id)
379 }
380}
381
382impl Display for MediaIdReq {
383 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
384 match self {
385 MediaIdReq::MediaRemote(media_id, host) => write!(f, "{media_id}:{host}"),
386 MediaIdReq::MediaId(media_id) => write!(f, "{media_id}"),
387 }
388 }
389}
390
391impl PathParam for MediaIdReq {
392 fn from_path_param(s: &str) -> Result<Self, PathParamError> {
393 if let Some((uuid_str, host_str)) = s.split_once(':') {
394 let media_id = MediaId::from_str(uuid_str).map_err(|_| {
395 PathParamError(format!("invalid remote media id uuid: {}", uuid_str))
396 })?;
397 if !is_valid_hostname(host_str) {
398 return Err(PathParamError(format!(
399 "invalid hostname in remote media id: {}",
400 host_str
401 )));
402 }
403 Ok(MediaIdReq::MediaRemote(
404 media_id,
405 Hostname(host_str.to_string()),
406 ))
407 } else {
408 MediaId::from_str(s)
409 .map(MediaIdReq::MediaId)
410 .map_err(|_| PathParamError(format!("invalid media id: {}", s)))
411 }
412 }
413}
414
415impl From<MediaId> for MediaIdReq {
416 fn from(id: MediaId) -> Self {
417 Self::MediaId(id)
418 }
419}
420
421impl From<ApplicationId> for ApplicationIdReq {
422 fn from(id: ApplicationId) -> Self {
423 Self::ApplicationId(id)
424 }
425}
426
427impl From<SessionId> for SessionIdReq {
428 fn from(id: SessionId) -> Self {
429 Self::SessionId(id)
430 }
431}
432
433impl From<MessageId> for InteractionMessageReq {
434 fn from(id: MessageId) -> Self {
435 Self::MessageId(id)
436 }
437}
438
439