1pub mod v3 {
6 use std::marker::PhantomData;
17
18 #[cfg(feature = "client")]
19 use ruma_common::api::EmptyBody;
20 use ruma_common::{
21 OwnedUserId,
22 api::{Metadata, auth_scheme::NoAccessToken, error::Error, path_builder::VersionHistory},
23 metadata,
24 profile::{ProfileFieldName, ProfileFieldValue, StaticProfileField},
25 };
26
27 metadata! {
28 method: GET,
29 rate_limited: false,
30 authentication: NoAccessToken,
31 history: {
33 unstable("uk.tcpip.msc4133") => "/_matrix/client/unstable/uk.tcpip.msc4133/profile/{user_id}/{field}",
34 1.0 => "/_matrix/client/r0/profile/{user_id}/{field}",
35 1.1 => "/_matrix/client/v3/profile/{user_id}/{field}",
36 }
37 }
38
39 #[derive(Clone, Debug)]
41 #[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
42 pub struct Request {
43 pub user_id: OwnedUserId,
45
46 pub field: ProfileFieldName,
48 }
49
50 impl Request {
51 pub fn new(user_id: OwnedUserId, field: ProfileFieldName) -> Self {
53 Self { user_id, field }
54 }
55
56 pub fn new_static<F: StaticProfileField>(user_id: OwnedUserId) -> RequestStatic<F> {
58 RequestStatic::new(user_id)
59 }
60 }
61
62 #[cfg(feature = "client")]
63 impl ruma_common::api::OutgoingRequest for Request {
64 type Body = EmptyBody;
65 type EndpointError = Error;
66 type IncomingResponse = Response;
67
68 fn try_into_http_request_inner(
69 self,
70 base_url: &str,
71 considering: std::borrow::Cow<'_, ruma_common::api::SupportedVersions>,
72 ) -> Result<http::Request<EmptyBody>, ruma_common::api::error::IntoHttpError> {
73 use ruma_common::api::path_builder::PathBuilder;
74
75 use crate::profile::field_existed_before_extended_profiles;
76
77 let url = if field_existed_before_extended_profiles(&self.field) {
78 Self::make_endpoint_url(considering, base_url, &[&self.user_id, &self.field], "")?
79 } else {
80 crate::profile::EXTENDED_PROFILE_FIELD_HISTORY.make_endpoint_url(
81 considering,
82 base_url,
83 &[&self.user_id, &self.field],
84 "",
85 )?
86 };
87
88 let http_request =
89 http::Request::builder().method(Self::METHOD).uri(url).body(EmptyBody)?;
90
91 Ok(http_request)
92 }
93 }
94
95 #[cfg(feature = "server")]
96 impl ruma_common::api::IncomingRequest for Request {
97 type EndpointError = Error;
98 type OutgoingResponse = Response;
99
100 fn try_from_http_request<B, S>(
101 request: http::Request<B>,
102 path_args: &[S],
103 ) -> Result<Self, ruma_common::api::error::FromHttpRequestError>
104 where
105 B: AsRef<[u8]>,
106 S: AsRef<str>,
107 {
108 Self::check_request_method(request.method())?;
109
110 let (user_id, field) =
111 serde::Deserialize::deserialize(serde::de::value::SeqDeserializer::<
112 _,
113 serde::de::value::Error,
114 >::new(
115 path_args.iter().map(::std::convert::AsRef::as_ref),
116 ))?;
117
118 Ok(Self { user_id, field })
119 }
120 }
121
122 #[derive(Debug)]
124 #[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
125 pub struct RequestStatic<F: StaticProfileField> {
126 pub user_id: OwnedUserId,
128
129 field: PhantomData<F>,
131 }
132
133 impl<F: StaticProfileField> RequestStatic<F> {
134 pub fn new(user_id: OwnedUserId) -> Self {
136 Self { user_id, field: PhantomData }
137 }
138 }
139
140 impl<F: StaticProfileField> Clone for RequestStatic<F> {
141 fn clone(&self) -> Self {
142 Self { user_id: self.user_id.clone(), field: self.field }
143 }
144 }
145
146 impl<F: StaticProfileField> Metadata for RequestStatic<F> {
147 const METHOD: http::Method = Request::METHOD;
148 const RATE_LIMITED: bool = Request::RATE_LIMITED;
149 type Authentication = <Request as Metadata>::Authentication;
150 type PathBuilder = <Request as Metadata>::PathBuilder;
151 const PATH_BUILDER: VersionHistory = Request::PATH_BUILDER;
152 }
153
154 #[cfg(feature = "client")]
155 impl<F: StaticProfileField> ruma_common::api::OutgoingRequest for RequestStatic<F> {
156 type Body = EmptyBody;
157 type EndpointError = Error;
158 type IncomingResponse = ResponseStatic<F>;
159
160 fn try_into_http_request_inner(
161 self,
162 base_url: &str,
163 considering: std::borrow::Cow<'_, ruma_common::api::SupportedVersions>,
164 ) -> Result<http::Request<EmptyBody>, ruma_common::api::error::IntoHttpError> {
165 Request::new(self.user_id, F::NAME.into())
166 .try_into_http_request_inner(base_url, considering)
167 }
168 }
169
170 #[derive(Debug, Clone, Default)]
172 #[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
173 pub struct Response {
174 pub value: Option<ProfileFieldValue>,
176 }
177
178 impl Response {
179 pub fn new(value: ProfileFieldValue) -> Self {
181 Self { value: Some(value) }
182 }
183 }
184
185 #[cfg(feature = "client")]
186 impl ruma_common::api::IncomingResponse for Response {
187 type EndpointError = Error;
188
189 fn try_from_http_response<T: AsRef<[u8]>>(
190 response: http::Response<T>,
191 ) -> Result<Self, ruma_common::api::error::FromHttpResponseError<Self::EndpointError>>
192 {
193 use ruma_common::{api::EndpointError, profile::ProfileFieldValueVisitor};
194 use serde::Deserializer;
195
196 if response.status().as_u16() >= 400 {
197 return Err(ruma_common::api::error::FromHttpResponseError::Server(
198 Self::EndpointError::from_http_response(response),
199 ));
200 }
201
202 let mut de = serde_json::Deserializer::from_slice(response.body().as_ref());
203 let value = de.deserialize_map(ProfileFieldValueVisitor::new(None))?;
204 de.end()?;
205
206 Ok(Self { value })
207 }
208 }
209
210 #[cfg(feature = "server")]
211 impl ruma_common::api::OutgoingResponse for Response {
212 fn try_into_http_response<T: Default + bytes::BufMut>(
213 self,
214 ) -> Result<http::Response<T>, ruma_common::api::error::IntoHttpError> {
215 use ruma_common::serde::JsonObject;
216
217 let body = self
218 .value
219 .as_ref()
220 .map(|value| ruma_common::serde::json_to_buf(value))
221 .unwrap_or_else(||
222 ruma_common::serde::json_to_buf(&JsonObject::new()))?;
224
225 Ok(http::Response::builder()
226 .status(http::StatusCode::OK)
227 .header(http::header::CONTENT_TYPE, ruma_common::http_headers::APPLICATION_JSON)
228 .body(body)?)
229 }
230 }
231
232 #[derive(Debug)]
234 #[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
235 pub struct ResponseStatic<F: StaticProfileField> {
236 pub value: Option<F::Value>,
238 }
239
240 impl<F: StaticProfileField> Clone for ResponseStatic<F>
241 where
242 F::Value: Clone,
243 {
244 fn clone(&self) -> Self {
245 Self { value: self.value.clone() }
246 }
247 }
248
249 #[cfg(feature = "client")]
250 impl<F: StaticProfileField> ruma_common::api::IncomingResponse for ResponseStatic<F> {
251 type EndpointError = Error;
252
253 fn try_from_http_response<T: AsRef<[u8]>>(
254 response: http::Response<T>,
255 ) -> Result<Self, ruma_common::api::error::FromHttpResponseError<Self::EndpointError>>
256 {
257 use ruma_common::api::EndpointError;
258 use serde::de::Deserializer;
259
260 use crate::profile::profile_field_serde::StaticProfileFieldVisitor;
261
262 if response.status().as_u16() >= 400 {
263 return Err(ruma_common::api::error::FromHttpResponseError::Server(
264 Self::EndpointError::from_http_response(response),
265 ));
266 }
267
268 let value = serde_json::Deserializer::from_slice(response.into_body().as_ref())
269 .deserialize_map(StaticProfileFieldVisitor(PhantomData::<F>))?;
270
271 Ok(Self { value })
272 }
273 }
274}
275
276#[cfg(all(test, feature = "client"))]
277mod tests_client {
278 use ruma_common::{
279 owned_mxc_uri, owned_user_id,
280 profile::{ProfileFieldName, ProfileFieldValue},
281 };
282 use serde_json::{json, to_vec as to_json_vec};
283
284 use super::v3::{Request, RequestStatic, Response};
285
286 #[test]
287 fn serialize_request() {
288 use std::borrow::Cow;
289
290 use ruma_common::api::{
291 OutgoingRequestExt as _, SupportedVersions, auth_scheme::SendAccessToken,
292 };
293
294 let avatar_url_request =
296 Request::new(owned_user_id!("@alice:localhost"), ProfileFieldName::AvatarUrl);
297
298 let http_request = avatar_url_request
300 .clone()
301 .try_into_http_request::<Vec<u8>>(
302 "http://localhost/",
303 SendAccessToken::None,
304 Cow::Owned(SupportedVersions::from_parts(
305 &["v1.11".to_owned()],
306 &Default::default(),
307 )),
308 )
309 .unwrap();
310 assert_eq!(
311 http_request.uri().path(),
312 "/_matrix/client/v3/profile/@alice:localhost/avatar_url"
313 );
314
315 let http_request = avatar_url_request
317 .try_into_http_request::<Vec<u8>>(
318 "http://localhost/",
319 SendAccessToken::None,
320 Cow::Owned(SupportedVersions::from_parts(
321 &["v1.16".to_owned()],
322 &Default::default(),
323 )),
324 )
325 .unwrap();
326 assert_eq!(
327 http_request.uri().path(),
328 "/_matrix/client/v3/profile/@alice:localhost/avatar_url"
329 );
330
331 let custom_field_request =
333 Request::new(owned_user_id!("@alice:localhost"), "dev.ruma.custom_field".into());
334
335 let http_request = custom_field_request
337 .clone()
338 .try_into_http_request::<Vec<u8>>(
339 "http://localhost/",
340 SendAccessToken::None,
341 Cow::Owned(SupportedVersions::from_parts(
342 &["v1.11".to_owned()],
343 &Default::default(),
344 )),
345 )
346 .unwrap();
347 assert_eq!(
348 http_request.uri().path(),
349 "/_matrix/client/unstable/uk.tcpip.msc4133/profile/@alice:localhost/dev.ruma.custom_field"
350 );
351
352 let http_request = custom_field_request
354 .try_into_http_request::<Vec<u8>>(
355 "http://localhost/",
356 SendAccessToken::None,
357 Cow::Owned(SupportedVersions::from_parts(
358 &["v1.16".to_owned()],
359 &Default::default(),
360 )),
361 )
362 .unwrap();
363 assert_eq!(
364 http_request.uri().path(),
365 "/_matrix/client/v3/profile/@alice:localhost/dev.ruma.custom_field"
366 );
367 }
368
369 #[test]
370 fn deserialize_response() {
371 use ruma_common::api::IncomingResponse;
372
373 let body = to_json_vec(&json!({
374 "custom_field": "value",
375 }))
376 .unwrap();
377
378 let response = Response::try_from_http_response(http::Response::new(body)).unwrap();
379 let value = response.value.unwrap();
380 assert_eq!(value.field_name().as_str(), "custom_field");
381 assert_eq!(value.value().as_str().unwrap(), "value");
382
383 let empty_body = to_json_vec(&json!({})).unwrap();
384
385 let response = Response::try_from_http_response(http::Response::new(empty_body)).unwrap();
386 assert!(response.value.is_none());
387 }
388
389 fn get_static_response<R: ruma_common::api::OutgoingRequest>(
392 value: Option<ProfileFieldValue>,
393 ) -> Result<R::IncomingResponse, ruma_common::api::error::FromHttpResponseError<R::EndpointError>>
394 {
395 use ruma_common::api::IncomingResponse;
396
397 let body =
398 value.map(|value| to_json_vec(&value).unwrap()).unwrap_or_else(|| b"{}".to_vec());
399 R::IncomingResponse::try_from_http_response(http::Response::new(body))
400 }
401
402 #[test]
403 fn static_request_and_valid_response() {
404 use crate::profile::AvatarUrl;
405
406 let response = get_static_response::<RequestStatic<AvatarUrl>>(Some(
407 ProfileFieldValue::AvatarUrl(owned_mxc_uri!("mxc://localhost/abcdef")),
408 ))
409 .unwrap();
410 assert_eq!(response.value.unwrap(), "mxc://localhost/abcdef");
411
412 let response = get_static_response::<RequestStatic<AvatarUrl>>(None).unwrap();
413 assert!(response.value.is_none());
414 }
415
416 #[test]
417 fn static_request_and_invalid_response() {
418 use crate::profile::AvatarUrl;
419
420 get_static_response::<RequestStatic<AvatarUrl>>(Some(ProfileFieldValue::DisplayName(
421 "Alice".to_owned(),
422 )))
423 .unwrap_err();
424 }
425}
426
427#[cfg(all(test, feature = "server"))]
428mod tests_server {
429 use ruma_common::{
430 owned_mxc_uri,
431 profile::{ProfileFieldName, ProfileFieldValue},
432 };
433 use serde_json::{Value as JsonValue, from_slice as from_json_slice, json};
434
435 use super::v3::{Request, Response};
436
437 #[test]
438 fn deserialize_request() {
439 use ruma_common::api::IncomingRequest;
440
441 let request = Request::try_from_http_request(
442 http::Request::get(
443 "http://localhost/_matrix/client/v3/profile/@alice:localhost/displayname",
444 )
445 .body(Vec::<u8>::new())
446 .unwrap(),
447 &["@alice:localhost", "displayname"],
448 )
449 .unwrap();
450
451 assert_eq!(request.user_id, "@alice:localhost");
452 assert_eq!(request.field, ProfileFieldName::DisplayName);
453 }
454
455 #[test]
456 fn serialize_response() {
457 use ruma_common::api::OutgoingResponse;
458
459 let response =
460 Response::new(ProfileFieldValue::AvatarUrl(owned_mxc_uri!("mxc://localhost/abcdef")));
461
462 let http_response = response.try_into_http_response::<Vec<u8>>().unwrap();
463
464 assert_eq!(
465 from_json_slice::<JsonValue>(http_response.body().as_ref()).unwrap(),
466 json!({
467 "avatar_url": "mxc://localhost/abcdef",
468 })
469 );
470 }
471}