#![warn(rust_2018_idioms)]
#![deny(missing_copy_implementations, missing_debug_implementations, missing_docs)]
use std::{
convert::{TryFrom, TryInto},
error::Error as StdError,
fmt::{Display, Formatter, Result as FmtResult},
io,
};
use http::{self, Method, StatusCode};
use ruma_identifiers;
use serde_json;
use serde_urlencoded;
#[cfg(feature = "with-ruma-api-macros")]
pub use ruma_api_macros::ruma_api;
#[cfg(feature = "with-ruma-api-macros")]
pub use ruma_api_macros::Outgoing;
#[cfg(feature = "with-ruma-api-macros")]
#[doc(hidden)]
pub mod exports {
pub use http;
pub use percent_encoding;
pub use serde;
pub use serde_json;
pub use serde_urlencoded;
pub use url;
}
pub trait Outgoing {
type Incoming;
}
pub trait Endpoint: Outgoing + TryInto<http::Request<Vec<u8>>, Error = Error>
where
<Self as Outgoing>::Incoming: TryFrom<http::Request<Vec<u8>>, Error = Error>,
<Self::Response as Outgoing>::Incoming: TryFrom<http::Response<Vec<u8>>, Error = Error>,
{
type Response: Outgoing + TryInto<http::Response<Vec<u8>>, Error = Error>;
const METADATA: Metadata;
}
#[derive(Debug)]
pub struct Error(pub(crate) InnerError);
impl Display for Error {
fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
let message = match self.0 {
InnerError::Http(_) => "An error converting to or from `http` types occurred.".into(),
InnerError::Io(_) => "An I/O error occurred.".into(),
InnerError::SerdeJson(_) => "A JSON error occurred.".into(),
InnerError::SerdeUrlEncodedDe(_) => {
"A URL encoding deserialization error occurred.".into()
}
InnerError::SerdeUrlEncodedSer(_) => {
"A URL encoding serialization error occurred.".into()
}
InnerError::RumaIdentifiers(_) => "A ruma-identifiers error occurred.".into(),
InnerError::StatusCode(code) => format!("A HTTP {} error occurred.", code),
};
write!(f, "{}", message)
}
}
impl StdError for Error {}
#[derive(Debug)]
pub(crate) enum InnerError {
Http(http::Error),
Io(io::Error),
SerdeJson(serde_json::Error),
SerdeUrlEncodedDe(serde_urlencoded::de::Error),
SerdeUrlEncodedSer(serde_urlencoded::ser::Error),
RumaIdentifiers(ruma_identifiers::Error),
StatusCode(StatusCode),
}
impl From<http::Error> for Error {
fn from(error: http::Error) -> Self {
Self(InnerError::Http(error))
}
}
impl From<io::Error> for Error {
fn from(error: io::Error) -> Self {
Self(InnerError::Io(error))
}
}
impl From<serde_json::Error> for Error {
fn from(error: serde_json::Error) -> Self {
Self(InnerError::SerdeJson(error))
}
}
impl From<serde_urlencoded::de::Error> for Error {
fn from(error: serde_urlencoded::de::Error) -> Self {
Self(InnerError::SerdeUrlEncodedDe(error))
}
}
impl From<serde_urlencoded::ser::Error> for Error {
fn from(error: serde_urlencoded::ser::Error) -> Self {
Self(InnerError::SerdeUrlEncodedSer(error))
}
}
impl From<ruma_identifiers::Error> for Error {
fn from(error: ruma_identifiers::Error) -> Self {
Self(InnerError::RumaIdentifiers(error))
}
}
impl From<StatusCode> for Error {
fn from(error: StatusCode) -> Self {
Self(InnerError::StatusCode(error))
}
}
#[derive(Clone, Debug)]
pub struct Metadata {
pub description: &'static str,
pub method: Method,
pub name: &'static str,
pub path: &'static str,
pub rate_limited: bool,
pub requires_authentication: bool,
}
#[cfg(test)]
mod tests {
pub mod create {
use std::convert::TryFrom;
use http::{self, header::CONTENT_TYPE, method::Method};
use percent_encoding;
use ruma_identifiers::{RoomAliasId, RoomId};
use serde::{de::IntoDeserializer, Deserialize, Serialize};
use serde_json;
use crate::{Endpoint, Error, Metadata, Outgoing};
#[derive(Debug)]
pub struct Request {
pub room_id: RoomId, pub room_alias: RoomAliasId, }
impl Outgoing for Request {
type Incoming = Self;
}
impl Endpoint for Request {
type Response = Response;
const METADATA: Metadata = Metadata {
description: "Add an alias to a room.",
method: Method::PUT,
name: "create_alias",
path: "/_matrix/client/r0/directory/room/:room_alias",
rate_limited: false,
requires_authentication: true,
};
}
impl TryFrom<Request> for http::Request<Vec<u8>> {
type Error = Error;
fn try_from(request: Request) -> Result<http::Request<Vec<u8>>, Self::Error> {
let metadata = Request::METADATA;
let path = metadata
.path
.to_string()
.replace(":room_alias", &request.room_alias.to_string());
let request_body = RequestBody { room_id: request.room_id };
let http_request = http::Request::builder()
.method(metadata.method)
.uri(path)
.body(serde_json::to_vec(&request_body).map_err(Error::from)?)?;
Ok(http_request)
}
}
impl TryFrom<http::Request<Vec<u8>>> for Request {
type Error = Error;
fn try_from(request: http::Request<Vec<u8>>) -> Result<Self, Self::Error> {
let request_body: RequestBody =
::serde_json::from_slice(request.body().as_slice())?;
let path_segments: Vec<&str> = request.uri().path()[1..].split('/').collect();
Ok(Request {
room_id: request_body.room_id,
room_alias: {
let segment = path_segments.get(5).unwrap().as_bytes();
let decoded = percent_encoding::percent_decode(segment).decode_utf8_lossy();
RoomAliasId::deserialize(decoded.into_deserializer())
.map_err(|e: serde_json::error::Error| e)?
},
})
}
}
#[derive(Debug, Serialize, Deserialize)]
struct RequestBody {
room_id: RoomId,
}
#[derive(Clone, Copy, Debug)]
pub struct Response;
impl Outgoing for Response {
type Incoming = Self;
}
impl TryFrom<http::Response<Vec<u8>>> for Response {
type Error = Error;
fn try_from(http_response: http::Response<Vec<u8>>) -> Result<Response, Self::Error> {
if http_response.status().is_success() {
Ok(Response)
} else {
Err(http_response.status().into())
}
}
}
impl TryFrom<Response> for http::Response<Vec<u8>> {
type Error = Error;
fn try_from(_: Response) -> Result<http::Response<Vec<u8>>, Self::Error> {
let response = http::Response::builder()
.header(CONTENT_TYPE, "application/json")
.body(b"{}".to_vec())
.unwrap();
Ok(response)
}
}
}
}