Use AnyMessageEventContent in send_message_event
This commit is contained in:
parent
456505081b
commit
aead9fa852
@ -20,6 +20,7 @@ edition = "2018"
|
|||||||
assign = "1.1.0"
|
assign = "1.1.0"
|
||||||
http = "0.2.1"
|
http = "0.2.1"
|
||||||
js_int = { version = "0.1.9", features = ["serde"] }
|
js_int = { version = "0.1.9", features = ["serde"] }
|
||||||
|
percent-encoding = "2.1.0"
|
||||||
ruma-api = { version = "=0.17.0-alpha.1", path = "../ruma-api" }
|
ruma-api = { version = "=0.17.0-alpha.1", path = "../ruma-api" }
|
||||||
ruma-common = { version = "0.2.0", path = "../ruma-common" }
|
ruma-common = { version = "0.2.0", path = "../ruma-common" }
|
||||||
ruma-events = { version = "=0.22.0-alpha.1", path = "../ruma-events" }
|
ruma-events = { version = "=0.22.0-alpha.1", path = "../ruma-events" }
|
||||||
|
@ -1,48 +1,203 @@
|
|||||||
//! [PUT /_matrix/client/r0/rooms/{roomId}/send/{eventType}/{txnId}](https://matrix.org/docs/spec/client_server/r0.6.1#put-matrix-client-r0-rooms-roomid-send-eventtype-txnid)
|
//! [PUT /_matrix/client/r0/rooms/{roomId}/send/{eventType}/{txnId}](https://matrix.org/docs/spec/client_server/r0.6.1#put-matrix-client-r0-rooms-roomid-send-eventtype-txnid)
|
||||||
|
|
||||||
use ruma_api::ruma_api;
|
use std::convert::TryFrom;
|
||||||
use ruma_events::EventType;
|
|
||||||
|
use ruma_api::{
|
||||||
|
error::{
|
||||||
|
FromHttpRequestError, FromHttpResponseError, IntoHttpError, RequestDeserializationError,
|
||||||
|
ResponseDeserializationError, ServerError,
|
||||||
|
},
|
||||||
|
EndpointError, Metadata, Outgoing,
|
||||||
|
};
|
||||||
|
use ruma_events::{AnyMessageEventContent, EventContent as _};
|
||||||
use ruma_identifiers::{EventId, RoomId};
|
use ruma_identifiers::{EventId, RoomId};
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
use serde_json::value::RawValue as RawJsonValue;
|
use serde_json::value::RawValue as RawJsonValue;
|
||||||
|
|
||||||
ruma_api! {
|
/// Data for a request to the `send_message_event` API endpoint.
|
||||||
metadata: {
|
///
|
||||||
description: "Send a message event to a room.",
|
/// Send a message event to a room.
|
||||||
method: PUT,
|
#[derive(Clone, Debug, Outgoing)]
|
||||||
name: "create_message_event",
|
#[non_exhaustive]
|
||||||
path: "/_matrix/client/r0/rooms/:room_id/send/:event_type/:txn_id",
|
#[incoming_no_deserialize]
|
||||||
rate_limited: false,
|
pub struct Request<'a> {
|
||||||
requires_authentication: true,
|
/// The room to send the event to.
|
||||||
}
|
pub room_id: &'a RoomId,
|
||||||
|
|
||||||
request: {
|
/// The transaction ID for this event.
|
||||||
/// The room to send the event to.
|
///
|
||||||
#[ruma_api(path)]
|
/// Clients should generate an ID unique across requests with the
|
||||||
pub room_id: &'a RoomId,
|
/// same access token; it will be used by the server to ensure
|
||||||
|
/// idempotency of requests.
|
||||||
|
pub txn_id: &'a str,
|
||||||
|
|
||||||
/// The type of event to send.
|
/// The event content to send.
|
||||||
#[ruma_api(path)]
|
pub content: &'a AnyMessageEventContent,
|
||||||
pub event_type: EventType,
|
}
|
||||||
|
|
||||||
/// The transaction ID for this event.
|
impl<'a> Request<'a> {
|
||||||
///
|
/// Creates a new `Request` with the given room id, transaction id and event content.
|
||||||
/// Clients should generate an ID unique across requests with the
|
pub fn new(room_id: &'a RoomId, txn_id: &'a str, content: &'a AnyMessageEventContent) -> Self {
|
||||||
/// same access token; it will be used by the server to ensure
|
Self { room_id, txn_id, content }
|
||||||
/// idempotency of requests.
|
}
|
||||||
#[ruma_api(path)]
|
}
|
||||||
pub txn_id: &'a str,
|
|
||||||
|
/// Data in the response from the `send_message_event` API endpoint.
|
||||||
/// The event's content. The type for this field will be updated in a
|
#[derive(Clone, Debug, Outgoing)]
|
||||||
/// future release, until then you can create a value using
|
#[non_exhaustive]
|
||||||
/// `serde_json::value::to_raw_value`.
|
#[incoming_no_deserialize]
|
||||||
#[ruma_api(body)]
|
pub struct Response {
|
||||||
pub data: Box<RawJsonValue>,
|
/// A unique identifier for the event.
|
||||||
}
|
pub event_id: EventId,
|
||||||
|
}
|
||||||
response: {
|
|
||||||
/// A unique identifier for the event.
|
impl Response {
|
||||||
pub event_id: EventId,
|
/// Creates a new `Response` with the given event id.
|
||||||
}
|
pub fn new(event_id: EventId) -> Self {
|
||||||
|
Self { event_id }
|
||||||
error: crate::Error
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const METADATA: Metadata = Metadata {
|
||||||
|
description: "Send a message event to a room.",
|
||||||
|
method: http::Method::PUT,
|
||||||
|
name: "send_message_event",
|
||||||
|
path: "/_matrix/client/r0/rooms/:room_id/send/:event_type/:txn_id",
|
||||||
|
rate_limited: false,
|
||||||
|
requires_authentication: true,
|
||||||
|
};
|
||||||
|
|
||||||
|
impl TryFrom<http::Request<Vec<u8>>> for IncomingRequest {
|
||||||
|
type Error = FromHttpRequestError;
|
||||||
|
|
||||||
|
fn try_from(request: http::Request<Vec<u8>>) -> Result<Self, Self::Error> {
|
||||||
|
let path_segments: Vec<&str> = request.uri().path()[1..].split('/').collect();
|
||||||
|
|
||||||
|
let room_id = {
|
||||||
|
let decoded =
|
||||||
|
match percent_encoding::percent_decode(path_segments[4].as_bytes()).decode_utf8() {
|
||||||
|
Ok(val) => val,
|
||||||
|
Err(err) => return Err(RequestDeserializationError::new(err, request).into()),
|
||||||
|
};
|
||||||
|
|
||||||
|
match RoomId::try_from(&*decoded) {
|
||||||
|
Ok(val) => val,
|
||||||
|
Err(err) => return Err(RequestDeserializationError::new(err, request).into()),
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
let txn_id =
|
||||||
|
match percent_encoding::percent_decode(path_segments[7].as_bytes()).decode_utf8() {
|
||||||
|
Ok(val) => val.into_owned(),
|
||||||
|
Err(err) => return Err(RequestDeserializationError::new(err, request).into()),
|
||||||
|
};
|
||||||
|
|
||||||
|
let content = {
|
||||||
|
let request_body: Box<RawJsonValue> =
|
||||||
|
match serde_json::from_slice(request.body().as_slice()) {
|
||||||
|
Ok(val) => val,
|
||||||
|
Err(err) => return Err(RequestDeserializationError::new(err, request).into()),
|
||||||
|
};
|
||||||
|
|
||||||
|
let event_type = {
|
||||||
|
match percent_encoding::percent_decode(path_segments[6].as_bytes()).decode_utf8() {
|
||||||
|
Ok(val) => val,
|
||||||
|
Err(err) => return Err(RequestDeserializationError::new(err, request).into()),
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
match AnyMessageEventContent::from_parts(&event_type, request_body) {
|
||||||
|
Ok(content) => content,
|
||||||
|
Err(err) => return Err(RequestDeserializationError::new(err, request).into()),
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
Ok(Self { room_id, txn_id, content })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Data in the response body.
|
||||||
|
#[derive(Debug, Deserialize, Serialize)]
|
||||||
|
struct ResponseBody {
|
||||||
|
/// A unique identifier for the event.
|
||||||
|
event_id: EventId,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl TryFrom<Response> for http::Response<Vec<u8>> {
|
||||||
|
type Error = IntoHttpError;
|
||||||
|
|
||||||
|
fn try_from(response: Response) -> Result<Self, Self::Error> {
|
||||||
|
let response = http::Response::builder()
|
||||||
|
.header(http::header::CONTENT_TYPE, "application/json")
|
||||||
|
.body(serde_json::to_vec(&ResponseBody { event_id: response.event_id })?)
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
Ok(response)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl TryFrom<http::Response<Vec<u8>>> for Response {
|
||||||
|
type Error = FromHttpResponseError<crate::Error>;
|
||||||
|
|
||||||
|
fn try_from(response: http::Response<Vec<u8>>) -> Result<Self, Self::Error> {
|
||||||
|
if response.status().as_u16() < 400 {
|
||||||
|
let response_body: ResponseBody =
|
||||||
|
match serde_json::from_slice(response.body().as_slice()) {
|
||||||
|
Ok(val) => val,
|
||||||
|
Err(err) => return Err(ResponseDeserializationError::new(err, response).into()),
|
||||||
|
};
|
||||||
|
|
||||||
|
Ok(Self { event_id: response_body.event_id })
|
||||||
|
} else {
|
||||||
|
match <crate::Error as EndpointError>::try_from_response(response) {
|
||||||
|
Ok(err) => Err(ServerError::Known(err).into()),
|
||||||
|
Err(response_err) => Err(ServerError::Unknown(response_err).into()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a> ruma_api::OutgoingRequest for Request<'a> {
|
||||||
|
type EndpointError = crate::Error;
|
||||||
|
type IncomingResponse = Response;
|
||||||
|
|
||||||
|
/// Metadata for the `send_message_event` endpoint.
|
||||||
|
const METADATA: Metadata = METADATA;
|
||||||
|
|
||||||
|
fn try_into_http_request(
|
||||||
|
self,
|
||||||
|
base_url: &str,
|
||||||
|
access_token: Option<&str>,
|
||||||
|
) -> Result<http::Request<Vec<u8>>, IntoHttpError> {
|
||||||
|
use http::header::{HeaderValue, AUTHORIZATION};
|
||||||
|
use percent_encoding::{utf8_percent_encode, NON_ALPHANUMERIC};
|
||||||
|
|
||||||
|
let http_request = http::Request::builder()
|
||||||
|
.method(http::Method::PUT)
|
||||||
|
.uri(format!(
|
||||||
|
"{}/_matrix/client/r0/rooms/{}/send/{}/{}",
|
||||||
|
base_url.strip_suffix("/").unwrap_or(base_url),
|
||||||
|
utf8_percent_encode(self.room_id.as_str(), NON_ALPHANUMERIC),
|
||||||
|
utf8_percent_encode(self.content.event_type(), NON_ALPHANUMERIC),
|
||||||
|
utf8_percent_encode(&self.txn_id, NON_ALPHANUMERIC),
|
||||||
|
))
|
||||||
|
.header(
|
||||||
|
AUTHORIZATION,
|
||||||
|
HeaderValue::from_str(&format!(
|
||||||
|
"Bearer {}",
|
||||||
|
access_token.ok_or(IntoHttpError::NeedsAuthentication)?
|
||||||
|
))?,
|
||||||
|
)
|
||||||
|
.body(serde_json::to_vec(&self.content)?)?;
|
||||||
|
|
||||||
|
Ok(http_request)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ruma_api::IncomingRequest for IncomingRequest {
|
||||||
|
type EndpointError = crate::Error;
|
||||||
|
type OutgoingResponse = Response;
|
||||||
|
|
||||||
|
/// Metadata for the `send_message_event` endpoint.
|
||||||
|
const METADATA: Metadata = METADATA;
|
||||||
}
|
}
|
||||||
|
@ -5,34 +5,30 @@ use ruma::{
|
|||||||
api::client::r0::{alias::get_alias, membership::join_room_by_id, message::send_message_event},
|
api::client::r0::{alias::get_alias, membership::join_room_by_id, message::send_message_event},
|
||||||
events::{
|
events::{
|
||||||
room::message::{MessageEventContent, TextMessageEventContent},
|
room::message::{MessageEventContent, TextMessageEventContent},
|
||||||
EventType,
|
AnyMessageEventContent,
|
||||||
},
|
},
|
||||||
RoomAliasId,
|
RoomAliasId,
|
||||||
};
|
};
|
||||||
use ruma_client::{self, Client};
|
use ruma_client::{self, Client};
|
||||||
use serde_json::value::to_raw_value as to_raw_json_value;
|
|
||||||
|
|
||||||
async fn hello_world(homeserver_url: Uri, room_alias: &RoomAliasId) -> anyhow::Result<()> {
|
async fn hello_world(homeserver_url: Uri, room_alias: &RoomAliasId) -> anyhow::Result<()> {
|
||||||
let client = Client::new(homeserver_url, None);
|
let client = Client::new(homeserver_url, None);
|
||||||
|
|
||||||
client.register_guest().await?;
|
client.register_guest().await?;
|
||||||
let response = client.request(get_alias::Request::new(room_alias)).await?;
|
|
||||||
|
|
||||||
let room_id = response.room_id;
|
|
||||||
|
|
||||||
|
let room_id = client.request(get_alias::Request::new(room_alias)).await?.room_id;
|
||||||
client.request(join_room_by_id::Request::new(&room_id)).await?;
|
client.request(join_room_by_id::Request::new(&room_id)).await?;
|
||||||
|
|
||||||
client
|
client
|
||||||
.request(send_message_event::Request {
|
.request(send_message_event::Request::new(
|
||||||
room_id: &room_id,
|
&room_id,
|
||||||
event_type: EventType::RoomMessage,
|
"1",
|
||||||
txn_id: "1",
|
&AnyMessageEventContent::RoomMessage(MessageEventContent::Text(
|
||||||
data: to_raw_json_value(&MessageEventContent::Text(TextMessageEventContent {
|
TextMessageEventContent {
|
||||||
body: "Hello World!".to_owned(),
|
body: "Hello World!".to_owned(),
|
||||||
formatted: None,
|
formatted: None,
|
||||||
relates_to: None,
|
relates_to: None,
|
||||||
}))?,
|
},
|
||||||
})
|
)),
|
||||||
|
))
|
||||||
.await?;
|
.await?;
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
|
Loading…
x
Reference in New Issue
Block a user