forked from lavina/lavina
1
0
Fork 0

apply uniform formatting

This commit is contained in:
Nikita Vilunov 2024-03-20 19:59:15 +01:00
parent 1d9937319e
commit 878ec33cbb
18 changed files with 63 additions and 159 deletions

View File

@ -12,7 +12,7 @@ jobs:
uses: https://github.com/actions-rs/cargo@v1
with:
command: fmt
args: "--check -p mgmt-api -p lavina-core -p projection-irc -p projection-xmpp -p sasl"
args: "--check --all"
- name: cargo check
uses: https://github.com/actions-rs/cargo@v1
with:

View File

@ -55,9 +55,7 @@ pub struct PlayerConnection {
}
impl PlayerConnection {
pub async fn send_message(&mut self, room_id: RoomId, body: Str) -> Result<()> {
self.player_handle
.send_message(room_id, self.connection_id.clone(), body)
.await
self.player_handle.send_message(room_id, self.connection_id.clone(), body).await
}
pub async fn join_room(&mut self, room_id: RoomId) -> Result<JoinResult> {
@ -71,9 +69,7 @@ impl PlayerConnection {
new_topic,
promise,
};
self.player_handle
.send(PlayerCommand::Cmd(cmd, self.connection_id.clone()))
.await;
self.player_handle.send(PlayerCommand::Cmd(cmd, self.connection_id.clone())).await;
Ok(deferred.await?)
}
@ -89,9 +85,7 @@ impl PlayerConnection {
}
pub async fn terminate(self) {
self.player_handle
.send(PlayerCommand::TerminateConnection(self.connection_id))
.await;
self.player_handle.send(PlayerCommand::TerminateConnection(self.connection_id)).await;
}
pub async fn get_rooms(&self) -> Result<Vec<RoomInfo>> {

View File

@ -180,9 +180,7 @@ impl Room {
async fn send_message(&mut self, author_id: PlayerId, body: Str) -> Result<()> {
tracing::info!("Adding a message to room");
self.storage
.insert_message(self.storage_id, self.message_count, &body, &*author_id.as_inner())
.await?;
self.storage.insert_message(self.storage_id, self.message_count, &body, &*author_id.as_inner()).await?;
self.message_count += 1;
let update = Updates::NewMessage {
room_id: self.room_id.clone(),

View File

@ -1,2 +0,0 @@
max_width = 120
chain_width = 120

View File

@ -1,2 +0,0 @@
max_width = 120
chain_width = 120

View File

@ -118,9 +118,7 @@ mod test {
assert_matches!(result, Ok((_, result)) => assert_eq!(expected, result));
let mut bytes = vec![];
sync_future(expected.write_async(&mut bytes))
.unwrap()
.unwrap();
sync_future(expected.write_async(&mut bytes)).unwrap().unwrap();
assert_eq!(bytes.as_slice(), input.as_bytes());
}
@ -134,9 +132,7 @@ mod test {
assert_matches!(result, Ok((_, result)) => assert_eq!(expected, result));
let mut bytes = vec![];
sync_future(expected.write_async(&mut bytes))
.unwrap()
.unwrap();
sync_future(expected.write_async(&mut bytes)).unwrap().unwrap();
assert_eq!(bytes.as_slice(), input.as_bytes());
}
@ -150,9 +146,7 @@ mod test {
assert_matches!(result, Ok((_, result)) => assert_eq!(expected, result));
let mut bytes = vec![];
sync_future(expected.write_async(&mut bytes))
.unwrap()
.unwrap();
sync_future(expected.write_async(&mut bytes)).unwrap().unwrap();
assert_eq!(bytes.as_slice(), input.as_bytes());
}

View File

@ -158,7 +158,7 @@ pub enum ServerMessageBody {
N904SaslFail {
nick: Str,
text: Str,
}
},
}
impl ServerMessageBody {
@ -273,11 +273,7 @@ impl ServerMessageBody {
writer.write_all(b" :").await?;
writer.write_all(msg.as_bytes()).await?;
}
ServerMessageBody::N332Topic {
client,
chat,
topic,
} => {
ServerMessageBody::N332Topic { client, chat, topic } => {
writer.write_all(b"332 ").await?;
writer.write_all(client.as_bytes()).await?;
writer.write_all(b" ").await?;
@ -315,20 +311,14 @@ impl ServerMessageBody {
writer.write_all(b" ").await?;
writer.write_all(realname.as_bytes()).await?;
}
ServerMessageBody::N353NamesReply {
client,
chan,
members,
} => {
ServerMessageBody::N353NamesReply { client, chan, members } => {
writer.write_all(b"353 ").await?;
writer.write_all(client.as_bytes()).await?;
writer.write_all(b" = ").await?;
chan.write_async(writer).await?;
writer.write_all(b" :").await?;
for member in members {
writer
.write_all(member.prefix.to_string().as_bytes())
.await?;
writer.write_all(member.prefix.to_string().as_bytes()).await?;
writer.write_all(member.nick.as_bytes()).await?;
writer.write_all(b" ").await?;
}
@ -340,11 +330,7 @@ impl ServerMessageBody {
chan.write_async(writer).await?;
writer.write_all(b" :End of /NAMES list").await?;
}
ServerMessageBody::N474BannedFromChan {
client,
chan,
message,
} => {
ServerMessageBody::N474BannedFromChan { client, chan, message } => {
writer.write_all(b"474 ").await?;
writer.write_all(client.as_bytes()).await?;
writer.write_all(b" ").await?;
@ -359,7 +345,12 @@ impl ServerMessageBody {
writer.write_all(b" :").await?;
writer.write_all(message.as_bytes()).await?;
}
ServerMessageBody::N900LoggedIn { nick, address, account, message } => {
ServerMessageBody::N900LoggedIn {
nick,
address,
account,
message,
} => {
writer.write_all(b"900 ").await?;
writer.write_all(nick.as_bytes()).await?;
writer.write_all(b" ").await?;
@ -404,7 +395,7 @@ fn server_message_body(input: &str) -> IResult<&str, ServerMessageBody> {
server_message_body_notice,
server_message_body_ping,
server_message_body_pong,
server_message_body_cap
server_message_body_cap,
))(input)
}

View File

@ -42,27 +42,19 @@ impl Display for Jid {
impl Jid {
pub fn from_string(i: &str) -> Result<Jid> {
use regex::Regex;
use lazy_static::lazy_static;
use regex::Regex;
lazy_static! {
static ref RE: Regex = Regex::new(r"^(([a-zA-Z]+)@)?([a-zA-Z.]+)(/([a-zA-Z\-]+))?$").unwrap();
}
let m = RE
.captures(i)
.ok_or(anyhow!("Incorrectly format jid: {i}"))?;
let m = RE.captures(i).ok_or(anyhow!("Incorrectly format jid: {i}"))?;
let name = m.get(2).map(|name| Name(name.as_str().into()));
let server = m.get(3).unwrap();
let server = Server(server.as_str().into());
let resource = m
.get(5)
.map(|resource| Resource(resource.as_str().into()));
let resource = m.get(5).map(|resource| Resource(resource.as_str().into()));
Ok(Jid {
name,
server,
resource,
})
Ok(Jid { name, server, resource })
}
}
@ -137,9 +129,7 @@ pub struct BindResponse(pub Jid);
impl ToXml for BindResponse {
fn serialize(&self, events: &mut Vec<Event<'static>>) {
events.extend_from_slice(&[
Event::Start(BytesStart::new(
r#"bind xmlns="urn:ietf:params:xml:ns:xmpp-bind""#,
)),
Event::Start(BytesStart::new(r#"bind xmlns="urn:ietf:params:xml:ns:xmpp-bind""#)),
Event::Start(BytesStart::new(r#"jid"#)),
Event::Text(BytesText::new(self.0.to_string().as_str()).into_owned()),
Event::End(BytesEnd::new("jid")),
@ -156,23 +146,16 @@ mod tests {
#[tokio::test]
async fn parse_message() {
let input =
r#"<bind xmlns="urn:ietf:params:xml:ns:xmpp-bind"><resource>mobile</resource></bind>"#;
let input = r#"<bind xmlns="urn:ietf:params:xml:ns:xmpp-bind"><resource>mobile</resource></bind>"#;
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 = 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);
}
}

View File

@ -2,8 +2,8 @@ use quick_xml::events::attributes::Attribute;
use quick_xml::events::{BytesEnd, BytesStart, Event};
use quick_xml::name::{QName, ResolveResult};
use anyhow::{Result, anyhow as ffail};
use crate::xml::*;
use anyhow::{anyhow as ffail, Result};
use super::bind::Jid;
@ -174,11 +174,7 @@ impl FromXml for Identity {
let Some(r#type) = r#type else {
return Err(ffail!("No type provided"));
};
let item = Identity {
category,
name,
r#type,
};
let item = Identity { category, name, r#type };
if end {
return Ok(item);
}

View File

@ -1,21 +1,16 @@
#![feature(
coroutines,
coroutine_trait,
type_alias_impl_trait,
impl_trait_in_assoc_type
)]
#![feature(coroutines, coroutine_trait, type_alias_impl_trait, impl_trait_in_assoc_type)]
pub mod bind;
pub mod client;
pub mod disco;
pub mod muc;
mod prelude;
pub mod roster;
pub mod sasl;
pub mod session;
pub mod stanzaerror;
pub mod stream;
pub mod tls;
mod prelude;
pub mod xml;
// Implemented as a macro instead of a fn due to borrowck limitations

View File

@ -52,9 +52,6 @@ impl FromXmlTag for RosterQuery {
impl ToXml for RosterQuery {
fn serialize(&self, events: &mut Vec<Event<'static>>) {
events.push(Event::Empty(BytesStart::new(format!(
r#"query xmlns="{}""#,
XMLNS
))));
events.push(Event::Empty(BytesStart::new(format!(r#"query xmlns="{}""#, XMLNS))));
}
}

View File

@ -25,9 +25,7 @@ impl Parser for SessionParser {
) -> Continuation<Self, Self::Output> {
match self.0 {
SessionParserInner::Initial => match event {
Event::Start(_) => {
Continuation::Continue(SessionParser(SessionParserInner::InSession))
}
Event::Start(_) => Continuation::Continue(SessionParser(SessionParserInner::InSession)),
Event::Empty(_) => Continuation::Final(Ok(Session)),
_ => Continuation::Final(Err(anyhow!("Unexpected XML event: {event:?}"))),
},
@ -54,9 +52,6 @@ impl FromXmlTag for Session {
impl ToXml for Session {
fn serialize(&self, events: &mut Vec<Event<'static>>) {
events.push(Event::Empty(BytesStart::new(format!(
r#"session xmlns="{}""#,
XMLNS
))));
events.push(Event::Empty(BytesStart::new(format!(r#"session xmlns="{}""#, XMLNS))));
}
}

View File

@ -6,8 +6,8 @@ use tokio::io::{AsyncBufRead, AsyncWrite};
use super::skip_text;
use anyhow::{anyhow, Result};
use crate::xml::ToXml;
use anyhow::{anyhow, Result};
pub static XMLNS: &'static str = "http://etherx.jabber.org/streams";
pub static PREFIX: &'static str = "stream";
@ -44,10 +44,7 @@ impl ClientStreamStart {
let value = attr.unescape_value()?;
to = Some(value.to_string());
}
(
ResolveResult::Bound(Namespace(b"http://www.w3.org/XML/1998/namespace")),
b"lang",
) => {
(ResolveResult::Bound(Namespace(b"http://www.w3.org/XML/1998/namespace")), b"lang") => {
let value = attr.unescape_value()?;
lang = Some(value.to_string());
}
@ -124,21 +121,15 @@ pub struct Features {
}
impl Features {
pub async fn write_xml(&self, writer: &mut Writer<impl AsyncWrite + Unpin>) -> Result<()> {
writer
.write_event_async(Event::Start(BytesStart::new("stream:features")))
.await?;
writer.write_event_async(Event::Start(BytesStart::new("stream:features"))).await?;
if self.start_tls {
writer
.write_event_async(Event::Start(BytesStart::new(
r#"starttls xmlns="urn:ietf:params:xml:ns:xmpp-tls""#,
)))
.await?;
writer
.write_event_async(Event::Empty(BytesStart::new("required")))
.await?;
writer
.write_event_async(Event::End(BytesEnd::new("starttls")))
.await?;
writer.write_event_async(Event::Empty(BytesStart::new("required"))).await?;
writer.write_event_async(Event::End(BytesEnd::new("starttls"))).await?;
}
if self.mechanisms {
writer
@ -146,18 +137,10 @@ impl Features {
r#"mechanisms xmlns="urn:ietf:params:xml:ns:xmpp-sasl""#,
)))
.await?;
writer
.write_event_async(Event::Start(BytesStart::new(r#"mechanism"#)))
.await?;
writer
.write_event_async(Event::Text(BytesText::new("PLAIN")))
.await?;
writer
.write_event_async(Event::End(BytesEnd::new("mechanism")))
.await?;
writer
.write_event_async(Event::End(BytesEnd::new("mechanisms")))
.await?;
writer.write_event_async(Event::Start(BytesStart::new(r#"mechanism"#))).await?;
writer.write_event_async(Event::Text(BytesText::new("PLAIN"))).await?;
writer.write_event_async(Event::End(BytesEnd::new("mechanism"))).await?;
writer.write_event_async(Event::End(BytesEnd::new("mechanisms"))).await?;
}
if self.bind {
writer
@ -166,9 +149,7 @@ impl Features {
)))
.await?;
}
writer
.write_event_async(Event::End(BytesEnd::new("stream:features")))
.await?;
writer.write_event_async(Event::End(BytesEnd::new("stream:features"))).await?;
Ok(())
}
}
@ -182,9 +163,7 @@ mod test {
let input = r###"<stream:stream xmlns:stream="http://etherx.jabber.org/streams" to="vlnv.dev" version="1.0" xmlns="jabber:client" xml:lang="en" xmlns:xml="http://www.w3.org/XML/1998/namespace">"###;
let mut reader = NsReader::from_reader(input.as_bytes());
let mut buf = vec![];
let res = ClientStreamStart::parse(&mut reader, &mut buf)
.await
.unwrap();
let res = ClientStreamStart::parse(&mut reader, &mut buf).await.unwrap();
assert_eq!(
res,
ClientStreamStart {

View File

@ -12,10 +12,7 @@ pub static XMLNS: &'static str = "urn:ietf:params:xml:ns:xmpp-tls";
pub struct StartTLS;
impl StartTLS {
pub async fn parse(
reader: &mut NsReader<impl AsyncBufRead + Unpin>,
buf: &mut Vec<u8>,
) -> Result<StartTLS> {
pub async fn parse(reader: &mut NsReader<impl AsyncBufRead + Unpin>, buf: &mut Vec<u8>) -> Result<StartTLS> {
let incoming = skip_text!(reader, buf);
if let Event::Empty(ref e) = incoming {
if e.name().0 == b"starttls" {

View File

@ -15,11 +15,7 @@ enum IgnoreParserInner {
impl Parser for IgnoreParser {
type Output = Result<Ignore>;
fn consume<'a>(
self: Self,
_: ResolveResult,
event: &Event<'a>,
) -> Continuation<Self, Self::Output> {
fn consume<'a>(self: Self, _: ResolveResult, event: &Event<'a>) -> Continuation<Self, Self::Output> {
match self.0 {
IgnoreParserInner::Initial => match event {
Event::Start(bytes) => {
@ -34,13 +30,7 @@ impl Parser for IgnoreParser {
if depth == 0 {
Continuation::Final(Ok(Ignore))
} else {
Continuation::Continue(
IgnoreParserInner::InTag {
name,
depth: depth - 1,
}
.into(),
)
Continuation::Continue(IgnoreParserInner::InTag { name, depth: depth - 1 }.into())
}
}
_ => Continuation::Continue(IgnoreParserInner::InTag { name, depth }.into()),

View File

@ -1,9 +1,9 @@
use std::ops::Coroutine;
use std::pin::Pin;
use quick_xml::NsReader;
use quick_xml::events::Event;
use quick_xml::name::ResolveResult;
use quick_xml::NsReader;
use anyhow::Result;
@ -28,25 +28,16 @@ pub trait FromXmlTag: FromXml {
pub trait Parser: Sized {
type Output;
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>;
}
impl<T, Out> Parser for T
where
T: Coroutine<(ResolveResult<'static>, &'static Event<'static>), Yield = (), Return = Out>
+ Unpin,
T: Coroutine<(ResolveResult<'static>, &'static Event<'static>), Yield = (), Return = Out> + Unpin,
{
type Output = Out;
fn consume<'a>(
mut self: Self,
namespace: ResolveResult,
event: &Event<'a>,
) -> Continuation<Self, Self::Output> {
fn consume<'a>(mut self: Self, namespace: ResolveResult, event: &Event<'a>) -> Continuation<Self, Self::Output> {
let s = Pin::new(&mut self);
// this is a very rude workaround fixing the fact that rust coroutines
// 1. don't support higher-kinded lifetimes (i.e. no `impl for <'a> Coroutine<Event<'a>>)

View File

@ -1 +1,2 @@
max_width = 120
chain_width = 120

View File

@ -62,7 +62,14 @@ async fn main() -> Result<()> {
storage.clone(),
)
.await?;
let xmpp = projection_xmpp::launch(xmpp_config, players.clone(), rooms.clone(), metrics.clone(), storage.clone()).await?;
let xmpp = projection_xmpp::launch(
xmpp_config,
players.clone(),
rooms.clone(),
metrics.clone(),
storage.clone(),
)
.await?;
tracing::info!("Started");
sleep.await;