forked from lavina/lavina
1
0
Fork 0

fix message parsing

This commit is contained in:
Nikita Vilunov 2023-10-01 21:54:14 +02:00
parent 7c89936a87
commit ea0377c78a
3 changed files with 57 additions and 58 deletions

View File

@ -328,7 +328,7 @@ async fn socket_final(
if let Some(update) = update {
match update {
lavina_core::player::Updates::NewMessage { room_id, author_id, body } => {
Message {
Message::<()> {
to: Some(Jid {
name: Some(authenticated.xmpp_name.clone()),
server: Server("localhost".into()),
@ -344,6 +344,7 @@ async fn socket_final(
lang: None,
subject: None,
body: body.into(),
custom: vec![],
}
.serialize(&mut events);
}
@ -393,7 +394,7 @@ async fn handle_packet(
user_handle
.send_message(RoomId::from(name.0.clone())?, m.body.clone().into())
.await?;
Message {
Message::<()> {
to: Some(Jid {
name: Some(user.xmpp_name.clone()),
server: Server("localhost".into()),
@ -409,6 +410,7 @@ async fn handle_packet(
lang: None,
subject: None,
body: m.body.clone(),
custom: vec![],
}
.serialize(output);
false

View File

@ -49,7 +49,7 @@ impl FromXml for IqClientBody {
#[derive(PartialEq, Eq, Debug, From)]
pub enum ClientPacket {
Iq(Iq<IqClientBody>),
Message(Message),
Message(Message<Ignore>),
Presence(Presence<Ignore>),
StreamEnd,
}
@ -65,7 +65,7 @@ impl FromXml for ClientPacket {
match_parser!(name, namespace, event;
Iq::<IqClientBody>,
Presence::<Ignore>,
Message,
Message::<Ignore>,
{
Err(anyhow!(
"Unexpected XML event of name {:?} in namespace {:?}",

View File

@ -3,8 +3,7 @@ use quick_xml::events::attributes::Attribute;
use quick_xml::events::{BytesEnd, BytesStart, BytesText, Event};
use quick_xml::name::{QName, ResolveResult};
use anyhow::{Result, anyhow as ffail};
use anyhow::{anyhow as ffail, Result};
use crate::prelude::*;
use crate::xml::*;
@ -26,33 +25,33 @@ pub struct Message<T> {
pub custom: Vec<T>,
}
impl<T> FromXmlTag for Message<T> {
impl<T: FromXml> FromXmlTag for Message<T> {
const NS: &'static str = XMLNS;
const NAME: &'static str = "message";
}
impl<T> FromXml for Message<T> {
type P = MessageParser<T>;
impl<T: FromXml> FromXml for Message<T> {
type P = impl Parser<Output = Result<Self>>;
fn parse() -> Self::P {
MessageParserInner::Init.into()
MessageParser(MessageParserInner::Init)
}
}
#[derive(From)]
pub struct MessageParser<T: FromXml>(MessageParserInner<T>);
struct MessageParser<T: FromXml>(MessageParserInner<T>);
#[derive(Default)]
enum MessageParserInner<T: FromXml> {
#[default]
Init,
Outer(MessageParserState),
InSubject(MessageParserState),
InBody(MessageParserState),
InCustom(T::P),
Outer(MessageParserState<T>),
InSubject(MessageParserState<T>),
InBody(MessageParserState<T>),
InCustom(MessageParserState<T>, T::P),
}
#[derive(Default)]
struct MessageParserState {
struct MessageParserState<T> {
from: Option<Jid>,
id: Option<String>,
to: Option<Jid>,
@ -60,21 +59,27 @@ struct MessageParserState {
lang: Option<Str>,
subject: Option<Str>,
body: Option<Str>,
custom: Vec<T>,
}
impl<T> Parser for MessageParser<T> {
impl<T: FromXml> Parser for MessageParser<T> {
type Output = Result<Message<T>>;
fn consume<'a>(
self: Self,
namespace: ResolveResult,
event: &Event<'a>,
) -> Continuation<Self, Self::Output> {
fn consume<'a>(self: Self, namespace: ResolveResult, event: &Event<'a>) -> Continuation<Self, Self::Output> {
// TODO validate tag name and namespace at each stage
use MessageParserInner::*;
match self.0 {
Init => {
if let Event::Start(ref bytes) = event {
let mut state: MessageParserState = Default::default();
let mut state: MessageParserState<T> = MessageParserState {
from: None,
id: None,
to: None,
r#type: MessageType::Normal,
lang: None,
subject: None,
body: None,
custom: vec![],
};
for attr in bytes.attributes() {
let attr = fail_fast!(attr);
if attr.key.0 == b"from" {
@ -105,7 +110,7 @@ impl<T> Parser for MessageParser<T> {
} else if bytes.name().0 == b"body" {
Continuation::Continue(InBody(state).into())
} else {
Continuation::Final(Err(ffail!("Unexpected XML event: {event:?}")))
Continuation::Continue(InCustom(state, T::parse()).into())
}
}
Event::End(_) => {
@ -118,6 +123,7 @@ impl<T> Parser for MessageParser<T> {
lang: state.lang,
subject: state.subject,
body,
custom: state.custom,
}))
} else {
Continuation::Final(Err(ffail!("Body not found")))
@ -145,6 +151,14 @@ impl<T> Parser for MessageParser<T> {
Event::End(_) => Continuation::Continue(Outer(state).into()),
_ => Continuation::Final(Err(ffail!("Unexpected XML event: {event:?}"))),
},
InCustom(mut state, mut custom) => match custom.consume(namespace, event) {
Continuation::Final(Ok(e)) => {
state.custom.push(e);
Continuation::Continue(Outer(state).into())
}
Continuation::Final(Err(e)) => Continuation::Final(Err(e)),
Continuation::Continue(c) => Continuation::Continue(InCustom(state, c).into()),
},
}
}
}
@ -262,11 +276,7 @@ struct IqParserState<T> {
impl<T: FromXml> Parser for IqParser<T> {
type Output = Result<Iq<T>>;
fn consume<'a>(
self: Self,
namespace: ResolveResult,
event: &Event<'a>,
) -> Continuation<Self, Self::Output> {
fn consume<'a>(self: Self, namespace: ResolveResult, event: &Event<'a>) -> Continuation<Self, Self::Output> {
match self.0 {
IqParserInner::Init => {
if let Event::Start(ref bytes) = event {
@ -298,8 +308,7 @@ impl<T: FromXml> Parser for IqParser<T> {
Continuation::Final(Err(ffail!("Expected start")))
}
}
IqParserInner::ParsingBody(mut state, parser) => {
match parser.consume(namespace, event) {
IqParserInner::ParsingBody(mut state, parser) => match parser.consume(namespace, event) {
Continuation::Final(f) => {
let body = fail_fast!(f);
state.body = Some(body);
@ -308,8 +317,7 @@ impl<T: FromXml> Parser for IqParser<T> {
Continuation::Continue(parser) => {
Continuation::Continue(IqParser(IqParserInner::ParsingBody(state, parser)))
}
}
}
},
IqParserInner::Final(state) => {
if let Event::End(ref bytes) = event {
let id = fail_fast!(state.id.ok_or_else(|| ffail!("No id provided")));
@ -590,22 +598,16 @@ mod tests {
#[tokio::test]
async fn parse_message() {
let input = r#"<message id="aacea" type="chat" to="nikita@vlnv.dev"><subject>daa</subject><body>bbb</body></message>"#;
let input = r#"<message id="aacea" type="chat" to="nikita@vlnv.dev"><subject>daa</subject><body>bbb</body><unknown-stuff></unknown-stuff></message>"#;
let mut reader = NsReader::from_reader(input.as_bytes());
let mut buf = vec![];
let (ns, event) = reader
.read_resolved_event_into_async(&mut buf)
.await
.unwrap();
let (ns, event) = reader.read_resolved_event_into_async(&mut buf).await.unwrap();
let mut parser = Message::parse().consume(ns, &event);
let result = loop {
match parser {
Continuation::Final(res) => break res,
Continuation::Continue(next) => {
let (ns, event) = reader
.read_resolved_event_into_async(&mut buf)
.await
.unwrap();
let (ns, event) = reader.read_resolved_event_into_async(&mut buf).await.unwrap();
parser = next.consume(ns, &event);
}
}
@ -613,7 +615,7 @@ mod tests {
.unwrap();
assert_eq!(
result,
Message {
Message::<Ignore> {
from: None,
id: Some("aacea".to_string()),
to: Some(Jid {
@ -625,6 +627,7 @@ mod tests {
lang: None,
subject: Some("daa".into()),
body: "bbb".into(),
custom: vec![Ignore],
}
)
}
@ -634,19 +637,13 @@ mod tests {
let input = r#"<iq id="bind_1" type="set"><bind xmlns="urn:ietf:params:xml:ns:xmpp-bind"><resource>mobile</resource></bind></iq>"#;
let mut reader = NsReader::from_reader(input.as_bytes());
let mut buf = vec![];
let (ns, event) = reader
.read_resolved_event_into_async(&mut buf)
.await
.unwrap();
let (ns, event) = reader.read_resolved_event_into_async(&mut buf).await.unwrap();
let mut parser = Iq::<BindRequest>::parse().consume(ns, &event);
let result = loop {
match parser {
Continuation::Final(res) => break res,
Continuation::Continue(next) => {
let (ns, event) = reader
.read_resolved_event_into_async(&mut buf)
.await
.unwrap();
let (ns, event) = reader.read_resolved_event_into_async(&mut buf).await.unwrap();
parser = next.consume(ns, &event);
}
}