From 70cba2279e382ebdf4454cb443a0b9e50f04e38f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Maxime=20=E2=80=9Cpep=E2=80=9D=20Buquet?= Date: Wed, 7 Sep 2022 13:10:38 +0200 Subject: [PATCH] tokio-xmpp: Automatically add id on send if not present MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Based on Yuka's work in !149, but moved into tokio-xmpp instead of xmpp-rs Signed-off-by: Maxime “pep” Buquet --- tokio-xmpp/Cargo.toml | 1 + tokio-xmpp/src/xmpp_stream.rs | 12 +++++++++++- 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/tokio-xmpp/Cargo.toml b/tokio-xmpp/Cargo.toml index 795bac8..fe0ce1c 100644 --- a/tokio-xmpp/Cargo.toml +++ b/tokio-xmpp/Cargo.toml @@ -29,6 +29,7 @@ xmpp-parsers = "0.19" minidom = "0.15" rxml = "^0.8.0" webpki-roots = { version = "0.22", optional = true } +rand = "^0.8" [build-dependencies] rustc_version = "0.4" diff --git a/tokio-xmpp/src/xmpp_stream.rs b/tokio-xmpp/src/xmpp_stream.rs index 86ca75b..3c5f047 100644 --- a/tokio-xmpp/src/xmpp_stream.rs +++ b/tokio-xmpp/src/xmpp_stream.rs @@ -2,6 +2,7 @@ use futures::sink::Send; use futures::{sink::SinkExt, task::Poll, Sink, Stream}; +use rand::{thread_rng, Rng}; use std::pin::Pin; use std::task::Context; use tokio::io::{AsyncRead, AsyncWrite}; @@ -13,6 +14,11 @@ use crate::stream_start; use crate::xmpp_codec::{Packet, XMPPCodec}; use crate::Error; +fn make_id() -> String { + let id: u64 = thread_rng().gen(); + format!("{}", id) +} + /// Wraps a binary stream (tokio's `AsyncRead + AsyncWrite`) to decode /// and encode XMPP packets. /// @@ -72,7 +78,11 @@ impl XMPPStream { impl XMPPStream { /// Convenience method pub fn send_stanza>(&mut self, e: E) -> Send { - self.send(Packet::Stanza(e.into())) + let mut el: Element = e.into(); + if el.attr("id").is_none() { + el.set_attr("id", make_id()); + } + self.send(Packet::Stanza(el)) } }