diff options
Diffstat (limited to 'src')
32 files changed, 676 insertions, 489 deletions
diff --git a/src/error.rs b/src/error.rs index 3140901..79bec38 100644 --- a/src/error.rs +++ b/src/error.rs @@ -4,8 +4,12 @@ use thiserror::Error; pub enum ProtocolError { #[error("message has wrong type")] WrongMsgType, + #[error("message has unkown type")] + UnknownMsgType, #[error("bool value is neither 0 nor 1")] BoolOutOfRange, + #[error("Sync Message does not contain any more parameters")] + MissingSyncMessageParams, #[error("QVariant is not known")] UnknownVariant, #[error("UserType is not known: {0}")] @@ -20,12 +24,37 @@ pub enum ProtocolError { TryFromIntError(#[from] std::num::TryFromIntError), #[error("utf8 error: {0}")] Utf8Error(#[from] std::string::FromUtf8Error), + #[error("utf16 error: {0}")] + Utf16Error(#[from] std::string::FromUtf16Error), #[error("errored to parse char as utf16")] CharError, #[error("failed to deal with time: {0}")] TimeError(#[from] time::error::ComponentRange), + #[error("failed to parse int: {0}")] + ParseIntError(#[from] std::num::ParseIntError), + #[error("error in sync proxy: {0}")] + SyncProxyError(#[from] SyncProxyError), + #[error("got unkown HighlightNickType: {0}")] + UnknownHighlightNickType(i32), + #[error("got unkown IgnoreType: {0}")] + UnknownIgnoreType(i32), + #[error("got unkown StrictnessType: {0}")] + UnknownStrictnessType(i32), + #[error("got unkown ScopeType: {0}")] + UnknownScopeType(i32), + } +#[derive(Debug, Error)] +pub enum SyncProxyError { + #[error("SYNC_PROXY was already initialized")] + AlreadyInitialized, + #[error("SYNC_PROXY was not yet initialized")] + NotInitialized, +} + +pub type Result<T> = std::result::Result<T, ProtocolError>; + // impl std::error::Error for ErrorKind {} // // impl std::convert::From<std::io::Error> for ErrorKind { diff --git a/src/frame/mod.rs b/src/frame/mod.rs index 1c2f859..75d57ff 100644 --- a/src/frame/mod.rs +++ b/src/frame/mod.rs @@ -162,7 +162,7 @@ impl Decoder for QuasselCodec { let after_in = self.decomp.total_in(); let after_out = self.decomp.total_out(); - let len = (after_out - before_out).try_into().unwrap(); + let len = (after_out - before_out).try_into()?; // Reserve length of uncompressed stream // and put bytes into there @@ -233,7 +233,7 @@ impl Encoder<Vec<u8>> for QuasselCodec { let after_in = self.comp.total_in(); let after_out = self.comp.total_out(); - cbuf.truncate((after_out - before_out).try_into().unwrap()); + cbuf.truncate((after_out - before_out).try_into()?); *dst = BytesMut::from(&cbuf[..]); } else { *dst = buf.clone(); diff --git a/src/frame/tests.rs b/src/frame/tests.rs index 4ae5e1a..69c27a6 100644 --- a/src/frame/tests.rs +++ b/src/frame/tests.rs @@ -111,7 +111,7 @@ fn quasselcodec_read_oversized() { ); tokio_test::block_on(async move { - let res = io.next().await.unwrap().map_err(|e| e.kind()); + let res = io.next().await?.map_err(|e| e.kind()); let want = Err(std::io::ErrorKind::InvalidData); assert_eq!(want, res); @@ -170,7 +170,7 @@ fn write_single_frame() { ); tokio_test::block_on(async move { - io.send(b"abcdefghi".to_vec()).await.unwrap(); + io.send(b"abcdefghi".to_vec()).await?; }); } @@ -188,9 +188,9 @@ fn write_multi_frame() { ); tokio_test::block_on(async move { - io.send(b"abcdefghi".to_vec()).await.unwrap(); - io.send(b"123".to_vec()).await.unwrap(); - io.send(b"hello world".to_vec()).await.unwrap(); + io.send(b"abcdefghi".to_vec()).await?; + io.send(b"123".to_vec()).await?; + io.send(b"hello world".to_vec()).await?; }); } @@ -206,6 +206,6 @@ fn write_single_frame_compressed() { ); tokio_test::block_on(async move { - io.send(b"abcdefghi".to_vec()).await.unwrap(); + io.send(b"abcdefghi".to_vec()).await?; }); } @@ -32,7 +32,7 @@ pub mod frame; #[cfg(all(feature = "client", feature = "server"))] compile_error!("feature \"client\" and feature \"server\" cannot be enabled at the same time"); -pub use crate::error::ProtocolError; +pub use crate::error::{ProtocolError, Result, SyncProxyError}; /// Traits for Serialization & Deserialization of objects pub mod serialize; @@ -41,14 +41,14 @@ pub mod serialize; /// /// The protocol has some minor differences during this phase compared to the regular parsing. pub trait HandshakeSerialize { - fn serialize(&self) -> Result<Vec<u8>, ProtocolError>; + fn serialize(&self) -> Result<Vec<u8>>; } /// HandshakeDeserialize implements the deserialization needed during the handhake phase. /// /// The protocol has some minor differences during this phase compared to the regular parsing. pub trait HandshakeDeserialize { - fn parse(b: &[u8]) -> Result<(usize, Self), ProtocolError> + fn parse(b: &[u8]) -> Result<(usize, Self)> where Self: std::marker::Sized; } diff --git a/src/message/handshake/init.rs b/src/message/handshake/init.rs index e303802..33c6fbb 100644 --- a/src/message/handshake/init.rs +++ b/src/message/handshake/init.rs @@ -1,4 +1,7 @@ -use crate::serialize::{Deserialize, Serialize}; +use crate::{ + serialize::{Deserialize, Serialize}, + ProtocolError, +}; /// The first few bytes sent to the core to initialize the connection and setup if we want to use tls and compression #[derive(Clone, Debug, Default)] @@ -22,7 +25,7 @@ impl Init { self } - pub fn serialize(self) -> Vec<u8> { + pub fn serialize(self) -> Result<Vec<u8>, ProtocolError> { // The handshake message let mut handshake: u32 = 0x42b33f00; @@ -41,14 +44,14 @@ impl Init { let mut init: Vec<u8> = vec![]; // Add handshake and protocol to our buffer - init.extend(handshake.serialize().unwrap()); - init.extend(crate::message::Protocol::Datastream.serialize()); + init.extend(handshake.serialize()?); + init.extend(crate::message::Protocol::Datastream.serialize()?); - init + Ok(init) } - pub fn parse(buf: &[u8]) -> Self { - let (_, handshake) = u32::parse(&buf[0..4]).unwrap(); + pub fn parse(buf: &[u8]) -> Result<Self, ProtocolError> { + let (_, handshake) = u32::parse(&buf[0..4])?; let mut init = Self { tls: false, @@ -63,6 +66,6 @@ impl Init { init.tls = true } - init + Ok(init) } } diff --git a/src/message/handshake/protocol.rs b/src/message/handshake/protocol.rs index 2a7d9ac..0dc419f 100644 --- a/src/message/handshake/protocol.rs +++ b/src/message/handshake/protocol.rs @@ -1,4 +1,7 @@ -use crate::serialize::{Deserialize, Serialize}; +use crate::{ + serialize::{Deserialize, Serialize}, + ProtocolError, +}; #[derive(Debug, Default)] pub enum Protocol { @@ -12,17 +15,17 @@ impl Protocol { Protocol::default() } - pub fn serialize(self) -> Vec<u8> { + pub fn serialize(self) -> Result<Vec<u8>, ProtocolError> { let proto: u32 = 0x80000002; - proto.serialize().unwrap() + proto.serialize() } - pub fn parse(buf: &[u8]) -> Self { + pub fn parse(buf: &[u8]) -> Result<Self, ProtocolError> { let mut protolist: Vec<u32> = Vec::new(); let mut pos = 0; loop { - let (_, proto) = u32::parse(&buf[pos..(pos + 4)]).unwrap(); + let (_, proto) = u32::parse(&buf[pos..(pos + 4)])?; if (proto & 0x80000000) >= 1 { protolist.push(proto - 0x80000000); break; @@ -32,6 +35,6 @@ impl Protocol { } } - Protocol::Datastream + Ok(Protocol::Datastream) } } diff --git a/src/message/handshake/types.rs b/src/message/handshake/types.rs index 9bd8aec..91248c4 100644 --- a/src/message/handshake/types.rs +++ b/src/message/handshake/types.rs @@ -19,7 +19,7 @@ impl HandshakeSerialize for VariantMap { res.extend(v.serialize()?); } - let len: i32 = (self.len() * 2).try_into().unwrap(); + let len: i32 = (self.len() * 2).try_into()?; util::insert_bytes(0, &mut res, &mut (len).to_be_bytes()); Ok(res) diff --git a/src/message/signalproxy/mod.rs b/src/message/signalproxy/mod.rs index 7e36017..727fd06 100644 --- a/src/message/signalproxy/mod.rs +++ b/src/message/signalproxy/mod.rs @@ -1,8 +1,7 @@ use crate::{ - error::ProtocolError, + error::{ProtocolError, SyncProxyError}, primitive::{Variant, VariantList}, - serialize::Deserialize, - serialize::Serialize, + serialize::{Deserialize, Serialize}, }; use rpccall::RpcCall; @@ -27,6 +26,8 @@ pub use syncmessage::*; use once_cell::sync::OnceCell; +use crate::error::Result; + pub static SYNC_PROXY: OnceCell<SyncProxy> = OnceCell::new(); #[derive(Debug, Clone)] @@ -41,10 +42,10 @@ impl SyncProxy { /// Initialize the global SYNC_PROXY object and return receiver ends for the SyncMessage and RpcCall channels pub fn init( cap: usize, - ) -> ( + ) -> Result<( crossbeam_channel::Receiver<SyncMessage>, crossbeam_channel::Receiver<RpcCall>, - ) { + )> { let (sync_tx, sync_rx) = crossbeam_channel::bounded(cap); let (rpc_tx, rpc_rx) = crossbeam_channel::bounded(cap); @@ -53,13 +54,19 @@ impl SyncProxy { sync_channel: sync_tx, rpc_channel: rpc_tx, }) - .unwrap(); + .map_err(|_| SyncProxyError::AlreadyInitialized)?; - (sync_rx, rpc_rx) + Ok((sync_rx, rpc_rx)) } /// Send a SyncMessage - fn sync(&self, class_name: Class, object_name: Option<&str>, function: &str, params: VariantList) { + fn sync( + &self, + class_name: Class, + object_name: Option<&str>, + function: &str, + params: VariantList, + ) -> Result<()> { let msg = SyncMessage { class_name, object_name: object_name.unwrap_or("").to_string(), @@ -68,7 +75,11 @@ impl SyncProxy { }; debug!("submitting {:#?}", msg); - self.sync_channel.send(msg).unwrap(); + self.sync_channel + .send(msg) + .map_err(|_| SyncProxyError::AlreadyInitialized)?; + + Ok(()) } /// Send an RpcCall @@ -86,19 +97,19 @@ pub trait Syncable { const CLASS: Class; /// Send a SyncMessage. - fn send_sync(&self, function: &str, params: VariantList) { + fn send_sync(&self, function: &str, params: VariantList) -> Result<()> { crate::message::signalproxy::SYNC_PROXY - .get() - .unwrap() - .sync(Self::CLASS, None, function, params); + .get().ok_or(SyncProxyError::NotInitialized)? + .sync(Self::CLASS, None, function, params)?; + Ok(()) } /// Send a RpcCall - fn send_rpc(&self, function: &str, params: VariantList) { + fn send_rpc(&self, function: &str, params: VariantList) -> Result<()> { crate::message::signalproxy::SYNC_PROXY - .get() - .unwrap() + .get().ok_or(SyncProxyError::NotInitialized)? .rpc(function, params); + Ok(()) } fn init(&mut self, data: Self) @@ -114,7 +125,7 @@ pub trait StatefulSyncableServer: Syncable + translation::NetworkMap where Variant: From<<Self as translation::NetworkMap>::Item>, { - fn sync(&mut self, mut msg: crate::message::SyncMessage) -> Result<(), ProtocolError> + fn sync(&mut self, mut msg: crate::message::SyncMessage) -> Result<()> where Self: Sized, { @@ -131,7 +142,7 @@ where } #[allow(unused_mut)] - fn sync_custom(&mut self, mut msg: crate::message::SyncMessage) -> Result<(), ProtocolError> + fn sync_custom(&mut self, mut msg: crate::message::SyncMessage) -> Result<()> where Self: Sized, { @@ -142,18 +153,15 @@ where } /// Client -> Server: Update the whole object with received data - fn update(&mut self) + fn update(&mut self) -> Result<()> where Self: Sized, { - self.send_sync("update", vec![self.to_network_map().into()]); + self.send_sync("update", vec![self.to_network_map().into()]) } /// Server -> Client: Update the whole object with received data - fn request_update( - &mut self, - mut param: <Self as translation::NetworkMap>::Item, - ) -> Result<(), ProtocolError> + fn request_update(&mut self, mut param: <Self as translation::NetworkMap>::Item) -> Result<()> where Self: Sized, { @@ -164,7 +172,7 @@ where /// Methods for a Stateful Syncable object on the server side. pub trait StatefulSyncableClient: Syncable + translation::NetworkMap { - fn sync(&mut self, mut msg: crate::message::SyncMessage) -> Result<(), ProtocolError> + fn sync(&mut self, mut msg: crate::message::SyncMessage) -> Result<()> where Self: Sized, { @@ -181,7 +189,7 @@ pub trait StatefulSyncableClient: Syncable + translation::NetworkMap { } #[allow(unused_mut)] - fn sync_custom(&mut self, mut msg: crate::message::SyncMessage) -> Result<(), ProtocolError> + fn sync_custom(&mut self, mut msg: crate::message::SyncMessage) -> Result<()> where Self: Sized, { @@ -192,7 +200,7 @@ pub trait StatefulSyncableClient: Syncable + translation::NetworkMap { } /// Client -> Server: Update the whole object with received data - fn update(&mut self, mut param: <Self as translation::NetworkMap>::Item) -> Result<(), ProtocolError> + fn update(&mut self, mut param: <Self as translation::NetworkMap>::Item) -> Result<()> where Self: Sized, { @@ -201,11 +209,11 @@ pub trait StatefulSyncableClient: Syncable + translation::NetworkMap { } /// Server -> Client: Update the whole object with received data - fn request_update(&mut self) + fn request_update(&mut self) -> Result<()> where Self: Sized, { - self.send_sync("requestUpdate", vec![self.to_network_map().into()]); + self.send_sync("requestUpdate", vec![self.to_network_map().into()]) } } @@ -237,7 +245,7 @@ pub enum Message { // } impl Serialize for Message { - fn serialize(&self) -> Result<Vec<std::primitive::u8>, ProtocolError> { + fn serialize(&self) -> Result<Vec<std::primitive::u8>> { match &self { Message::SyncMessage(value) => value.serialize(), Message::RpcCall(value) => value.serialize(), @@ -250,7 +258,7 @@ impl Serialize for Message { } impl Deserialize for Message { - fn parse(b: &[std::primitive::u8]) -> Result<(std::primitive::usize, Self), ProtocolError> { + fn parse(b: &[std::primitive::u8]) -> Result<(std::primitive::usize, Self)> { let (_, message_type) = i32::parse(&b[9..13])?; match MessageType::from(message_type) { diff --git a/src/message/signalproxy/objects/aliasmanager.rs b/src/message/signalproxy/objects/aliasmanager.rs index 7b98426..df60987 100644 --- a/src/message/signalproxy/objects/aliasmanager.rs +++ b/src/message/signalproxy/objects/aliasmanager.rs @@ -14,6 +14,7 @@ use crate::message::Syncable; #[allow(unused_imports)] use crate::primitive::VariantMap; +use crate::Result; /// AliasManager /// keeps a list of all registered aliases @@ -25,13 +26,15 @@ pub struct AliasManager { } impl AliasManager { - pub fn add_alias(&mut self, alias: Alias) { + pub fn add_alias(&mut self, alias: Alias) -> Result<()> { #[cfg(feature = "server")] - sync!("addAlias", [alias.to_network_map()]); + sync!("addAlias", [alias.to_network_map()])?; if !self.aliases.contains(&alias) { self.aliases.push(alias) } + + Ok(()) } } @@ -40,17 +43,18 @@ impl StatefulSyncableClient for AliasManager {} #[cfg(feature = "server")] impl StatefulSyncableServer for AliasManager { - fn sync_custom(&mut self, mut msg: crate::message::SyncMessage) -> Result<(), crate::error::ProtocolError> + fn sync_custom(&mut self, mut msg: crate::message::SyncMessage) -> crate::Result<()> where Self: Sized, { match msg.slot_name.as_str() { - "addAlias" => self.add_alias(Alias::from_network_map( - &mut VariantMap::try_from(msg.params.pop().unwrap()).unwrap(), - )), - _ => (), + "addAlias" => self.add_alias(Alias::from_network_map(&mut VariantMap::try_from( + msg.params + .pop() + .ok_or(crate::ProtocolError::MissingSyncMessageParams)?, + )?)), + _ => Ok(()), } - Ok(()) } } @@ -123,11 +127,14 @@ mod tests { #[test] fn aliasmanager_to_network() { - assert_eq!(get_src().to_network_list(), get_dest()) + assert_eq!(get_src().to_network_list().unwrap(), get_dest()) } #[test] fn aliasmanager_from_network() { - assert_eq!(AliasManager::from_network_list(&mut get_dest()), get_src()) + assert_eq!( + AliasManager::from_network_list(&mut get_dest()).unwrap(), + get_src() + ) } } diff --git a/src/message/signalproxy/objects/backlogmanager.rs b/src/message/signalproxy/objects/backlogmanager.rs index dbf4697..bad0e5d 100644 --- a/src/message/signalproxy/objects/backlogmanager.rs +++ b/src/message/signalproxy/objects/backlogmanager.rs @@ -55,6 +55,7 @@ use libquassel_derive::{sync, NetworkMap}; use crate::message::{Class, Syncable}; use crate::primitive::{BufferId, MessageType, MsgId, VariantList}; +use crate::Result; /// Receive and Request Backlog /// All "request" functions are Client to Server and all "receive" functions are Server to Client @@ -73,8 +74,8 @@ impl BacklogManager { last: MsgId, limit: i32, additional: i32, - ) { - sync!("requestBacklog", [buffer_id, first, last, limit, additional]); + ) -> Result<()> { + sync!("requestBacklog", [buffer_id, first, last, limit, additional]) } /// Same as `requestBacklog`, but only messages of a certain message `type` @@ -88,16 +89,16 @@ impl BacklogManager { additional: i32, msgtype: MessageType, flags: i32, - ) { + ) -> Result<()> { sync!( "requestBacklogFiltered", [buffer_id, first, last, limit, additional, msgtype.bits(), flags] - ); + ) } /// Same as `requestBacklog`, but applied to all buffers. - pub fn requestBacklogAll(&self, first: MsgId, last: MsgId, limit: i32, additional: i32) { - sync!("requestBacklogAll", [first, last, limit, additional]); + pub fn requestBacklogAll(&self, first: MsgId, last: MsgId, limit: i32, additional: i32) -> Result<()> { + sync!("requestBacklogAll", [first, last, limit, additional]) } /// Same as `requestBacklogFiltered`, but applied to all buffers. @@ -109,11 +110,11 @@ impl BacklogManager { additional: i32, msgtype: MessageType, flags: i32, - ) { + ) -> Result<()> { sync!( "requestBacklogAllFiltered", [first, last, limit, additional, msgtype.bits(), flags] - ); + ) } /// The response to `requestBacklog`, with the messages encoded as Variants @@ -126,11 +127,11 @@ impl BacklogManager { limit: i32, additional: i32, messages: VariantList, - ) { + ) -> Result<()> { sync!( "receiveBacklog", [buffer_id, first, last, limit, additional, messages] - ); + ) } /// The response to `requestBacklogFiltered`, with the messages encoded as @@ -145,7 +146,7 @@ impl BacklogManager { msgtype: MessageType, flags: i32, messages: VariantList, - ) { + ) -> Result<()> { sync!( "receiveBacklogFiltered", [ @@ -158,7 +159,7 @@ impl BacklogManager { flags, messages ] - ); + ) } /// Same as `receiveBacklog`, but applied to all buffers. @@ -169,8 +170,8 @@ impl BacklogManager { limit: i32, additional: i32, messages: VariantList, - ) { - sync!("receiveBacklogAll", [first, last, limit, additional, messages]); + ) -> Result<()> { + sync!("receiveBacklogAll", [first, last, limit, additional, messages]) } /// Same as `receiveBacklogFiltered`, but applied to all buffers. @@ -183,11 +184,11 @@ impl BacklogManager { msgtype: MessageType, flags: i32, messages: VariantList, - ) { + ) -> Result<()> { sync!( "receiveBacklogAllFiltered", [first, last, limit, additional, msgtype.bits(), flags, messages] - ); + ) } } diff --git a/src/message/signalproxy/objects/buffersyncer.rs b/src/message/signalproxy/objects/buffersyncer.rs index 22a435d..5e8b8e7 100644 --- a/src/message/signalproxy/objects/buffersyncer.rs +++ b/src/message/signalproxy/objects/buffersyncer.rs @@ -1,9 +1,9 @@ use std::collections::HashMap; use crate::{ - error::ProtocolError, message::{Class, Syncable}, primitive::{BufferId, MessageType, MsgId}, + Result, }; use libquassel_derive::{sync, NetworkList, NetworkMap}; @@ -21,45 +21,48 @@ pub struct BufferSyncer { } impl BufferSyncer { - pub fn request_mark_buffer_as_read(&mut self, id: i32) { - sync!("requestMarkBufferAsRead", [id]); + pub fn request_mark_buffer_as_read(&mut self, id: i32) -> Result<()> { + sync!("requestMarkBufferAsRead", [id]) } - pub fn request_merge_buffers_permanently(&self, src_id: i32, target_id: i32) { - sync!("requestMergeBuffersPermanently", [src_id, target_id]); + pub fn request_merge_buffers_permanently(&self, src_id: i32, target_id: i32) -> Result<()> { + sync!("requestMergeBuffersPermanently", [src_id, target_id]) } - pub fn request_purge_buffer_ids(&self) { - sync!("requestPurgeBufferIds", []); + pub fn request_purge_buffer_ids(&self) -> Result<()> { + sync!("requestPurgeBufferIds", []) } - pub fn request_remove_buffer(&self, id: i32) { - sync!("requestRemoveBuffer", [id]); + pub fn request_remove_buffer(&self, id: i32) -> Result<()> { + sync!("requestRemoveBuffer", [id]) } - pub fn request_rename_buffer(&self, id: i32) { - sync!("requestRenameBuffer", [id]); + pub fn request_rename_buffer(&self, id: i32) -> Result<()> { + sync!("requestRenameBuffer", [id]) } - pub fn request_set_last_seen_msg(&self, id: i32, msgid: i32) { - sync!("requestSetLastSeenMsg", [id, msgid]); + pub fn request_set_last_seen_msg(&self, id: i32, msgid: i32) -> Result<()> { + sync!("requestSetLastSeenMsg", [id, msgid]) } - pub fn request_set_marker_line(&self, id: i32, msgid: i32) { - sync!("requestSetMarkerLine", [id, msgid]); + pub fn request_set_marker_line(&self, id: i32, msgid: i32) -> Result<()> { + sync!("requestSetMarkerLine", [id, msgid]) } // // S->C calls - pub fn mark_buffer_as_read(&mut self, id: BufferId) { - self.set_buffer_activity(id, MessageType::NONE); - self.set_highlight_count(id, 0); + pub fn mark_buffer_as_read(&mut self, id: BufferId) -> Result<()> { + self.set_buffer_activity(id, MessageType::NONE)?; + self.set_highlight_count(id, 0)?; #[cfg(feature = "server")] - sync!("markBufferAsRead", [id]); + return sync!("markBufferAsRead", [id]); + + #[cfg(feature = "client")] + return Ok(()); } - pub fn merge_buffers_permanently(&mut self, target: BufferId, source: BufferId) { + pub fn merge_buffers_permanently(&mut self, target: BufferId, source: BufferId) -> Result<()> { if let Some(activities) = self.activities.remove(&source) { *self.activities.entry(target).or_insert(MessageType::NONE) |= activities; } @@ -83,60 +86,81 @@ impl BufferSyncer { } #[cfg(feature = "server")] - sync!("mergeBuffersPermanently", [source, target]); + return sync!("mergeBuffersPermanently", [source, target]); + + #[cfg(feature = "client")] + return Ok(()); } // TODO remove buffer from bufferviews - pub fn remove_buffer(&mut self, id: BufferId) { + pub fn remove_buffer(&mut self, id: BufferId) -> Result<()> { self.activities.remove(&id); self.highlight_counts.remove(&id); self.last_seen_msg.remove(&id); self.marker_line.remove(&id); #[cfg(feature = "server")] - sync!("removeBuffer", [id]); + return sync!("removeBuffer", [id]); + + #[cfg(feature = "client")] + return Ok(()); } // TODO actually rename the buffer in whereever we should store buffers // and the BufferView #[allow(unused_variables)] - pub fn rename_buffer(&mut self, id: i32, name: String) { + pub fn rename_buffer(&mut self, id: i32, name: String) -> Result<()> { #[cfg(feature = "server")] - sync!("renameBuffer", [id, name]); + return sync!("renameBuffer", [id, name]); + + #[cfg(feature = "client")] + return Ok(()); } - pub fn set_buffer_activity(&mut self, id: BufferId, activity: MessageType) { + pub fn set_buffer_activity(&mut self, id: BufferId, activity: MessageType) -> Result<()> { *self.activities.entry(id).or_insert(MessageType::NONE) = activity; #[cfg(feature = "server")] - sync!("setBufferActivity", [id, activity.bits()]); + return sync!("setBufferActivity", [id, activity.bits()]); + + #[cfg(feature = "client")] + return Ok(()); } - pub fn set_highlight_count(&mut self, id: BufferId, count: i32) { + pub fn set_highlight_count(&mut self, id: BufferId, count: i32) -> Result<()> { *self.highlight_counts.entry(id).or_default() = count; #[cfg(feature = "server")] - sync!("setHighlightCount", [id, count]); + return sync!("setHighlightCount", [id, count]); + + #[cfg(feature = "client")] + return Ok(()); } - pub fn set_last_seen_msg(&mut self, id: BufferId, msg_id: MsgId) { + pub fn set_last_seen_msg(&mut self, id: BufferId, msg_id: MsgId) -> Result<()> { *self.last_seen_msg.entry(id).or_default() = msg_id; #[cfg(feature = "server")] - sync!("setHighlightCount", [id, msg_id]); + return sync!("setHighlightCount", [id, msg_id]); + + #[cfg(feature = "client")] + return Ok(()); } - pub fn set_marker_line(&mut self, id: BufferId, msg_id: MsgId) { + pub fn set_marker_line(&mut self, id: BufferId, msg_id: MsgId) -> Result<()> { *self.marker_line.entry(id).or_default() = msg_id; #[cfg(feature = "server")] - sync!("setHighlightCount", [id, msg_id]); + return sync!("setHighlightCount", [id, msg_id]); + + #[cfg(feature = "client")] + return Ok(()); } } #[cfg(feature = "client")] impl crate::message::StatefulSyncableClient for BufferSyncer { - fn sync_custom(&mut self, mut msg: crate::message::SyncMessage) -> Result<(), ProtocolError> + fn sync_custom(&mut self, mut msg: crate::message::SyncMessage) -> Result<()> where Self: Sized, { @@ -152,15 +176,14 @@ impl crate::message::StatefulSyncableClient for BufferSyncer { "setHighlightCount" => self.set_highlight_count(get_param!(msg), get_param!(msg)), "setLastSeenMsg" => self.set_last_seen_msg(get_param!(msg), get_param!(msg)), "setMarkerLine" => self.set_marker_line(get_param!(msg), get_param!(msg)), - _ => (), + _ => Ok(()), } - Ok(()) } } #[cfg(feature = "server")] impl crate::message::StatefulSyncableServer for BufferSyncer { - fn sync_custom(&mut self, mut msg: crate::message::SyncMessage) -> Result<(), ProtocolError> + fn sync_custom(&mut self, mut msg: crate::message::SyncMessage) -> Result<()> where Self: Sized, { @@ -169,14 +192,13 @@ impl crate::message::StatefulSyncableServer for BufferSyncer { "requestMergeBuffersPermanently" => { self.merge_buffers_permanently(get_param!(msg), get_param!(msg)) } - "requestPurgeBufferIds" => (), + "requestPurgeBufferIds" => Ok(()), "requestRemoveBuffer" => self.remove_buffer(get_param!(msg)), "requestRenameBuffer" => self.rename_buffer(get_param!(msg), get_param!(msg)), "requestSetLastSeenMsg" => self.set_last_seen_msg(get_param!(msg), get_param!(msg)), "requestSetMarkerLine" => self.set_marker_line(get_param!(msg), get_param!(msg)), - _ => (), + _ => Ok(()), } - Ok(()) } } @@ -289,6 +311,9 @@ mod tests { #[test] fn buffersyncer_from_network() { - assert_eq!(BufferSyncer::from_network_list(&mut get_network()), get_runtime()) + assert_eq!( + BufferSyncer::from_network_list(&mut get_network()).unwrap(), + get_runtime() + ) } } diff --git a/src/message/signalproxy/objects/bufferviewconfig.rs b/src/message/signalproxy/objects/bufferviewconfig.rs index ade5bc5..9c7f6fc 100644 --- a/src/message/signalproxy/objects/bufferviewconfig.rs +++ b/src/message/signalproxy/objects/bufferviewconfig.rs @@ -8,6 +8,7 @@ use crate::message::StatefulSyncableServer; use crate::message::{Class, Syncable}; use crate::primitive::{BufferId, NetworkId, VariantList}; +use crate::{Result, SyncProxyError}; #[derive(Debug, Default, Clone, PartialEq, NetworkList, NetworkMap)] pub struct BufferViewConfig { @@ -49,11 +50,11 @@ pub struct BufferViewConfig { #[allow(dead_code)] impl BufferViewConfig { - pub fn request_add_buffer(&self, id: BufferId, pos: usize) { - sync!("requestAddBuffer", [id, (pos as i32)]); + pub fn request_add_buffer(&self, id: BufferId, pos: usize) -> Result<()> { + sync!("requestAddBuffer", [id, (pos as i32)]) } - pub fn add_buffer(&mut self, id: BufferId, pos: usize) { + pub fn add_buffer(&mut self, id: BufferId, pos: usize) -> Result<()> { if !self.buffers.contains(&id) { self.buffers.insert(pos, id) } @@ -67,27 +68,33 @@ impl BufferViewConfig { } #[cfg(feature = "server")] - sync!("addBuffer", [id, (pos as i32)]); + return sync!("addBuffer", [id, (pos as i32)]); + + #[cfg(feature = "client")] + return Ok(()); } - pub fn request_move_buffer(&self, id: BufferId, pos: usize) { - sync!("requestMoveBuffer", [id, (pos as i32)]); + pub fn request_move_buffer(&self, id: BufferId, pos: usize) -> Result<()> { + sync!("requestMoveBuffer", [id, (pos as i32)]) } - pub fn move_buffer(&mut self, id: BufferId, pos: usize) { + pub fn move_buffer(&mut self, id: BufferId, pos: usize) -> Result<()> { let old_pos = self.buffers.iter().position(|&x| x == id).unwrap(); self.buffers.remove(old_pos); self.buffers.insert(pos, id); #[cfg(feature = "server")] - sync!("moveBuffer", [id, (pos as i32)]); + return sync!("moveBuffer", [id, (pos as i32)]); + + #[cfg(feature = "client")] + return Ok(()); } - pub fn request_remove_buffer(&mut self, id: BufferId) { - sync!("requestRemoveBuffer", [id]); + pub fn request_remove_buffer(&mut self, id: BufferId) -> Result<()> { + sync!("requestRemoveBuffer", [id]) } - pub fn remove_buffer(&mut self, id: BufferId) { + pub fn remove_buffer(&mut self, id: BufferId) -> Result<()> { if let Some(old_pos) = self.buffers.iter().position(|&x| x == id) { self.buffers.remove(old_pos); } @@ -101,14 +108,17 @@ impl BufferViewConfig { } #[cfg(feature = "server")] - sync!("removeBuffer", [id]); + return sync!("removeBuffer", [id]); + + #[cfg(feature = "client")] + return Ok(()); } - pub fn request_remove_buffer_permanently(&mut self, id: BufferId) { - sync!("requestRemoveBufferPermanently", [id]); + pub fn request_remove_buffer_permanently(&mut self, id: BufferId) -> Result<()> { + sync!("requestRemoveBufferPermanently", [id]) } - pub fn remove_buffer_permanently(&mut self, id: BufferId) { + pub fn remove_buffer_permanently(&mut self, id: BufferId) -> Result<()> { if let Some(old_pos) = self.buffers.iter().position(|&x| x == id) { self.buffers.remove(old_pos); } @@ -122,69 +132,67 @@ impl BufferViewConfig { } #[cfg(feature = "server")] - sync!("removeBufferPermanently", [id]); + return sync!("removeBufferPermanently", [id]); + + #[cfg(feature = "client")] + return Ok(()); } } #[cfg(feature = "client")] impl StatefulSyncableClient for BufferViewConfig { - fn sync_custom(&mut self, mut msg: crate::message::SyncMessage) -> Result<(), crate::error::ProtocolError> + fn sync_custom(&mut self, mut msg: crate::message::SyncMessage) -> Result<()> where Self: Sized, { log::debug!("entering bufferviewconfig sync_custom()"); match msg.slot_name.as_str() { "addBuffer" => self.add_buffer( - msg.params.remove(0).try_into().unwrap(), - i32::try_from(msg.params.remove(0)).unwrap() as usize, + msg.params.remove(0).try_into()?, + i32::try_from(msg.params.remove(0))? as usize, ), "moveBuffer" => self.move_buffer( - msg.params.remove(0).try_into().unwrap(), - i32::try_from(msg.params.remove(0)).unwrap() as usize, + msg.params.remove(0).try_into()?, + i32::try_from(msg.params.remove(0))? as usize, ), - "removeBuffer" => self.remove_buffer(msg.params.remove(0).try_into().unwrap()), - "removeBufferPermanently" => { - self.remove_buffer_permanently(msg.params.remove(0).try_into().unwrap()) - } - _ => (), + "removeBuffer" => self.remove_buffer(msg.params.remove(0).try_into()?), + "removeBufferPermanently" => self.remove_buffer_permanently(msg.params.remove(0).try_into()?), + _ => Ok(()), } - Ok(()) } } #[cfg(feature = "server")] impl StatefulSyncableServer for BufferViewConfig { - fn sync_custom(&mut self, mut msg: crate::message::SyncMessage) -> Result<(), crate::error::ProtocolError> + fn sync_custom(&mut self, mut msg: crate::message::SyncMessage) -> Result<()> where Self: Sized, { match msg.slot_name.as_str() { "requestAddBuffer" => self.add_buffer( - msg.params.remove(0).try_into().unwrap(), - i32::try_from(msg.params.remove(0)).unwrap() as usize, - ), + msg.params.remove(0).try_into()?, + i32::try_from(msg.params.remove(0))? as usize, + )?, "requestMoveBuffer" => self.move_buffer( - msg.params.remove(0).try_into().unwrap(), - i32::try_from(msg.params.remove(0)).unwrap() as usize, - ), - "requestRemoveBuffer" => self.remove_buffer(msg.params.remove(0).try_into().unwrap()), + msg.params.remove(0).try_into()?, + i32::try_from(msg.params.remove(0))? as usize, + )?, + "requestRemoveBuffer" => self.remove_buffer(msg.params.remove(0).try_into()?)?, "requestRemoveBufferPermanently" => { - self.remove_buffer_permanently(msg.params.remove(0).try_into().unwrap()) + self.remove_buffer_permanently(msg.params.remove(0).try_into()?)? } "setAddNewBuffersAutomatically" => { - self.add_new_buffers_automatically = msg.params.remove(0).try_into().unwrap() + self.add_new_buffers_automatically = msg.params.remove(0).try_into()? } - "setAllowedBufferTypes" => self.allowed_buffer_types = msg.params.remove(0).try_into().unwrap(), - "setBufferViewName" => self.buffer_view_name = msg.params.remove(0).try_into().unwrap(), - "setDisableDecoration" => self.disable_decoration = msg.params.remove(0).try_into().unwrap(), - "setHideInactiveBuffers" => self.hide_inactive_buffers = msg.params.remove(0).try_into().unwrap(), - "setHideInactiveNetworks" => { - self.hide_inactive_networks = msg.params.remove(0).try_into().unwrap() - } - "setMinimumActivity" => self.minimum_activity = msg.params.remove(0).try_into().unwrap(), - "setNetworkId" => self.network_id = msg.params.remove(0).try_into().unwrap(), - "setShowSearch" => self.show_search = msg.params.remove(0).try_into().unwrap(), - "setSortAlphabetically" => self.sort_alphabetically = msg.params.remove(0).try_into().unwrap(), + "setAllowedBufferTypes" => self.allowed_buffer_types = msg.params.remove(0).try_into()?, + "setBufferViewName" => self.buffer_view_name = msg.params.remove(0).try_into()?, + "setDisableDecoration" => self.disable_decoration = msg.params.remove(0).try_into()?, + "setHideInactiveBuffers" => self.hide_inactive_buffers = msg.params.remove(0).try_into()?, + "setHideInactiveNetworks" => self.hide_inactive_networks = msg.params.remove(0).try_into()?, + "setMinimumActivity" => self.minimum_activity = msg.params.remove(0).try_into()?, + "setNetworkId" => self.network_id = msg.params.remove(0).try_into()?, + "setShowSearch" => self.show_search = msg.params.remove(0).try_into()?, + "setSortAlphabetically" => self.sort_alphabetically = msg.params.remove(0).try_into()?, _ => (), } Ok(()) @@ -194,13 +202,16 @@ impl StatefulSyncableServer for BufferViewConfig { impl Syncable for BufferViewConfig { const CLASS: Class = Class::BufferViewConfig; - fn send_sync(&self, function: &str, params: VariantList) { - crate::message::signalproxy::SYNC_PROXY.get().unwrap().sync( - Self::CLASS, - Some(&self.buffer_view_id.to_string()), - function, - params, - ); + fn send_sync(&self, function: &str, params: VariantList) -> Result<()> { + crate::message::signalproxy::SYNC_PROXY + .get() + .ok_or(SyncProxyError::NotInitialized)? + .sync( + Self::CLASS, + Some(&self.buffer_view_id.to_string()), + function, + params, + ) } } @@ -221,12 +232,12 @@ mod tests { fn bufferviewconfig_add_buffer() { // Add existing buffer, no change let mut buffer_view_config = bufferviewconfig_sample(); - buffer_view_config.add_buffer(1.into(), 2); + buffer_view_config.add_buffer(1.into(), 2).unwrap(); assert_eq!(bufferviewconfig_sample(), buffer_view_config); // Add new buffer let mut buffer_view_config = bufferviewconfig_sample(); - buffer_view_config.add_buffer(10.into(), 1); + buffer_view_config.add_buffer(10.into(), 1).unwrap(); assert_eq!( BufferViewConfig { buffers: vec![1.into(), 10.into(), 2.into(), 3.into()], @@ -244,7 +255,7 @@ mod tests { temporarily_removed_buffers: vec![6.into(), 7.into(), 10.into()], ..Default::default() }; - buffer_view_config.add_buffer(10.into(), 1); + buffer_view_config.add_buffer(10.into(), 1).unwrap(); assert_eq!( BufferViewConfig { buffers: vec![1.into(), 10.into(), 2.into(), 3.into()], @@ -260,12 +271,12 @@ mod tests { fn bufferviewconfig_remove_buffer() { // Remove already removed buffer let mut buffer_view_config = bufferviewconfig_sample(); - buffer_view_config.remove_buffer(6.into()); + buffer_view_config.remove_buffer(6.into()).unwrap(); assert_eq!(bufferviewconfig_sample(), buffer_view_config); // Remove buffer let mut buffer_view_config = bufferviewconfig_sample(); - buffer_view_config.remove_buffer(1.into()); + buffer_view_config.remove_buffer(1.into()).unwrap(); assert_eq!( BufferViewConfig { buffers: vec![2.into(), 3.into()], @@ -281,12 +292,12 @@ mod tests { fn bufferviewconfig_remove_buffer_permanently() { // Remove already removed buffer let mut buffer_view_config = bufferviewconfig_sample(); - buffer_view_config.remove_buffer_permanently(4.into()); + buffer_view_config.remove_buffer_permanently(4.into()).unwrap(); assert_eq!(bufferviewconfig_sample(), buffer_view_config); // Remove buffer let mut buffer_view_config = bufferviewconfig_sample(); - buffer_view_config.remove_buffer_permanently(1.into()); + buffer_view_config.remove_buffer_permanently(1.into()).unwrap(); assert_eq!( BufferViewConfig { buffers: vec![2.into(), 3.into()], @@ -302,12 +313,12 @@ mod tests { fn bufferviewconfig_move_buffer() { // Do nothing let mut buffer_view_config = bufferviewconfig_sample(); - buffer_view_config.move_buffer(1.into(), 0); + buffer_view_config.move_buffer(1.into(), 0).unwrap(); assert_eq!(bufferviewconfig_sample(), buffer_view_config); // Move buffer let mut buffer_view_config = bufferviewconfig_sample(); - buffer_view_config.move_buffer(1.into(), 1); + buffer_view_config.move_buffer(1.into(), 1).unwrap(); assert_eq!( BufferViewConfig { buffers: vec![2.into(), 1.into(), 3.into()], diff --git a/src/message/signalproxy/objects/bufferviewmanager.rs b/src/message/signalproxy/objects/bufferviewmanager.rs index 6d2d593..1ecac4c 100644 --- a/src/message/signalproxy/objects/bufferviewmanager.rs +++ b/src/message/signalproxy/objects/bufferviewmanager.rs @@ -10,6 +10,7 @@ use crate::message::StatefulSyncableServer; use crate::message::{NetworkMap, Syncable}; use crate::primitive::{Variant, VariantList, VariantMap}; +use crate::Result; use super::BufferViewConfig; @@ -21,11 +22,11 @@ pub struct BufferViewManager { // TODO initialize the BufferViewConfigs from somewhere // TODO add buffer view configs, where does the data come from? impl BufferViewManager { - pub fn request_create_buffer_view(&self, properties: BufferViewConfig) { + pub fn request_create_buffer_view(&self, properties: BufferViewConfig) -> Result<()> { sync!("requestCreateBufferView", [properties.to_network_map()]) } - pub fn request_create_buffer_views(&self, properties: &[BufferViewConfig]) { + pub fn request_create_buffer_views(&self, properties: &[BufferViewConfig]) -> Result<()> { self.send_sync( "requestCreateBufferViews", properties @@ -35,11 +36,11 @@ impl BufferViewManager { ) } - pub fn request_delete_buffer_view(&self, id: i32) { + pub fn request_delete_buffer_view(&self, id: i32) -> Result<()> { sync!("requestDeleteBufferView", [id]) } - pub fn request_delete_buffer_views(&self, ids: &[i32]) { + pub fn request_delete_buffer_views(&self, ids: &[i32]) -> Result<()> { self.send_sync( "requestCreateBufferViews", ids.iter().map(|id| (*id).into()).collect(), @@ -48,24 +49,28 @@ impl BufferViewManager { #[cfg(feature = "client")] #[allow(unused_variables)] - pub fn add_buffer_view_config(&mut self, id: i32) { + pub fn add_buffer_view_config(&mut self, id: i32) -> Result<()> { // TODO init!("BufferViewConfig", id); + Ok(()) } #[cfg(feature = "server")] - pub fn add_buffer_view_config(&mut self, config: BufferViewConfig) { + pub fn add_buffer_view_config(&mut self, config: BufferViewConfig) -> Result<()> { self.buffer_view_configs.insert(0, Some(config)); - sync!("addBufferViewConfig", [0]); + sync!("addBufferViewConfig", [0]) } - pub fn delete_buffer_view_config(&mut self, id: i32) { + pub fn delete_buffer_view_config(&mut self, id: i32) -> Result<()> { if self.buffer_view_configs.contains_key(&id) { self.buffer_view_configs.remove(&id); } #[cfg(feature = "server")] - sync!("deleteBufferViewConfig", [id]) + return sync!("deleteBufferViewConfig", [id]); + + #[cfg(feature = "client")] + return Ok(()); } pub fn init_buffer_view_config(&mut self, config: BufferViewConfig) { @@ -80,48 +85,42 @@ impl BufferViewManager { #[cfg(feature = "client")] impl StatefulSyncableClient for BufferViewManager { - fn sync_custom(&mut self, mut msg: crate::message::SyncMessage) -> Result<(), crate::error::ProtocolError> + fn sync_custom(&mut self, mut msg: crate::message::SyncMessage) -> Result<()> where Self: Sized, { match msg.slot_name.as_str() { "addBufferViewConfig" | "newBufferViewConfig" => { - self.add_buffer_view_config(msg.params.remove(0).try_into().unwrap()) + self.add_buffer_view_config(msg.params.remove(0).try_into()?) } - "deleteBufferViewConfig" => { - self.delete_buffer_view_config(msg.params.remove(0).try_into().unwrap()) - } - _ => (), + "deleteBufferViewConfig" => self.delete_buffer_view_config(msg.params.remove(0).try_into()?), + _ => Ok(()), } - Ok(()) } } #[cfg(feature = "server")] impl StatefulSyncableServer for BufferViewManager { - fn sync_custom(&mut self, mut msg: crate::message::SyncMessage) -> Result<(), crate::error::ProtocolError> + fn sync_custom(&mut self, mut msg: crate::message::SyncMessage) -> Result<()> where Self: Sized, { match msg.slot_name.as_str() { "requestCreateBufferView" => self.add_buffer_view_config(BufferViewConfig::from_network_map( - &mut msg.params.remove(0).try_into().unwrap(), - )), + &mut msg.params.remove(0).try_into()?, + ))?, "requestCreateBufferViews" => { - let views: VariantList = msg.params.remove(0).try_into().unwrap(); - views.into_iter().for_each(|view| { - self.add_buffer_view_config(BufferViewConfig::from_network_map( - &mut view.try_into().unwrap(), - )) - }); - } - "requestDeleteBufferView" => { - self.delete_buffer_view_config(msg.params.remove(0).try_into().unwrap()) + let views: VariantList = msg.params.remove(0).try_into()?; + for view in views.into_iter() { + self.add_buffer_view_config(BufferViewConfig::from_network_map(&mut view.try_into()?))? + } } + "requestDeleteBufferView" => self.delete_buffer_view_config(msg.params.remove(0).try_into()?)?, "requestDeleteBufferViews" => { - let ids: VariantList = msg.params.remove(0).try_into().unwrap(); - ids.into_iter() - .for_each(|id| self.delete_buffer_view_config(id.try_into().unwrap())); + let ids: VariantList = msg.params.remove(0).try_into()?; + for id in ids.into_iter() { + self.delete_buffer_view_config(id.try_into()?)? + } } _ => (), } @@ -134,14 +133,14 @@ impl Syncable for BufferViewManager { } impl super::NetworkList for BufferViewManager { - fn to_network_list(&self) -> VariantList { - vec![ + fn to_network_list(&self) -> Result<VariantList> { + Ok(vec![ Variant::ByteArray(s!("bufferViewIds")), Variant::VariantList(self.buffer_view_configs.keys().map(|k| i32::into(*k)).collect()), - ] + ]) } - fn from_network_list(input: &mut VariantList) -> Self { + fn from_network_list(input: &mut VariantList) -> Result<Self> { let mut i = input.iter(); i.position(|x| *x == Variant::ByteArray(String::from("BufferViewIds"))) .expect("failed to get field BufferViewIds"); @@ -152,12 +151,12 @@ impl super::NetworkList for BufferViewManager { }; // TODO Somehow do the initrequests for all the IDs we get here - Self { + Ok(Self { buffer_view_configs: ids .into_iter() .map(|id| (i32::try_from(id).unwrap(), Option::None)) .collect(), - } + }) } } diff --git a/src/message/signalproxy/objects/certmanager.rs b/src/message/signalproxy/objects/certmanager.rs index ab78500..240db8d 100644 --- a/src/message/signalproxy/objects/certmanager.rs +++ b/src/message/signalproxy/objects/certmanager.rs @@ -3,6 +3,7 @@ use libquassel_derive::{NetworkList, NetworkMap}; use crate::message::{Class, Syncable}; #[allow(unused_imports)] use crate::primitive::Variant; +use crate::Result; #[derive(Debug, Clone, PartialEq, NetworkList, NetworkMap, Default)] pub struct CertManager { @@ -13,33 +14,36 @@ pub struct CertManager { } impl CertManager { - pub fn set_ssl_cert(&mut self, cert: String) { + pub fn set_ssl_cert(&mut self, cert: String) -> Result<()> { #[cfg(feature = "server")] - self.send_sync("setSslCert", vec![Variant::ByteArray(cert.clone())]); + self.send_sync("setSslCert", vec![Variant::ByteArray(cert.clone())])?; self.ssl_cert = cert; + + Ok(()) } - pub fn set_ssl_key(&mut self, key: String) { + pub fn set_ssl_key(&mut self, key: String) -> Result<()> { #[cfg(feature = "server")] - self.send_sync("setSslKey", vec![Variant::ByteArray(key.clone())]); + self.send_sync("setSslKey", vec![Variant::ByteArray(key.clone())])?; self.ssl_key = key; + + Ok(()) } } #[cfg(feature = "client")] impl crate::message::StatefulSyncableClient for CertManager { - fn sync_custom(&mut self, mut msg: crate::message::SyncMessage) -> Result<(), crate::error::ProtocolError> + fn sync_custom(&mut self, mut msg: crate::message::SyncMessage) -> Result<()> where Self: Sized, { match msg.slot_name.as_str() { "setSslCert" => self.set_ssl_cert(get_param!(msg)), "setSslKey" => self.set_ssl_key(get_param!(msg)), - _ => (), + _ => Ok(()), } - Ok(()) } } diff --git a/src/message/signalproxy/objects/coreinfo.rs b/src/message/signalproxy/objects/coreinfo.rs index 8dba602..bde4217 100644 --- a/src/message/signalproxy/objects/coreinfo.rs +++ b/src/message/signalproxy/objects/coreinfo.rs @@ -3,6 +3,7 @@ use libquassel_derive::{NetworkList, NetworkMap}; use crate::message::signalproxy::translation::NetworkMap; use crate::message::{Class, Syncable}; use crate::primitive::{DateTime, StringList}; +use crate::Result; #[derive(Default, Debug, Clone, PartialEq, NetworkList, NetworkMap)] #[network(repr = "map")] @@ -12,33 +13,35 @@ pub struct CoreInfo { } impl CoreInfo { - pub fn set_core_data(&mut self, data: CoreData) { + pub fn set_core_data(&mut self, data: CoreData) -> Result<()> { #[cfg(feature = "server")] - libquassel_derive::sync!("setCoreData", [data.to_network_map()]); + libquassel_derive::sync!("setCoreData", [data.to_network_map()])?; self.core_data = data; + + Ok(()) } } #[cfg(feature = "client")] impl crate::message::StatefulSyncableClient for CoreInfo { - fn sync_custom(&mut self, mut msg: crate::message::SyncMessage) -> Result<(), crate::error::ProtocolError> + fn sync_custom(&mut self, mut msg: crate::message::SyncMessage) -> Result<()> where Self: Sized, { #[allow(clippy::single_match)] match msg.slot_name.as_str() { "setCoreData" => self.set_core_data(CoreData::from_network_map(&mut get_param!(msg))), - _ => (), + _ => Ok(()), } - Ok(()) } /// Not Implemented - fn request_update(&mut self) + fn request_update(&mut self) -> crate::Result<()> where Self: Sized, { + unimplemented!() } } @@ -48,7 +51,7 @@ impl crate::message::StatefulSyncableServer for CoreInfo { fn request_update( &mut self, mut _param: <CoreInfo as NetworkMap>::Item, - ) -> Result<(), crate::error::ProtocolError> + ) -> Result<()> where Self: Sized, { diff --git a/src/message/signalproxy/objects/highlightrulemanager.rs b/src/message/signalproxy/objects/highlightrulemanager.rs index 9af0b4c..aa9fe25 100644 --- a/src/message/signalproxy/objects/highlightrulemanager.rs +++ b/src/message/signalproxy/objects/highlightrulemanager.rs @@ -10,6 +10,7 @@ use crate::message::StatefulSyncableServer; use crate::message::Syncable; use crate::primitive::Variant; +use crate::Result; #[derive(Default, Debug, Clone, PartialEq, NetworkList, NetworkMap)] pub struct HighlightRuleManager { @@ -40,11 +41,11 @@ impl HighlightRuleManager { } } - pub fn request_remove_highlight_rule(&self, id: i32) { + pub fn request_remove_highlight_rule(&self, id: i32) -> Result<()> { sync!("requestRemoveHighlightRule", [id]) } - pub fn request_toggle_highlight_rule(&self, id: i32) { + pub fn request_toggle_highlight_rule(&self, id: i32) -> Result<()> { sync!("requestToggleHighlightRule", [id]) } @@ -58,7 +59,7 @@ impl HighlightRuleManager { is_inverse: bool, sender: String, channel: String, - ) { + ) -> Result<()> { sync!( "requestAddHighlightRule", [ @@ -74,69 +75,81 @@ impl HighlightRuleManager { ) } - pub fn request_set_highlight_nick(&self, nick: HighlightNickType) { + pub fn request_set_highlight_nick(&self, nick: HighlightNickType) -> Result<()> { sync!("requestSetHighlightNick", [nick]) } - pub fn request_set_nicks_case_sensitive(&self, enabled: bool) { + pub fn request_set_nicks_case_sensitive(&self, enabled: bool) -> Result<()> { sync!("requestSetNicksCaseSensitive", [enabled]) } - pub fn remove_highlight_rule(&mut self, id: i32) { + pub fn remove_highlight_rule(&mut self, id: i32) -> Result<()> { if let Some(position) = self.highlight_rule_list.iter().position(|rule| rule.id == id) { self.highlight_rule_list.remove(position); } #[cfg(feature = "server")] - sync!("removeHighlightRule", [id]); + return sync!("removeHighlightRule", [id]); + + #[cfg(feature = "client")] + return Ok(()); } - pub fn toggle_highlight_rule(&mut self, id: i32) { + pub fn toggle_highlight_rule(&mut self, id: i32) -> Result<()> { if let Some(rule) = self.highlight_rule_mut(id) { rule.is_enabled = !rule.is_enabled; } #[cfg(feature = "server")] - sync!("toggleHighlightRule", [id]) + return sync!("toggleHighlightRule", [id]); + + #[cfg(feature = "client")] + return Ok(()); } - pub fn add_highlight_rule(&mut self, rule: HighlightRule) { + pub fn add_highlight_rule(&mut self, rule: HighlightRule) -> Result<()> { #[cfg(feature = "server")] sync!( "addHighlightRule", [ - rule.id.clone(), + rule.id, rule.name.clone(), - rule.is_regex.clone(), - rule.is_case_sensitive.clone(), - rule.is_enabled.clone(), - rule.is_inverse.clone(), + rule.is_regex, + rule.is_case_sensitive, + rule.is_enabled, + rule.is_inverse, rule.sender.clone(), rule.channel.clone() ] - ); + )?; self.highlight_rule_list.push(rule); + + Ok(()) } - pub fn set_highlight_nick(&mut self, nick: HighlightNickType) { + pub fn set_highlight_nick(&mut self, nick: HighlightNickType) -> Result<()> { #[cfg(feature = "server")] - sync!("setHighlightNick", [Variant::from(nick)]); + sync!("setHighlightNick", [Variant::from(nick)])?; self.highlight_nick = nick; + + Ok(()) } - pub fn set_nicks_case_sensitive(&mut self, enabled: bool) { + pub fn set_nicks_case_sensitive(&mut self, enabled: bool) -> Result<()> { #[cfg(feature = "server")] - sync!("setNicksCaseSensitive", [enabled]); + sync!("setNicksCaseSensitive", [enabled])?; self.nicks_case_sensitive = enabled; + + Ok(()) } } #[cfg(feature = "client")] impl StatefulSyncableClient for HighlightRuleManager { - fn sync_custom(&mut self, mut msg: crate::message::SyncMessage) -> Result<(), ProtocolError> + fn sync_custom(&mut self, mut msg: crate::message::SyncMessage) -> Result<()> where Self: Sized, { @@ -155,15 +168,14 @@ impl StatefulSyncableClient for HighlightRuleManager { }), "setHighlightNick" => self.set_highlight_nick(get_param!(msg)), "setNicksCaseSensitive" => self.set_nicks_case_sensitive(get_param!(msg)), - _ => (), + _ => Ok(()), } - Ok(()) } } #[cfg(feature = "server")] impl StatefulSyncableServer for HighlightRuleManager { - fn sync_custom(&mut self, mut msg: crate::message::SyncMessage) -> Result<(), ProtocolError> + fn sync_custom(&mut self, mut msg: crate::message::SyncMessage) -> Result<()> where Self: Sized, { @@ -182,9 +194,8 @@ impl StatefulSyncableServer for HighlightRuleManager { }), "requestSetHighlightNick" => self.set_highlight_nick(get_param!(msg)), "requestSetNicksCaseSensitive" => self.set_nicks_case_sensitive(get_param!(msg)), - _ => (), + _ => Ok(()), } - Ok(()) } } @@ -229,7 +240,7 @@ impl From<HighlightNickType> for Variant { impl TryFrom<Variant> for HighlightNickType { type Error = ProtocolError; - fn try_from(value: Variant) -> Result<Self, Self::Error> { + fn try_from(value: Variant) -> Result<Self> { let i: i32 = value.try_into()?; Self::try_from(i).map_err(|_| ProtocolError::WrongVariant) } @@ -242,14 +253,14 @@ impl From<HighlightNickType> for i32 { } impl TryFrom<i32> for HighlightNickType { - type Error = &'static str; + type Error = ProtocolError; - fn try_from(value: i32) -> Result<Self, Self::Error> { + fn try_from(value: i32) -> Result<Self> { match value { 0x00 => Ok(HighlightNickType::NoNick), 0x01 => Ok(HighlightNickType::CurrentNick), 0x02 => Ok(HighlightNickType::AllNicks), - _ => Err("no matching HighlightNickType found"), + err => Err(ProtocolError::UnknownHighlightNickType(err)), } } } @@ -301,13 +312,13 @@ mod tests { #[test] fn highlightrulemanager_to_network() { - assert_eq!(get_runtime().to_network_list(), get_network()) + assert_eq!(get_runtime().to_network_list().unwrap(), get_network()) } #[test] fn highlightrulemanager_from_network() { assert_eq!( - HighlightRuleManager::from_network_list(&mut get_network()), + HighlightRuleManager::from_network_list(&mut get_network()).unwrap(), get_runtime() ) } diff --git a/src/message/signalproxy/objects/identity.rs b/src/message/signalproxy/objects/identity.rs index e745a9e..57cd588 100644 --- a/src/message/signalproxy/objects/identity.rs +++ b/src/message/signalproxy/objects/identity.rs @@ -17,6 +17,7 @@ use crate::primitive::VariantMap; use crate::serialize::Deserialize; use crate::serialize::Serialize; use crate::serialize::UserType; +use crate::{Result, SyncProxyError}; #[derive(Default, Debug, Clone, PartialEq, NetworkMap, NetworkList, Setters)] pub struct Identity { @@ -70,13 +71,13 @@ impl UserType for Identity { } impl Serialize for Identity { - fn serialize(&self) -> Result<Vec<u8>, crate::ProtocolError> { + fn serialize(&self) -> Result<Vec<u8>> { self.to_network_map().serialize() } } impl Deserialize for Identity { - fn parse(b: &[u8]) -> Result<(usize, Self), crate::ProtocolError> + fn parse(b: &[u8]) -> Result<(usize, Self)> where Self: std::marker::Sized, { @@ -86,17 +87,19 @@ impl Deserialize for Identity { } impl Identity { - pub fn copy_from(&mut self, other: Identity) { + pub fn copy_from(&mut self, other: Identity) -> Result<()> { #[cfg(feature = "server")] - sync!("copyFrom", [other.to_network_map()]); + sync!("copyFrom", [other.to_network_map()])?; *self = other; + + Ok(()) } } #[cfg(feature = "client")] impl StatefulSyncableClient for Identity { - fn sync_custom(&mut self, mut msg: crate::message::SyncMessage) -> Result<(), crate::error::ProtocolError> + fn sync_custom(&mut self, mut msg: crate::message::SyncMessage) -> Result<()> where Self: Sized, { @@ -121,9 +124,8 @@ impl StatefulSyncableClient for Identity { "setPartReason" => self.set_part_reason(get_param!(msg)), "setQuitReason" => self.set_quit_reason(get_param!(msg)), "setRealName" => self.set_real_name(get_param!(msg)), - _ => (), + _ => Ok(()), } - Ok(()) } } @@ -133,12 +135,10 @@ impl StatefulSyncableServer for Identity {} impl Syncable for Identity { const CLASS: Class = Class::Identity; - fn send_sync(&self, function: &str, params: crate::primitive::VariantList) { - crate::message::signalproxy::SYNC_PROXY.get().unwrap().sync( - Self::CLASS, - Some(&self.identity_id.to_string()), - function, - params, - ); + fn send_sync(&self, function: &str, params: crate::primitive::VariantList) -> crate::Result<()> { + crate::message::signalproxy::SYNC_PROXY + .get() + .ok_or(SyncProxyError::NotInitialized)? + .sync(Self::CLASS, Some(&self.identity_id.to_string()), function, params) } } diff --git a/src/message/signalproxy/objects/ignorelistmanager.rs b/src/message/signalproxy/objects/ignorelistmanager.rs index 4697611..5a38fd0 100644 --- a/src/message/signalproxy/objects/ignorelistmanager.rs +++ b/src/message/signalproxy/objects/ignorelistmanager.rs @@ -1,7 +1,7 @@ use crate::{ - error::ProtocolError, message::{Class, Syncable}, primitive::Variant, + ProtocolError, Result, }; use libquassel_derive::{sync, NetworkList, NetworkMap}; @@ -51,7 +51,7 @@ impl IgnoreListManager { scope_rule, is_active, }: IgnoreListItem, - ) { + ) -> Result<()> { sync!( "requestAddIgnoreListItem", [ @@ -66,15 +66,15 @@ impl IgnoreListManager { ) } - pub fn request_remove_ignore_list_item(&self, rule: String) { + pub fn request_remove_ignore_list_item(&self, rule: String) -> Result<()> { sync!("requestRemoveIgnoreListItem", [rule]) } - pub fn request_toggle_ignore_rule(&self, rule: String) { + pub fn request_toggle_ignore_rule(&self, rule: String) -> Result<()> { sync!("requestToggleIgnoreRule", [rule]) } - pub fn add_ignore_list_item(&mut self, item: IgnoreListItem) { + pub fn add_ignore_list_item(&mut self, item: IgnoreListItem) -> Result<()> { #[cfg(feature = "server")] sync!( "addIgnoreListItem", @@ -87,14 +87,16 @@ impl IgnoreListManager { item.scope_rule.clone(), item.is_active ] - ); + )?; if self.ignore_list_item(&item.ignore_rule).is_none() { self.ignore_list.push(item) }; + + Ok(()) } - pub fn remove_ignore_list_item(&mut self, rule: &str) { + pub fn remove_ignore_list_item(&mut self, rule: &str) -> Result<()> { if let Some(position) = self .ignore_list .iter() @@ -104,22 +106,28 @@ impl IgnoreListManager { }; #[cfg(feature = "server")] - sync!("removeIgnoreListItem", [rule]) + return sync!("removeIgnoreListItem", [rule]); + + #[cfg(feature = "client")] + return Ok(()); } - pub fn toggle_ignore_rule(&mut self, rule: &str) { + pub fn toggle_ignore_rule(&mut self, rule: &str) -> Result<()> { if let Some(item) = self.ignore_list_item_mut(rule) { item.is_active = !item.is_active } #[cfg(feature = "server")] - sync!("toggleIgnoreRule", [rule]) + return sync!("toggleIgnoreRule", [rule]); + + #[cfg(feature = "client")] + return Ok(()); } } #[cfg(feature = "client")] impl crate::message::StatefulSyncableClient for IgnoreListManager { - fn sync_custom(&mut self, mut msg: crate::message::SyncMessage) -> Result<(), ProtocolError> + fn sync_custom(&mut self, mut msg: crate::message::SyncMessage) -> Result<()> where Self: Sized, { @@ -135,21 +143,20 @@ impl crate::message::StatefulSyncableClient for IgnoreListManager { }), "removeIgnoreListItem" => { let rule: String = get_param!(msg); - self.remove_ignore_list_item(&rule); + self.remove_ignore_list_item(&rule) } "toggleIgnoreRule" => { let rule: String = get_param!(msg); - self.toggle_ignore_rule(&rule); + self.toggle_ignore_rule(&rule) } - _ => (), + _ => Ok(()), } - Ok(()) } } #[cfg(feature = "server")] impl crate::message::StatefulSyncableServer for IgnoreListManager { - fn sync_custom(&mut self, mut msg: crate::message::SyncMessage) -> Result<(), ProtocolError> + fn sync_custom(&mut self, mut msg: crate::message::SyncMessage) -> Result<()> where Self: Sized, { @@ -165,15 +172,14 @@ impl crate::message::StatefulSyncableServer for IgnoreListManager { }), "requestRemoveIgnoreListItem" => { let rule: String = get_param!(msg); - self.remove_ignore_list_item(&rule); + self.remove_ignore_list_item(&rule) } "requestToggleIgnoreRule" => { let rule: String = get_param!(msg); - self.toggle_ignore_rule(&rule); + self.toggle_ignore_rule(&rule) } - _ => (), + _ => Ok(()), } - Ok(()) } } @@ -221,7 +227,7 @@ impl From<IgnoreType> for Variant { impl TryFrom<Variant> for IgnoreType { type Error = ProtocolError; - fn try_from(value: Variant) -> Result<Self, Self::Error> { + fn try_from(value: Variant) -> Result<Self> { let i: i32 = value.try_into()?; Self::try_from(i).map_err(|_| ProtocolError::WrongVariant) } @@ -234,14 +240,14 @@ impl From<IgnoreType> for i32 { } impl TryFrom<i32> for IgnoreType { - type Error = &'static str; + type Error = ProtocolError; - fn try_from(value: i32) -> Result<Self, Self::Error> { + fn try_from(value: i32) -> Result<Self> { match value { 0x00 => Ok(IgnoreType::SenderIgnore), 0x01 => Ok(IgnoreType::MessageIgnore), 0x02 => Ok(IgnoreType::CtcpIgnore), - _ => Err("no matching IgnoreType found"), + err => Err(ProtocolError::UnknownIgnoreType(err)), } } } @@ -263,7 +269,7 @@ impl From<StrictnessType> for Variant { impl TryFrom<Variant> for StrictnessType { type Error = ProtocolError; - fn try_from(value: Variant) -> Result<Self, Self::Error> { + fn try_from(value: Variant) -> Result<Self> { let i: i32 = value.try_into()?; Self::try_from(i).map_err(|_| ProtocolError::WrongVariant) } @@ -276,14 +282,14 @@ impl From<StrictnessType> for i32 { } impl TryFrom<i32> for StrictnessType { - type Error = &'static str; + type Error = ProtocolError; - fn try_from(value: i32) -> Result<Self, Self::Error> { + fn try_from(value: i32) -> Result<Self> { match value { 0x00 => Ok(StrictnessType::UnmatchedStrictness), 0x01 => Ok(StrictnessType::SoftStrictness), 0x02 => Ok(StrictnessType::HardStrictness), - _ => Err("no matching StrictnessType found"), + err => Err(ProtocolError::UnknownStrictnessType(err)), } } } @@ -305,7 +311,7 @@ impl From<ScopeType> for Variant { impl TryFrom<Variant> for ScopeType { type Error = ProtocolError; - fn try_from(value: Variant) -> Result<Self, Self::Error> { + fn try_from(value: Variant) -> Result<Self> { let i: i32 = value.try_into()?; Self::try_from(i).map_err(|_| ProtocolError::WrongVariant) } @@ -318,14 +324,14 @@ impl From<ScopeType> for i32 { } impl TryFrom<i32> for ScopeType { - type Error = &'static str; + type Error = ProtocolError; - fn try_from(value: i32) -> Result<Self, Self::Error> { + fn try_from(value: i32) -> Result<Self> { match value { 0x00 => Ok(ScopeType::GlobalScope), 0x01 => Ok(ScopeType::NetworkScope), 0x02 => Ok(ScopeType::ChannelScope), - _ => Err("no matching ScopeType found"), + err => Err(ProtocolError::UnknownScopeType(err)), } } } diff --git a/src/message/signalproxy/objects/ircchannel.rs b/src/message/signalproxy/objects/ircchannel.rs index ef42d3b..d160ac3 100644 --- a/src/message/signalproxy/objects/ircchannel.rs +++ b/src/message/signalproxy/objects/ircchannel.rs @@ -8,6 +8,7 @@ use log::{error, warn}; use crate::message::{signalproxy::translation::NetworkMap, Class, Syncable}; use crate::primitive::{StringList, VariantMap}; use crate::serialize::{Deserialize, Serialize, UserType}; +use crate::Result; use super::{ChanModes, ChannelModeType}; @@ -36,13 +37,13 @@ impl UserType for IrcChannel { } impl Serialize for IrcChannel { - fn serialize(&self) -> Result<Vec<u8>, crate::ProtocolError> { + fn serialize(&self) -> Result<Vec<u8>> { self.to_network_map().serialize() } } impl Deserialize for IrcChannel { - fn parse(b: &[u8]) -> Result<(usize, Self), crate::ProtocolError> + fn parse(b: &[u8]) -> Result<(usize, Self)> where Self: std::marker::Sized, { @@ -99,7 +100,7 @@ impl IrcChannel { // TODO add user mode validation /// Add one or more mode flags to a user - pub fn add_user_mode(&mut self, nick: String, mode: String) { + pub fn add_user_mode(&mut self, nick: String, mode: String) -> Result<()> { if let Some(user_modes) = self.user_modes.get_mut(&nick) { mode.chars().for_each(|c| { if !user_modes.contains(c) { @@ -115,16 +116,18 @@ impl IrcChannel { // TODO this might actually be dumb can IRC even into mutiple modes at once? #[cfg(feature = "server")] if let Some(user_modes) = self.user_modes.get(&nick) { - mode.chars().for_each(|c| { + for c in mode.chars() { if !user_modes.contains(c) { - sync!("addUserMode", [nick.clone(), c.to_string()]); + sync!("addUserMode", [nick.clone(), c.to_string()])?; } - }); + } }; + + Ok(()) } /// Remove one or more mode flags from a user - pub fn remove_user_mode(&mut self, nick: String, mode: String) { + pub fn remove_user_mode(&mut self, nick: String, mode: String) -> Result<()> { if let Some(user_modes) = self.user_modes.get_mut(&nick) { mode.chars().for_each(|c| { *user_modes = user_modes.replace(c, ""); @@ -132,24 +135,28 @@ impl IrcChannel { } #[cfg(feature = "server")] - sync!("removeUserMode", [nick, mode]); + return sync!("removeUserMode", [nick, mode]); + + #[cfg(feature = "client")] + return Ok(()); } - pub fn join_irc_users(&mut self, nicks: StringList, modes: StringList) { + pub fn join_irc_users(&mut self, nicks: StringList, modes: StringList) -> Result<()> { if nicks.len() != modes.len() { error!("number of nicks does not match number of modes"); } #[cfg(feature = "server")] - sync!("joinIrcUsers", [nicks.clone(), modes.clone()]); + sync!("joinIrcUsers", [nicks.clone(), modes.clone()])?; + + for (nick, mode) in nicks.into_iter().zip(modes) { + self.add_user_mode(nick, mode)? + } - nicks - .into_iter() - .zip(modes) - .for_each(|(nick, mode)| self.add_user_mode(nick, mode)); + Ok(()) } - pub fn part(&mut self, nick: String) { + pub fn part(&mut self, nick: String) -> Result<()> { match self.user_modes.remove(&nick) { Some(_) => (), None => warn!("tried to remove a user that is not joined to the channel"), @@ -160,30 +167,34 @@ impl IrcChannel { { // TODO Clean up channel and delete } + + Ok(()) } - pub fn set_user_modes(&mut self, nick: String, modes: String) { + pub fn set_user_modes(&mut self, nick: String, modes: String) -> Result<()> { #[cfg(feature = "server")] - sync!("setUserModes", [nick.clone(), modes.clone()]); + sync!("setUserModes", [nick.clone(), modes.clone()])?; *self.user_modes.entry(nick).or_default() = modes; + + Ok(()) } } #[cfg(feature = "client")] impl crate::message::StatefulSyncableClient for IrcChannel { - fn sync_custom(&mut self, mut msg: crate::message::SyncMessage) -> Result<(), crate::error::ProtocolError> + fn sync_custom(&mut self, mut msg: crate::message::SyncMessage) -> Result<()> where Self: Sized, { match msg.slot_name.as_str() { // "addChannelMode" => { // let mode: String = get_param!(msg); - // self.add_channel_mode(mode.chars().next().unwrap(), get_param!(msg)); + // self.add_channel_mode(mode.chars().next()?, get_param!(msg)); // } // "removeChannelMode" => { // let mode: String = get_param!(msg); - // self.remove_channel_mode(mode.chars().next().unwrap(), get_param!(msg)); + // self.remove_channel_mode(mode.chars().next()?, get_param!(msg)); // } "addUserMode" => self.add_user_mode(get_param!(msg), get_param!(msg)), "removeUserMode" => self.remove_user_mode(get_param!(msg), get_param!(msg)), @@ -193,13 +204,12 @@ impl crate::message::StatefulSyncableClient for IrcChannel { "setPassword" => self.set_password(get_param!(msg)), "setTopic" => self.set_topic(get_param!(msg)), "setUserModes" => self.set_user_modes(get_param!(msg), get_param!(msg)), - _ => (), + _ => Ok(()), } - Ok(()) } /// Not Implemented for this type - fn request_update(&mut self) + fn request_update(&mut self) -> crate::Result<()> where Self: Sized, { @@ -210,10 +220,7 @@ impl crate::message::StatefulSyncableClient for IrcChannel { #[cfg(feature = "server")] impl crate::message::StatefulSyncableServer for IrcChannel { /// Not Implemented for this type - fn request_update( - &mut self, - _param: <IrcChannel as crate::message::NetworkMap>::Item, - ) -> Result<(), crate::error::ProtocolError> + fn request_update(&mut self, _param: <IrcChannel as crate::message::NetworkMap>::Item) -> Result<()> where Self: Sized, { @@ -324,13 +331,13 @@ mod tests { let mut res = get_runtime(); res.user_modes = map! { s!("audron") => s!("oh"), s!("audron_") => s!("") }; - base.add_user_mode(s!("audron"), s!("h")); + base.add_user_mode(s!("audron"), s!("h")).unwrap(); assert_eq!(res, base); - base.add_user_mode(s!("audron"), s!("o")); + base.add_user_mode(s!("audron"), s!("o")).unwrap(); assert_eq!(res, base); res.user_modes = map! { s!("audron") => s!("oh"), s!("audron_") => s!(""), s!("test") => s!("h") }; - base.add_user_mode(s!("test"), s!("h")); + base.add_user_mode(s!("test"), s!("h")).unwrap(); assert_eq!(res, base); } } diff --git a/src/message/signalproxy/objects/ircuser.rs b/src/message/signalproxy/objects/ircuser.rs index 8529405..e9de178 100644 --- a/src/message/signalproxy/objects/ircuser.rs +++ b/src/message/signalproxy/objects/ircuser.rs @@ -2,6 +2,7 @@ use crate::{ message::{Class, NetworkMap, Syncable}, primitive::{DateTime, StringList, VariantMap}, serialize::{Deserialize, Serialize, UserType}, + Result, SyncProxyError, }; use itertools::Itertools; @@ -48,13 +49,13 @@ impl UserType for IrcUser { } impl Serialize for IrcUser { - fn serialize(&self) -> Result<Vec<u8>, crate::ProtocolError> { + fn serialize(&self) -> Result<Vec<u8>> { self.to_network_map().serialize() } } impl Deserialize for IrcUser { - fn parse(b: &[u8]) -> Result<(usize, Self), crate::ProtocolError> + fn parse(b: &[u8]) -> Result<(usize, Self)> where Self: std::marker::Sized, { @@ -64,7 +65,7 @@ impl Deserialize for IrcUser { } impl IrcUser { - pub fn add_user_modes(&mut self, modes: String) { + pub fn add_user_modes(&mut self, modes: String) -> Result<()> { for mode in modes.chars() { if !self.user_modes.contains(mode) { self.user_modes.push(mode); @@ -72,10 +73,13 @@ impl IrcUser { } #[cfg(feature = "server")] - sync!("addUserModes", [modes]); + return sync!("addUserModes", [modes]); + + #[cfg(feature = "client")] + return Ok(()); } - pub fn remove_user_modes(&mut self, modes: String) { + pub fn remove_user_modes(&mut self, modes: String) -> Result<()> { for mode in modes.chars() { if self.user_modes.contains(mode) { self.user_modes = self.user_modes.chars().filter(|c| *c != mode).collect(); @@ -83,35 +87,48 @@ impl IrcUser { } #[cfg(feature = "server")] - sync!("removeUserModes", [modes]); + return sync!("removeUserModes", [modes]); + + #[cfg(feature = "client")] + return Ok(()); } - pub fn update_hostmask(&mut self, _mask: String) {} + pub fn update_hostmask(&mut self, _mask: String) -> Result<()> { + Ok(()) + } - pub fn join_channel(&mut self, channel: String) { + pub fn join_channel(&mut self, channel: String) -> Result<()> { if !self.channels.contains(&channel) { self.channels.push(channel.clone()) } #[cfg(feature = "server")] - sync!("partChannel", [channel]); + return sync!("partChannel", [channel]); + + #[cfg(feature = "client")] + return Ok(()); } - pub fn part_channel(&mut self, channel: String) { + pub fn part_channel(&mut self, channel: String) -> Result<()> { if let Some((i, _)) = self.channels.iter().find_position(|c| **c == channel) { self.channels.remove(i); } #[cfg(feature = "server")] - sync!("partChannel", [channel]); + return sync!("partChannel", [channel]); + + #[cfg(feature = "client")] + return Ok(()); } - pub fn quit(&mut self) {} + pub fn quit(&mut self) -> Result<()> { + Ok(()) + } } #[cfg(feature = "client")] impl crate::message::StatefulSyncableClient for IrcUser { - fn sync_custom(&mut self, mut msg: crate::message::SyncMessage) -> Result<(), crate::error::ProtocolError> + fn sync_custom(&mut self, mut msg: crate::message::SyncMessage) -> Result<()> where Self: Sized, { @@ -140,9 +157,8 @@ impl crate::message::StatefulSyncableClient for IrcUser { "setUserModes" => self.set_user_modes(get_param!(msg)), "setWhoisServiceReply" => self.set_whois_service_reply(get_param!(msg)), "updateHostmask" => self.update_hostmask(get_param!(msg)), - _ => unimplemented!(), + _ => Ok(()), } - Ok(()) } } @@ -152,11 +168,11 @@ impl crate::message::StatefulSyncableServer for IrcUser {} impl Syncable for IrcUser { const CLASS: Class = Class::IrcUser; - fn send_sync(&self, function: &str, params: crate::primitive::VariantList) { + fn send_sync(&self, function: &str, params: crate::primitive::VariantList) -> Result<()> { crate::message::signalproxy::SYNC_PROXY .get() - .unwrap() - .sync(Self::CLASS, None, function, params); + .ok_or(SyncProxyError::NotInitialized)? + .sync(Self::CLASS, None, function, params) } } diff --git a/src/message/signalproxy/objects/mod.rs b/src/message/signalproxy/objects/mod.rs index 999cd41..4bde771 100644 --- a/src/message/signalproxy/objects/mod.rs +++ b/src/message/signalproxy/objects/mod.rs @@ -80,19 +80,19 @@ impl Types { pub fn to_network(&self) -> VariantList { debug!("converting to network object: {:#?}", self); match self { - Types::AliasManager(val) => val.to_network_list(), - Types::BufferSyncer(val) => val.to_network_list(), - Types::BufferViewConfig(val) => val.to_network_list(), - Types::BufferViewManager(val) => val.to_network_list(), + Types::AliasManager(val) => val.to_network_list().unwrap(), + Types::BufferSyncer(val) => val.to_network_list().unwrap(), + Types::BufferViewConfig(val) => val.to_network_list().unwrap(), + Types::BufferViewManager(val) => val.to_network_list().unwrap(), // Types::CoreInfo(val) => vec![val.to_network_map().into()], Types::CoreData(val) => vec![val.to_network_map().into()], - Types::HighlightRuleManager(val) => val.to_network_list(), - Types::IgnoreListManager(val) => val.to_network_list(), - Types::CertManager(val) => val.to_network_list(), - Types::Network(val) => val.to_network_list(), - Types::NetworkInfo(val) => val.to_network_list(), - Types::NetworkConfig(val) => val.to_network_list(), - Types::IrcChannel(val) => val.to_network_list(), + Types::HighlightRuleManager(val) => val.to_network_list().unwrap(), + Types::IgnoreListManager(val) => val.to_network_list().unwrap(), + Types::CertManager(val) => val.to_network_list().unwrap(), + Types::Network(val) => val.to_network_list().unwrap(), + Types::NetworkInfo(val) => val.to_network_list().unwrap(), + Types::NetworkConfig(val) => val.to_network_list().unwrap(), + Types::IrcChannel(val) => val.to_network_list().unwrap(), Types::Unknown(val) => *val.clone(), } } @@ -100,33 +100,33 @@ impl Types { pub fn from_network(class_name: &str, object_name: &str, input: &mut VariantList) -> Self { debug!("converting {} from network object: {:#?}", class_name, input); match class_name { - "AliasManager" => Types::AliasManager(Box::new(AliasManager::from_network_list(input))), - "BufferSyncer" => Types::BufferSyncer(Box::new(BufferSyncer::from_network_list(input))), + "AliasManager" => Types::AliasManager(Box::new(AliasManager::from_network_list(input).unwrap())), + "BufferSyncer" => Types::BufferSyncer(Box::new(BufferSyncer::from_network_list(input).unwrap())), "BufferViewConfig" => { - let mut config = BufferViewConfig::from_network_list(input); + let mut config = BufferViewConfig::from_network_list(input).unwrap(); config.buffer_view_id = object_name.parse().unwrap(); Types::BufferViewConfig(Box::new(config)) } "BufferViewManager" => { - Types::BufferViewManager(Box::new(BufferViewManager::from_network_list(input))) + Types::BufferViewManager(Box::new(BufferViewManager::from_network_list(input).unwrap())) } // "CoreInfo" => Types::CoreInfo(CoreInfo::from_network_map( - // &mut input.remove(0).try_into().unwrap(), + // &mut input.remove(0).try_into()?.unwrap(), // )), "CoreData" => Types::CoreData(Box::new(CoreData::from_network_map( &mut input.remove(0).try_into().unwrap(), ))), "HighlightRuleManager" => { - Types::HighlightRuleManager(Box::new(HighlightRuleManager::from_network_list(input))) + Types::HighlightRuleManager(Box::new(HighlightRuleManager::from_network_list(input).unwrap())) } "IgnoreListManager" => { - Types::IgnoreListManager(Box::new(IgnoreListManager::from_network_list(input))) + Types::IgnoreListManager(Box::new(IgnoreListManager::from_network_list(input).unwrap())) } - "CertManager" => Types::CertManager(Box::new(CertManager::from_network_list(input))), - "Network" => Types::Network(Box::new(Network::from_network_list(input))), - "NetworkInfo" => Types::NetworkInfo(Box::new(NetworkInfo::from_network_list(input))), - "NetworkConfig" => Types::NetworkConfig(Box::new(NetworkConfig::from_network_list(input))), - "IrcChannel" => Types::IrcChannel(Box::new(IrcChannel::from_network_list(input))), + "CertManager" => Types::CertManager(Box::new(CertManager::from_network_list(input).unwrap())), + "Network" => Types::Network(Box::new(Network::from_network_list(input).unwrap())), + "NetworkInfo" => Types::NetworkInfo(Box::new(NetworkInfo::from_network_list(input).unwrap())), + "NetworkConfig" => Types::NetworkConfig(Box::new(NetworkConfig::from_network_list(input).unwrap())), + "IrcChannel" => Types::IrcChannel(Box::new(IrcChannel::from_network_list(input).unwrap())), _ => Types::Unknown(Box::new(input.to_owned())), } } diff --git a/src/message/signalproxy/objects/network.rs b/src/message/signalproxy/objects/network.rs index d256f67..5c5c0c6 100644 --- a/src/message/signalproxy/objects/network.rs +++ b/src/message/signalproxy/objects/network.rs @@ -7,11 +7,11 @@ use num_traits::{FromPrimitive, ToPrimitive}; use libquassel_derive::{sync, NetworkMap, Setters}; -use crate::error::ProtocolError; use crate::message::signalproxy::translation::NetworkMap; use crate::message::{Class, NetworkList, Syncable}; use crate::primitive::{Variant, VariantList, VariantMap}; use crate::serialize::{Deserialize, Serialize, UserType}; +use crate::{ProtocolError, Result}; use super::{ircchannel::IrcChannel, ircuser::IrcUser, networkinfo::NetworkInfo}; @@ -90,99 +90,127 @@ impl Network { self.irc_channels.insert(name.to_owned(), channel); } - pub fn connect(&self) { + pub fn connect(&self) -> Result<()> { #[cfg(feature = "client")] - sync!("requestConnect", []) + return sync!("requestConnect", []); + + #[cfg(feature = "server")] + return Ok(()); } - pub fn disconnect(&self) { + pub fn disconnect(&self) -> Result<()> { #[cfg(feature = "client")] - sync!("requestDisconnect", []) + return sync!("requestDisconnect", []); + + #[cfg(feature = "server")] + return Ok(()); } - pub fn set_network_info(&mut self, network_info: NetworkInfo) { + pub fn set_network_info(&mut self, network_info: NetworkInfo) -> Result<()> { #[cfg(feature = "client")] - sync!("requestSetNetworkInfo", [network_info.to_network_map()]); + sync!("requestSetNetworkInfo", [network_info.to_network_map()])?; self.network_info = network_info; + + Ok(()) } /// Enable the capability `cap` if it is not already enabled - pub fn acknowledge_cap(&mut self, cap: String) { + pub fn acknowledge_cap(&mut self, cap: String) -> Result<()> { #[cfg(feature = "server")] - sync!("acknowledgeCap", [cap.clone()]); + sync!("acknowledgeCap", [cap.clone()])?; if !self.caps_enabled.contains(&cap) { self.caps_enabled.push(cap); } else { warn!("Capability {} already enabled", cap) } + + Ok(()) } /// Add a new capability supported by the server - pub fn add_cap(&mut self, cap: String, value: String) { + pub fn add_cap(&mut self, cap: String, value: String) -> Result<()> { #[cfg(feature = "server")] - sync!("addCap", [cap.clone(), value.clone()]); + sync!("addCap", [cap.clone(), value.clone()])?; self.caps.insert(cap, value); + + Ok(()) } /// Clear `caps` and `caps_enabled` - pub fn clear_caps(&mut self) { + pub fn clear_caps(&mut self) -> Result<()> { #[cfg(feature = "server")] - sync!("clearCaps", []); + sync!("clearCaps", [])?; self.caps.clear(); self.caps_enabled.clear(); + + Ok(()) } /// Remove a capability from `caps` and `caps_enabled` - pub fn remove_cap(&mut self, cap: String) { + pub fn remove_cap(&mut self, cap: String) -> Result<()> { #[cfg(feature = "server")] - sync!("removeCap", [cap.clone()]); + sync!("removeCap", [cap.clone()])?; self.caps.remove(&cap); if let Some((i, _)) = self.caps_enabled.iter().find_position(|c| **c == cap) { self.caps_enabled.remove(i); } + + Ok(()) } // TODO - pub fn add_irc_channel(&mut self, _name: String) {} - pub fn add_irc_user(&mut self, _hostmask: String) {} + pub fn add_irc_channel(&mut self, _name: String) -> Result<()> { + Ok(()) + } + pub fn add_irc_user(&mut self, _hostmask: String) -> Result<()> { + Ok(()) + } - pub fn add_support(&mut self, key: String, value: String) { + pub fn add_support(&mut self, key: String, value: String) -> Result<()> { #[cfg(feature = "server")] - sync!("addSupport", [key.clone(), value.clone()]); + sync!("addSupport", [key.clone(), value.clone()])?; self.supports.insert(key, value); + + Ok(()) } - pub fn remove_support(&mut self, key: String) { + pub fn remove_support(&mut self, key: String) -> Result<()> { #[cfg(feature = "server")] - sync!("removeSupport", [key.clone()]); + sync!("removeSupport", [key.clone()])?; self.supports.remove(&key); + + Ok(()) } - pub fn emit_connection_error(&mut self, error: String) { + pub fn emit_connection_error(&mut self, error: String) -> Result<()> { #[cfg(feature = "server")] - sync!("emitConnectionError", [error.clone()]); + sync!("emitConnectionError", [error.clone()])?; + + error!("{}", error); - error!("{}", error) + Ok(()) } /// Rename the user object in the network object /// TODO the actual nick change is done with a sepperate sync message against the IrcUser object? - pub fn irc_user_nick_changed(&mut self, before: String, after: String) { + pub fn irc_user_nick_changed(&mut self, before: String, after: String) -> Result<()> { #[cfg(feature = "server")] - sync!("ircUserNickChanged", [before.clone(), after.clone()]); + sync!("ircUserNickChanged", [before.clone(), after.clone()])?; if let Some(user) = self.irc_users.remove(&before) { self.irc_users.insert(after, user); } else { warn!("irc user {} not found", before); } + + Ok(()) } } @@ -192,7 +220,7 @@ impl Syncable for Network { #[cfg(feature = "client")] impl crate::message::StatefulSyncableClient for Network { - fn sync_custom(&mut self, mut msg: crate::message::SyncMessage) -> Result<(), ProtocolError> + fn sync_custom(&mut self, mut msg: crate::message::SyncMessage) -> Result<()> where Self: Sized, { @@ -225,7 +253,7 @@ impl crate::message::StatefulSyncableClient for Network { "setNetworkName" => self.network_info.set_network_name(get_param!(msg)), "setNetworkInfo" => { let mut map = VariantMap::try_from(msg.params.remove(0))?; - self.set_network_info(NetworkInfo::from_network_map(&mut map)); + self.set_network_info(NetworkInfo::from_network_map(&mut map)) } "setPerform" => self.network_info.set_perform(get_param!(msg)), "setRejoinChannels" => self.network_info.set_rejoin_channels(get_param!(msg)), @@ -253,15 +281,14 @@ impl crate::message::StatefulSyncableClient for Network { "setUseCustomMessageRate" => self.network_info.set_use_custom_message_rate(get_param!(msg)), "setUseRandomServer" => self.network_info.set_use_random_server(get_param!(msg)), "setUseSasl" => self.network_info.set_use_sasl(get_param!(msg)), - _ => (), + _ => Ok(()), } - Ok(()) } } #[cfg(feature = "server")] impl crate::message::StatefulSyncableServer for Network { - fn sync_custom(&mut self, mut msg: crate::message::SyncMessage) -> Result<(), ProtocolError> + fn sync_custom(&mut self, mut msg: crate::message::SyncMessage) -> Result<()> where Self: Sized, { @@ -270,16 +297,15 @@ impl crate::message::StatefulSyncableServer for Network { "requestDisconnect" => self.disconnect(), "requestSetNetworkInfo" => { let mut map = VariantMap::try_from(msg.params.remove(0))?; - self.set_network_info(NetworkInfo::from_network_map(&mut map)); + self.set_network_info(NetworkInfo::from_network_map(&mut map)) } - _ => (), + _ => Ok(()), } - Ok(()) } } impl crate::message::signalproxy::NetworkList for Network { - fn to_network_list(&self) -> VariantList { + fn to_network_list(&self) -> Result<VariantList> { #![allow(clippy::vec_init_then_push)] let mut res = VariantList::new(); @@ -342,13 +368,13 @@ impl crate::message::signalproxy::NetworkList for Network { res.push(Variant::VariantMap(map)); } - res.extend(self.network_info.to_network_list()); + res.extend(self.network_info.to_network_list()?); - res + Ok(res) } // TODO VariantList -> VariantMap conversion - fn from_network_list(input: &mut VariantList) -> Self { + fn from_network_list(input: &mut VariantList) -> Result<Self> { let mut i = input.iter().cycle(); let users_and_channels: VariantMap = { @@ -411,7 +437,7 @@ impl crate::message::signalproxy::NetworkList for Network { match users_and_channels.get("Channels") { Some(channels) => { let channels: Vec<IrcChannel> = - Vec::<IrcChannel>::from_network_map(&mut channels.try_into().unwrap()); + Vec::<IrcChannel>::from_network_map(&mut channels.try_into()?); channels .into_iter() .map(|channel| (channel.name.clone(), channel)) @@ -444,13 +470,13 @@ impl crate::message::signalproxy::NetworkList for Network { var.into_iter().map(|v| v.try_into().unwrap()).collect() }, - network_info: NetworkInfo::from_network_list(input), + network_info: NetworkInfo::from_network_list(input).unwrap(), }; network.determine_channel_mode_types(); network.determine_prefixes(); - network + Ok(network) } } @@ -624,12 +650,12 @@ pub struct NetworkServer { // we have this problem since now we have generic VariantList impls // for all the variants and this type is now also directly a variant impl NetworkList for Vec<NetworkServer> { - fn to_network_list(&self) -> super::VariantList { - self.iter().map(|b| Variant::NetworkServer(b.clone())).collect() + fn to_network_list(&self) -> Result<super::VariantList> { + Ok(self.iter().map(|b| Variant::NetworkServer(b.clone())).collect()) } - fn from_network_list(input: &mut super::VariantList) -> Self { - input.iter().map(|b| b.try_into().unwrap()).collect() + fn from_network_list(input: &mut super::VariantList) -> Result<Self> { + Ok(input.iter().map(|b| b.try_into().unwrap()).collect()) } } @@ -638,13 +664,13 @@ impl UserType for NetworkServer { } impl Serialize for NetworkServer { - fn serialize(&self) -> Result<Vec<u8>, crate::ProtocolError> { + fn serialize(&self) -> Result<Vec<u8>> { self.to_network_map().serialize() } } impl Deserialize for NetworkServer { - fn parse(b: &[u8]) -> Result<(usize, Self), crate::ProtocolError> + fn parse(b: &[u8]) -> Result<(usize, Self)> where Self: std::marker::Sized, { @@ -812,7 +838,7 @@ impl From<ConnectionState> for Variant { impl TryFrom<Variant> for ConnectionState { type Error = ProtocolError; - fn try_from(value: Variant) -> Result<Self, Self::Error> { + fn try_from(value: Variant) -> Result<Self> { match value { Variant::i32(n) => Ok(ConnectionState::from_i32(n).unwrap()), _ => Err(ProtocolError::WrongVariant), diff --git a/src/message/signalproxy/objects/networkconfig.rs b/src/message/signalproxy/objects/networkconfig.rs index 6268a69..871e387 100644 --- a/src/message/signalproxy/objects/networkconfig.rs +++ b/src/message/signalproxy/objects/networkconfig.rs @@ -41,9 +41,8 @@ impl crate::message::StatefulSyncableClient for NetworkConfig { "setPingInterval" => self.set_ping_interval(get_param!(msg)), "setPingTimeoutEnabled" => self.set_ping_timeout_enabled(get_param!(msg)), "setStandardCtcp" => self.set_standard_ctcp(get_param!(msg)), - _ => (), + _ => Ok(()), } - Ok(()) } } @@ -62,8 +61,7 @@ impl crate::message::StatefulSyncableServer for NetworkConfig { "requestSetPingInterval" => self.set_ping_interval(get_param!(msg)), "requestSetPingTimeoutEnabled" => self.set_ping_timeout_enabled(get_param!(msg)), "requestSetStandardCtcp" => self.set_standard_ctcp(get_param!(msg)), - _ => (), + _ => Ok(()), } - Ok(()) } } diff --git a/src/message/signalproxy/objects/networkinfo.rs b/src/message/signalproxy/objects/networkinfo.rs index ba944e8..bc08989 100644 --- a/src/message/signalproxy/objects/networkinfo.rs +++ b/src/message/signalproxy/objects/networkinfo.rs @@ -1,13 +1,12 @@ use crate::{ - message::{signalproxy::translation::NetworkMap, Class, Syncable}, + message::{objects::network::NetworkServer, signalproxy::translation::NetworkMap, Class, Syncable}, primitive::{IdentityId, NetworkId, StringList, VariantMap}, serialize::{Deserialize, Serialize, UserType}, + Result, }; use libquassel_derive::{NetworkList, NetworkMap, Setters}; -use crate::message::objects::network::NetworkServer; - #[derive(Default, Debug, Clone, PartialEq, NetworkList, NetworkMap, Setters)] pub struct NetworkInfo { #[network(rename = "networkName")] @@ -77,13 +76,13 @@ impl UserType for NetworkInfo { } impl Serialize for NetworkInfo { - fn serialize(&self) -> Result<Vec<u8>, crate::ProtocolError> { + fn serialize(&self) -> Result<Vec<u8>> { self.to_network_map().serialize() } } impl Deserialize for NetworkInfo { - fn parse(b: &[u8]) -> Result<(usize, Self), crate::ProtocolError> + fn parse(b: &[u8]) -> Result<(usize, Self)> where Self: std::marker::Sized, { @@ -93,16 +92,18 @@ impl Deserialize for NetworkInfo { } impl NetworkInfo { - pub fn set_server_list(&mut self, servers: Vec<NetworkServer>) { + pub fn set_server_list(&mut self, servers: Vec<NetworkServer>) -> Result<()> { #[cfg(feature = "server")] { use crate::message::NetworkMap; use libquassel_derive::sync; - sync!("setServerList", [Vec::<NetworkServer>::to_network_map(&servers)]); + sync!("setServerList", [Vec::<NetworkServer>::to_network_map(&servers)])?; } self.server_list = servers; + + Ok(()) } } @@ -204,20 +205,23 @@ mod tests { #[test] fn networkinfo_to_network() { - assert_eq!(get_runtime().to_network_list(), get_network()); - assert_eq!(get_runtime().to_network_list(), get_network()); + assert_eq!(get_runtime().to_network_list().unwrap(), get_network()); + assert_eq!(get_runtime().to_network_list().unwrap(), get_network()); } #[test] fn networkinfo_from_network() { - assert_eq!(NetworkInfo::from_network_list(&mut get_network()), get_runtime()); + assert_eq!( + NetworkInfo::from_network_list(&mut get_network()).unwrap(), + get_runtime() + ); // Test serialization without given network id let mut network = get_network(); network.remove(20); network.remove(20); - let left = NetworkInfo::from_network_list(&mut network); + let left = NetworkInfo::from_network_list(&mut network).unwrap(); assert_eq!(left.network_id, NetworkId(0)); } } diff --git a/src/message/signalproxy/translation.rs b/src/message/signalproxy/translation.rs index f120026..7121032 100644 --- a/src/message/signalproxy/translation.rs +++ b/src/message/signalproxy/translation.rs @@ -91,7 +91,10 @@ //! ]) //! }) //! ``` -use crate::primitive::{Variant, VariantList}; +use crate::{ + primitive::{Variant, VariantList}, + ProtocolError, +}; #[deprecated( since = "0.1.0", @@ -116,6 +119,8 @@ where } pub trait NetworkList { - fn to_network_list(&self) -> VariantList; - fn from_network_list(input: &mut VariantList) -> Self; + fn to_network_list(&self) -> Result<VariantList, ProtocolError>; + fn from_network_list(input: &mut VariantList) -> Result<Self, ProtocolError> + where + Self: std::marker::Sized; } diff --git a/src/primitive/bufferid.rs b/src/primitive/bufferid.rs index 9d780c6..88b56fa 100644 --- a/src/primitive/bufferid.rs +++ b/src/primitive/bufferid.rs @@ -48,12 +48,12 @@ impl UserType for BufferId { // TODO this is not correct usage, it's technically not really network repr were converting from // but just the conversion of VariantList -> Self directly impl NetworkList for Vec<BufferId> { - fn to_network_list(&self) -> super::VariantList { - self.iter().map(|b| Variant::BufferId(*b)).collect() + fn to_network_list(&self) -> Result<super::VariantList, ProtocolError> { + Ok(self.iter().map(|b| Variant::BufferId(*b)).collect()) } - fn from_network_list(input: &mut super::VariantList) -> Self { - input.iter().map(|b| b.try_into().unwrap()).collect() + fn from_network_list(input: &mut super::VariantList) -> Result<Self, ProtocolError> { + input.iter().map(|b| b.try_into()).collect() } } diff --git a/src/primitive/message.rs b/src/primitive/message.rs index e558570..819ddd1 100644 --- a/src/primitive/message.rs +++ b/src/primitive/message.rs @@ -143,7 +143,7 @@ impl Deserialize for Message { Self { msg_id, timestamp, - msg_type: MessageType::from_bits(msg_type).unwrap(), + msg_type: MessageType::from_bits(msg_type).ok_or(ProtocolError::UnknownMsgType)?, flags, buffer, sender, @@ -195,7 +195,7 @@ impl<T> crate::message::NetworkList for HashMap<T, MessageType> where T: std::convert::TryFrom<Variant> + Into<Variant> + Clone + std::hash::Hash + std::cmp::Eq, { - fn to_network_list(&self) -> VariantList { + fn to_network_list(&self) -> Result<VariantList, ProtocolError> { let mut res = Vec::with_capacity(self.len() * 2); self.iter().for_each(|(k, v)| { @@ -203,10 +203,10 @@ where res.push((*v).clone().bits().into()); }); - res + Ok(res) } - fn from_network_list(input: &mut VariantList) -> Self { + fn from_network_list(input: &mut VariantList) -> Result<Self, ProtocolError> { use itertools::Itertools; let mut res = HashMap::with_capacity(input.len() / 2); @@ -224,7 +224,7 @@ where ); }); - res + Ok(res) } } diff --git a/src/primitive/peerptr.rs b/src/primitive/peerptr.rs index f5fc042..dc4f676 100644 --- a/src/primitive/peerptr.rs +++ b/src/primitive/peerptr.rs @@ -40,7 +40,7 @@ mod tests { // let test_bytes: &[u8] = &[ // 0, 0, 0, 7, 80, 101, 101, 114, 80, 116, 114, 0, 0, 0, 0, 0, 0, 0, 1, // ]; - // let (len, res) = PeerPtr::parse(test_bytes).unwrap(); + // let (len, res) = PeerPtr::parse(test_bytes)?; // assert_eq!(len, test_bytes.len()); // assert_eq!(res, PeerPtr(1)); // } diff --git a/src/primitive/string.rs b/src/primitive/string.rs index 0d3e344..31492ae 100644 --- a/src/primitive/string.rs +++ b/src/primitive/string.rs @@ -99,7 +99,7 @@ impl Deserialize for String { pos += slen; } - let res: String = String::from_utf16(&chars).unwrap(); + let res: String = String::from_utf16(&chars)?; trace!("parsed string: {}", res); Ok((pos, res)) } diff --git a/src/primitive/variant.rs b/src/primitive/variant.rs index f39d405..b201b46 100644 --- a/src/primitive/variant.rs +++ b/src/primitive/variant.rs @@ -92,7 +92,7 @@ where T: std::convert::TryFrom<Variant> + Into<Variant> + Clone + std::hash::Hash + std::cmp::Eq, S: std::convert::TryFrom<Variant> + Into<Variant> + Clone + std::hash::Hash + std::cmp::Eq, { - fn to_network_list(&self) -> VariantList { + fn to_network_list(&self) -> Result<VariantList, ProtocolError> { let mut res = Vec::with_capacity(self.len() * 2); self.iter().for_each(|(k, v)| { @@ -100,10 +100,10 @@ where res.push((*v).clone().into()); }); - res + Ok(res) } - fn from_network_list(input: &mut VariantList) -> Self { + fn from_network_list(input: &mut VariantList) -> Result<Self, ProtocolError> { let mut res = HashMap::with_capacity(input.len() / 2); input.iter().tuples().for_each(|(k, v)| { @@ -119,7 +119,7 @@ where ); }); - res + Ok(res) } } diff --git a/src/session.rs b/src/session.rs index c30551e..945c7fd 100644 --- a/src/session.rs +++ b/src/session.rs @@ -72,7 +72,7 @@ pub trait SessionManager { Class::CoreData => Ok(()), Class::HighlightRuleManager => self.highlight_rule_manager().sync(msg), Class::Identity => { - let identity_id: i32 = msg.object_name.parse().unwrap(); + let identity_id: i32 = msg.object_name.parse()?; if let Some(identity) = self.identity(identity_id as usize) { identity.sync(msg)?; } else { @@ -83,7 +83,7 @@ pub trait SessionManager { Class::IgnoreListManager => self.ignore_list_manager().sync(msg), Class::CertManager => self.cert_manager().sync(msg), Class::Network => { - let id: i32 = msg.object_name.parse().unwrap(); + let id: i32 = msg.object_name.parse()?; if let Some(network) = self.network(id) { network.sync(msg)?; } @@ -103,8 +103,13 @@ pub trait SessionManager { }, Class::IrcChannel => { let mut object_name = msg.object_name.split('/'); - let network_id: i32 = object_name.next().unwrap().parse().unwrap(); - let channel = object_name.next().unwrap(); + let network_id: i32 = object_name + .next() + .ok_or_else(|| ProtocolError::MissingField("NetworkId".to_string()))? + .parse()?; + let channel = object_name + .next() + .ok_or_else(|| ProtocolError::MissingField("Channel".to_string()))?; debug!("Syncing IrcChannel {} in Network {:?}", channel, network_id); @@ -121,11 +126,11 @@ pub trait SessionManager { let mode: char = get_param!(msg); let mode_type: ChannelModeType = network.get_channel_mode_type(mode); - network.irc_channels.get_mut(channel).unwrap().add_channel_mode( - mode_type, - mode, - get_param!(msg), - ); + network + .irc_channels + .get_mut(channel) + .ok_or_else(|| ProtocolError::MissingField(channel.to_string()))? + .add_channel_mode(mode_type, mode, get_param!(msg)); Ok(()) } "removeChannelMode" => { @@ -136,11 +141,15 @@ pub trait SessionManager { network .irc_channels .get_mut(channel) - .unwrap() + .ok_or_else(|| ProtocolError::MissingField(channel.to_string()))? .remove_channel_mode(mode_type, mode, get_param!(msg)); Ok(()) } - _ => network.irc_channels.get_mut(channel).unwrap().sync(msg.clone()), + _ => network + .irc_channels + .get_mut(channel) + .ok_or_else(|| ProtocolError::MissingField(channel.to_string()))? + .sync(msg.clone()), }?; } } @@ -148,8 +157,13 @@ pub trait SessionManager { } Class::IrcUser => { let mut object_name = msg.object_name.split('/'); - let network_id: i32 = object_name.next().unwrap().parse().unwrap(); - let user = object_name.next().unwrap(); + let network_id: i32 = object_name + .next() + .ok_or_else(|| ProtocolError::MissingField("NetworkId".to_string()))? + .parse()?; + let user = object_name + .next() + .ok_or_else(|| ProtocolError::MissingField("User".to_string()))?; debug!("Syncing IrcUser {} in Network {:?}", user, network_id); @@ -177,32 +191,39 @@ pub trait SessionManager { /// Handles an [InitData] messages and initializes the SessionManagers Objects. /// TODO handle automatic sending of InitRequest for whatever objects will need that. - fn init(&mut self, data: InitData) { + fn init(&mut self, data: InitData) -> Result<(), ProtocolError> { match data.init_data { Types::AliasManager(data) => self.alias_manager().init(*data), Types::BufferSyncer(data) => self.buffer_syncer().init(*data), Types::BufferViewConfig(data) => self.buffer_view_manager().init_buffer_view_config(*data), Types::BufferViewManager(data) => self.buffer_view_manager().init(*data), - Types::CoreData(data) => self.core_info().set_core_data(*data), + Types::CoreData(data) => self.core_info().set_core_data(*data)?, Types::HighlightRuleManager(data) => self.highlight_rule_manager().init(*data), Types::IgnoreListManager(data) => self.ignore_list_manager().init(*data), Types::CertManager(data) => self.cert_manager().init(*data), Types::Network(network) => { - let id: NetworkId = NetworkId(data.object_name.parse().unwrap()); + let id: NetworkId = NetworkId(data.object_name.parse()?); self.networks().insert(id, *network); } Types::NetworkInfo(_) => (), Types::NetworkConfig(_) => (), Types::IrcChannel(channel) => { let mut name = data.object_name.split("/"); - let id: i32 = name.next().unwrap().parse().unwrap(); - let name = name.next().unwrap(); + let id: i32 = name + .next() + .ok_or_else(|| ProtocolError::MissingField("Irc Channel ID".to_string()))? + .parse()?; + let name = name + .next() + .ok_or_else(|| ProtocolError::MissingField("Irc Channel Name".to_string()))?; if let Some(network) = self.network(id) { network.add_channel(name, *channel) } } Types::Unknown(_) => (), - } + }; + + Ok(()) } } diff --git a/src/util.rs b/src/util.rs index 9c78bdb..1f6fd9c 100644 --- a/src/util.rs +++ b/src/util.rs @@ -51,6 +51,6 @@ macro_rules! s { #[macro_export] macro_rules! get_param { ( $msg:expr ) => { - $msg.params.remove(0).try_into().unwrap() + $msg.params.remove(0).try_into()? }; } |
