use std::ops::Deref;
use matrix_sdk_base::deserialized_responses::EncryptionInfo;
use ruma::push::Action;
use serde_json::value::RawValue as RawJsonValue;
use super::{EventHandlerData, EventHandlerHandle};
use crate::{Client, Room};
pub trait EventHandlerContext: Sized {
#[doc(hidden)]
fn from_data(_: &EventHandlerData<'_>) -> Option<Self>;
}
impl EventHandlerContext for Client {
fn from_data(data: &EventHandlerData<'_>) -> Option<Self> {
Some(data.client.clone())
}
}
impl EventHandlerContext for EventHandlerHandle {
fn from_data(data: &EventHandlerData<'_>) -> Option<Self> {
Some(data.handle.clone())
}
}
impl EventHandlerContext for Room {
fn from_data(data: &EventHandlerData<'_>) -> Option<Self> {
data.room.clone()
}
}
#[derive(Clone, Debug)]
pub struct RawEvent(pub Box<RawJsonValue>);
impl Deref for RawEvent {
type Target = RawJsonValue;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl EventHandlerContext for RawEvent {
fn from_data(data: &EventHandlerData<'_>) -> Option<Self> {
Some(Self(data.raw.to_owned()))
}
}
impl EventHandlerContext for Option<EncryptionInfo> {
fn from_data(data: &EventHandlerData<'_>) -> Option<Self> {
Some(data.encryption_info.cloned())
}
}
impl EventHandlerContext for Vec<Action> {
fn from_data(data: &EventHandlerData<'_>) -> Option<Self> {
Some(data.push_actions.to_owned())
}
}
#[derive(Debug)]
pub struct Ctx<T>(pub T);
impl<T: Clone + Send + Sync + 'static> EventHandlerContext for Ctx<T> {
fn from_data(data: &EventHandlerData<'_>) -> Option<Self> {
let map = data.client.inner.event_handlers.context.read().unwrap();
map.get::<T>().cloned().map(Ctx)
}
}
impl<T> Deref for Ctx<T> {
type Target = T;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl EventHandlerContext for () {
fn from_data(_data: &EventHandlerData<'_>) -> Option<Self> {
Some(())
}
}
macro_rules! impl_context_for_tuple {
( $( $ty:ident ),* $(,)? ) => {
#[allow(non_snake_case)]
impl< $( $ty ),* > EventHandlerContext for ( $( $ty ),* , )
where
$( $ty : EventHandlerContext, )*
{
fn from_data(data: &EventHandlerData<'_>) -> Option<Self> {
$(
let $ty = $ty ::from_data(data)?;
)*
Some(( $( $ty ),* , ))
}
}
};
}
impl_context_for_tuple!(A);
impl_context_for_tuple!(A, B);
impl_context_for_tuple!(A, B, C);
impl_context_for_tuple!(A, B, C, D);
impl_context_for_tuple!(A, B, C, D, E);
impl_context_for_tuple!(A, B, C, D, E, F);
impl_context_for_tuple!(A, B, C, D, E, F, G);
impl_context_for_tuple!(A, B, C, D, E, F, G, H);