matrix_sdk/event_handler/
context.rs

1// Copyright 2021 Jonas Platte
2// Copyright 2022 Famedly GmbH
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8//     http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16use std::ops::Deref;
17
18use matrix_sdk_base::deserialized_responses::EncryptionInfo;
19use ruma::push::Action;
20use serde_json::value::RawValue as RawJsonValue;
21
22use super::{EventHandlerData, EventHandlerHandle};
23use crate::{Client, Room};
24
25/// Context for an event handler.
26///
27/// This trait defines the set of types that may be used as additional arguments
28/// in event handler functions after the event itself.
29pub trait EventHandlerContext: Sized {
30    #[doc(hidden)]
31    fn from_data(_: &EventHandlerData<'_>) -> Option<Self>;
32}
33
34impl EventHandlerContext for Client {
35    fn from_data(data: &EventHandlerData<'_>) -> Option<Self> {
36        Some(data.client.clone())
37    }
38}
39
40impl EventHandlerContext for EventHandlerHandle {
41    fn from_data(data: &EventHandlerData<'_>) -> Option<Self> {
42        Some(data.handle.clone())
43    }
44}
45
46/// This event handler context argument is only applicable to room-specific
47/// events.
48///
49/// Trying to use it in the event handler for another event, for example a
50/// global account data or presence event, will result in the event handler
51/// being skipped and an error getting logged.
52impl EventHandlerContext for Room {
53    fn from_data(data: &EventHandlerData<'_>) -> Option<Self> {
54        data.room.clone()
55    }
56}
57
58/// The raw JSON form of an event.
59///
60/// Used as a context argument for event handlers (see
61/// [`Client::add_event_handler`]).
62#[derive(Clone, Debug)]
63pub struct RawEvent(pub Box<RawJsonValue>);
64
65impl Deref for RawEvent {
66    type Target = RawJsonValue;
67
68    fn deref(&self) -> &Self::Target {
69        &self.0
70    }
71}
72
73impl EventHandlerContext for RawEvent {
74    fn from_data(data: &EventHandlerData<'_>) -> Option<Self> {
75        Some(Self(data.raw.to_owned()))
76    }
77}
78
79impl EventHandlerContext for Option<EncryptionInfo> {
80    fn from_data(data: &EventHandlerData<'_>) -> Option<Self> {
81        Some(data.encryption_info.cloned())
82    }
83}
84
85impl EventHandlerContext for Vec<Action> {
86    fn from_data(data: &EventHandlerData<'_>) -> Option<Self> {
87        Some(data.push_actions.to_owned())
88    }
89}
90
91/// A custom value registered with
92/// [`.add_event_handler_context`][Client::add_event_handler_context].
93#[derive(Debug)]
94pub struct Ctx<T>(pub T);
95
96impl<T: Clone + Send + Sync + 'static> EventHandlerContext for Ctx<T> {
97    fn from_data(data: &EventHandlerData<'_>) -> Option<Self> {
98        let map = data.client.inner.event_handlers.context.read().unwrap();
99        map.get::<T>().cloned().map(Ctx)
100    }
101}
102
103impl<T> Deref for Ctx<T> {
104    type Target = T;
105
106    fn deref(&self) -> &Self::Target {
107        &self.0
108    }
109}
110
111// `EventHandlerContext` for tuples.
112
113impl EventHandlerContext for () {
114    fn from_data(_data: &EventHandlerData<'_>) -> Option<Self> {
115        Some(())
116    }
117}
118
119macro_rules! impl_context_for_tuple {
120    ( $( $ty:ident ),* $(,)? ) => {
121        #[allow(non_snake_case)]
122        impl< $( $ty ),* > EventHandlerContext for ( $( $ty ),* , )
123        where
124            $( $ty : EventHandlerContext, )*
125        {
126            fn from_data(data: &EventHandlerData<'_>) -> Option<Self> {
127                $(
128                    let $ty = $ty ::from_data(data)?;
129                )*
130
131                Some(( $( $ty ),* , ))
132            }
133        }
134    };
135}
136
137impl_context_for_tuple!(A);
138impl_context_for_tuple!(A, B);
139impl_context_for_tuple!(A, B, C);
140impl_context_for_tuple!(A, B, C, D);
141impl_context_for_tuple!(A, B, C, D, E);
142impl_context_for_tuple!(A, B, C, D, E, F);
143impl_context_for_tuple!(A, B, C, D, E, F, G);
144impl_context_for_tuple!(A, B, C, D, E, F, G, H);