diff --git a/tokio-xmpp/examples/download_avatars.rs b/tokio-xmpp/examples/download_avatars.rs index d8dbd67..c63f409 100644 --- a/tokio-xmpp/examples/download_avatars.rs +++ b/tokio-xmpp/examples/download_avatars.rs @@ -67,16 +67,18 @@ async fn main() { .with_to(iq.from.unwrap()); client.send_stanza(iq.into()).await.unwrap(); } - Err(err) => client - .send_stanza(make_error( - iq.from.unwrap(), - iq.id, - ErrorType::Modify, - DefinedCondition::BadRequest, - &format!("{}", err), - )) - .await - .unwrap(), + Err(err) => { + client + .send_stanza(make_error( + iq.from.unwrap(), + iq.id, + ErrorType::Modify, + DefinedCondition::BadRequest, + &format!("{}", err), + )) + .await + .unwrap(); + } } } else { // We MUST answer unhandled get iqs with a service-unavailable error. diff --git a/tokio-xmpp/src/client/async_client.rs b/tokio-xmpp/src/client/async_client.rs index 4f85185..8118734 100644 --- a/tokio-xmpp/src/client/async_client.rs +++ b/tokio-xmpp/src/client/async_client.rs @@ -76,10 +76,16 @@ impl Client { } } - /// Send stanza - pub async fn send_stanza(&mut self, stanza: Element) -> Result<(), Error> { - self.send(Packet::Stanza(add_stanza_id(stanza, ns::JABBER_CLIENT))) - .await + /// Send stanza. An id will be assigned if not already present. + pub async fn send_stanza(&mut self, stanza: Element) -> Result { + let stanza = add_stanza_id(stanza, ns::JABBER_CLIENT); + + // Get the Id. (With add_stanza_id, it should always be present) + let id = stanza.attr("id").unwrap().to_string(); + + self.send(Packet::Stanza(stanza)).await?; + + Ok(id) } /// Get the stream features (``) of the underlying stream diff --git a/xmpp/examples/hello_bot.rs b/xmpp/examples/hello_bot.rs index dac0ac6..d4529c0 100644 --- a/xmpp/examples/hello_bot.rs +++ b/xmpp/examples/hello_bot.rs @@ -76,7 +76,8 @@ async fn main() -> Result<(), Option<()>> { println!("Joined room {}.", jid); client .send_message(Jid::Bare(jid), MessageType::Groupchat, "en", "Hello world!") - .await; + .await + .expect("Could not send message."); } Event::RoomLeft(jid) => { println!("Left room {}.", jid); diff --git a/xmpp/src/agent.rs b/xmpp/src/agent.rs index df31db7..daa99ee 100644 --- a/xmpp/src/agent.rs +++ b/xmpp/src/agent.rs @@ -60,23 +60,52 @@ impl Agent { muc::room::leave_room(self, room_jid, nickname, lang, status).await } + /// Send a message to a given recipient. + /// + /// Returns the generated message ID. + /// + /// # Arguments + /// + /// * `recipient`: The JID of the recipient. + /// * `type_`: The type of message to send. + /// For a message to a MUC room, this should be `MessageType::Groupchat`. + /// For a private message to a MUC room member or regular contact, + /// this should be `MessageType::Chat`. + /// * `lang`: The language of the message. (See IETF RFC 5646) + /// * `text`: The text of the message. pub async fn send_message( &mut self, recipient: Jid, type_: MessageType, lang: &str, text: &str, - ) { + ) -> Result { message::send::send_message(self, recipient, type_, lang, text).await } + /// Send a private message to a given MUC room member. + /// + /// Returns the generated message ID. + /// + /// # Arguments + /// + /// * `room`: The JID of the room. + /// * `recipient`: The nickname of the recipient within the room. + /// * `type_`: The type of message to send. + /// For a message to a MUC room, this should be `MessageType::Groupchat`. + /// For a private message to a MUC room member or regular contact, + /// this should be `MessageType::Chat`. + /// * `lang`: The language of the message. (See IETF RFC 5646) + /// * `text`: The text of the message. + /// + /// Returns the generated message ID, or an error if the message could not be sent. pub async fn send_room_private_message( &mut self, room: BareJid, recipient: RoomNick, lang: &str, text: &str, - ) { + ) -> Result { muc::private_message::send_room_private_message(self, room, recipient, lang, text).await } diff --git a/xmpp/src/event.rs b/xmpp/src/event.rs index c7a8e3a..c3d667c 100644 --- a/xmpp/src/event.rs +++ b/xmpp/src/event.rs @@ -8,6 +8,7 @@ use tokio_xmpp::parsers::Jid; use tokio_xmpp::parsers::{bookmarks2, message::Body, roster::Item as RosterItem, BareJid}; +use crate::message::MucMessageId; use crate::{delay::StanzaTimeInfo, Error, Id, RoomNick}; #[derive(Debug)] @@ -30,15 +31,42 @@ pub enum Event { LeaveAllRooms, RoomJoined(BareJid), RoomLeft(BareJid), - RoomMessage(Id, BareJid, RoomNick, Body, StanzaTimeInfo), + /// A message received from a group chat room. + /// - The [`MucMessageId`] is the ID of the message; it contains the ID assigned by the room, + /// and the ID assigned by the sending client. + /// - The [`BareJid`] is the room's address. + /// - The [`RoomNick`] is the nickname of the room member who sent the message. + /// - The [`Body`] is the message body. + /// - The [`StanzaTimeInfo`] about when message was received, and when the message was claimed sent. + /// + /// Note: if the sender_assigned_id matches the ID returned by Agent::send_message, + /// then the message is an echo of a message sent by the client. + RoomMessage(MucMessageId, BareJid, RoomNick, Body, StanzaTimeInfo), /// The subject of a room was received. - /// - The BareJid is the room's address. - /// - The RoomNick is the nickname of the room member who set the subject. - /// - The String is the new subject. - RoomSubject(BareJid, Option, String, StanzaTimeInfo), - /// A private message received from a room, containing the message ID, the room's BareJid, - /// the sender's nickname, and the message body. - RoomPrivateMessage(Id, BareJid, RoomNick, Body, StanzaTimeInfo), + /// - The MucMessageId is the ID of the message that contained the subject; + /// it contains the ID assigned by the room, and the ID assigned by the sending client. + /// - The [`BareJid`] is the room's address. + /// - The [`RoomNick`] is the nickname of the room member who set the subject. + /// - The [`String`] is the new subject. + /// - The [`StanzaTimeInfo`] about when message was received, and when the message was claimed sent. + RoomSubject( + MucMessageId, + BareJid, + Option, + String, + StanzaTimeInfo, + ), + /// A private message received from a member of a room. + /// - The [`MucMessageId`] is the ID of the message; it contains the ID assigned by the room, + /// and the ID assigned by the sending client. + /// - The [`BareJid`] is the room's address. + /// - The [`RoomNick`] is the nickname of the room member who sent the message. + /// - The [`Body`] is the message body. + /// - The [`StanzaTimeInfo`] about when message was received, and when the message was claimed sent. + /// + /// Note: if the sender_assigned_id matches the ID returned by Agent::send_room_private_message, + /// then the message is an echo of a message sent by the client. + RoomPrivateMessage(MucMessageId, BareJid, RoomNick, Body, StanzaTimeInfo), ServiceMessage(Id, BareJid, Body, StanzaTimeInfo), HttpUploadedFile(String), } diff --git a/xmpp/src/lib.rs b/xmpp/src/lib.rs index 780fe4e..00eaed4 100644 --- a/xmpp/src/lib.rs +++ b/xmpp/src/lib.rs @@ -33,6 +33,7 @@ pub use feature::ClientFeature; pub type Error = tokio_xmpp::Error; pub type Id = Option; + pub type RoomNick = String; #[cfg(all(test, any(feature = "starttls-rust", feature = "starttls-native")))] diff --git a/xmpp/src/message/mod.rs b/xmpp/src/message/mod.rs index f38387b..1db0580 100644 --- a/xmpp/src/message/mod.rs +++ b/xmpp/src/message/mod.rs @@ -4,5 +4,24 @@ // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. +use crate::Id; + pub mod receive; pub mod send; + +/// A message ID for a message in a MUC room. +/// +/// Note: this struct is a bit weird due to an inconsistency between XEPs 0308 and 0424. +/// +/// XEP-0424 (Message Retraction) designates messages to correct by the sender-assigned ID, +/// but XEP-0308 (Last Message Correction) designates messages to correct by the room-assigned ID. +/// +/// Hence, both are needed, but depending on context, one or the other may be missing or may +/// refer to something else; see the context-specific documentation for more information. +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub struct MucMessageId { + /// The ID of the message as assigned by the client that sent it. + pub sender_assigned_id: Id, + /// The ID of the message as assigned by the room. + pub room_assigned_id: Id, +} diff --git a/xmpp/src/message/receive/chat.rs b/xmpp/src/message/receive/chat.rs index bca97c8..bca92a6 100644 --- a/xmpp/src/message/receive/chat.rs +++ b/xmpp/src/message/receive/chat.rs @@ -10,6 +10,7 @@ use tokio_xmpp::{ Jid, }; +use crate::message::receive::group_chat::extract_muc_message_id; use crate::{delay::StanzaTimeInfo, Agent, Event}; pub async fn handle_message_chat( @@ -37,7 +38,7 @@ pub async fn handle_message_chat( ) } Jid::Full(full) => Event::RoomPrivateMessage( - message.id.clone(), + extract_muc_message_id(message), full.to_bare(), full.resource().to_string(), body.clone(), diff --git a/xmpp/src/message/receive/group_chat.rs b/xmpp/src/message/receive/group_chat.rs index 118039e..5e99da6 100644 --- a/xmpp/src/message/receive/group_chat.rs +++ b/xmpp/src/message/receive/group_chat.rs @@ -7,6 +7,9 @@ use tokio_xmpp::connect::ServerConnector; use tokio_xmpp::{parsers::message::Message, Jid}; +use crate::message::MucMessageId; +use crate::parsers::ns::SID; +use crate::parsers::stanza_id::StanzaId; use crate::{delay::StanzaTimeInfo, Agent, Event}; pub async fn handle_message_group_chat( @@ -18,8 +21,11 @@ pub async fn handle_message_group_chat( ) { let langs: Vec<&str> = agent.lang.iter().map(String::as_str).collect(); + let id = extract_muc_message_id(message); + if let Some((_lang, subject)) = message.get_best_subject(langs.clone()) { events.push(Event::RoomSubject( + id.clone(), from.to_bare(), from.resource().map(|x| x.to_string()), subject.0.clone(), @@ -30,7 +36,7 @@ pub async fn handle_message_group_chat( if let Some((_lang, body)) = message.get_best_body(langs) { let event = match from.clone() { Jid::Full(full) => Event::RoomMessage( - message.id.clone(), + id, from.to_bare(), full.resource().to_string(), body.clone(), @@ -43,3 +49,23 @@ pub async fn handle_message_group_chat( events.push(event) } } + +/// Extract the sender-assigned and room-assigned IDs from a message. +pub fn extract_muc_message_id(message: &Message) -> MucMessageId { + // Find a stanza-id element, if any. + let stanza_id = message + .payloads + .iter() + .find(|payload| payload.is("stanza-id", SID)) + .map(|elem| { + StanzaId::try_from(elem.clone()) + .expect("Failed to parse stanza-id") + .id + }); + + let id = MucMessageId { + sender_assigned_id: message.id.clone(), + room_assigned_id: stanza_id, + }; + id +} diff --git a/xmpp/src/message/send.rs b/xmpp/src/message/send.rs index 877aca8..734060b 100644 --- a/xmpp/src/message/send.rs +++ b/xmpp/src/message/send.rs @@ -7,22 +7,38 @@ use tokio_xmpp::connect::ServerConnector; use tokio_xmpp::{ parsers::message::{Body, Message, MessageType}, - Jid, + Error, Jid, }; use crate::Agent; +/// Send a message to a given recipient. +/// +/// Returns the generated message ID. +/// +/// # Arguments +/// +/// * `agent`: The agent to use to send the message. +/// * `recipient`: The JID of the recipient. +/// * `type_`: The type of message to send. +/// For a message to a MUC room, this should be `MessageType::Groupchat`. +/// For a private message to a MUC room member or regular contact, +/// this should be `MessageType::Chat`. +/// * `lang`: The language of the message. (See IETF RFC 5646) +/// * `text`: The text of the message. +/// +/// Returns the generated message ID, or an error if the message could not be sent. pub async fn send_message( agent: &mut Agent, recipient: Jid, type_: MessageType, lang: &str, text: &str, -) { +) -> Result { let mut message = Message::new(Some(recipient)); message.type_ = type_; message .bodies .insert(String::from(lang), Body(String::from(text))); - let _ = agent.client.send_stanza(message.into()).await; + agent.client.send_stanza(message.into()).await } diff --git a/xmpp/src/muc/private_message.rs b/xmpp/src/muc/private_message.rs index 7b5883f..a3c9fc0 100644 --- a/xmpp/src/muc/private_message.rs +++ b/xmpp/src/muc/private_message.rs @@ -10,23 +10,40 @@ use tokio_xmpp::{ message::{Body, Message, MessageType}, muc::user::MucUser, }, - BareJid, Jid, + BareJid, Error, Jid, }; use crate::{Agent, RoomNick}; +/// Send a private message to a given MUC room member. +/// +/// Returns the generated message ID. +/// +/// # Arguments +/// +/// * `agent`: The agent to use to send the message. +/// * `room`: The JID of the room. +/// * `recipient`: The nickname of the recipient within the room. +/// * `type_`: The type of message to send. +/// For a message to a MUC room, this should be `MessageType::Groupchat`. +/// For a private message to a MUC room member or regular contact, +/// this should be `MessageType::Chat`. +/// * `lang`: The language of the message. (See IETF RFC 5646) +/// * `text`: The text of the message. +/// +/// Returns the generated message ID, or an error if the message could not be sent. pub async fn send_room_private_message( agent: &mut Agent, room: BareJid, recipient: RoomNick, lang: &str, text: &str, -) { +) -> Result { let recipient: Jid = room.with_resource_str(&recipient).unwrap().into(); let mut message = Message::new(recipient).with_payload(MucUser::new()); message.type_ = MessageType::Chat; message .bodies .insert(String::from(lang), Body(String::from(text))); - let _ = agent.client.send_stanza(message.into()).await; + agent.client.send_stanza(message.into()).await }