1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
// Copyright 2021 Jonas Platte
// Copyright 2022 Famedly GmbH
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

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};

/// Context for an event handler.
///
/// This trait defines the set of types that may be used as additional arguments
/// in event handler functions after the event itself.
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())
    }
}

/// This event handler context argument is only applicable to room-specific
/// events.
///
/// Trying to use it in the event handler for another event, for example a
/// global account data or presence event, will result in the event handler
/// being skipped and an error getting logged.
impl EventHandlerContext for Room {
    fn from_data(data: &EventHandlerData<'_>) -> Option<Self> {
        data.room.clone()
    }
}

/// The raw JSON form of an event.
///
/// Used as a context argument for event handlers (see
/// [`Client::add_event_handler`]).
#[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())
    }
}

/// A custom value registered with
/// [`.add_event_handler_context`][Client::add_event_handler_context].
#[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
    }
}

// `EventHandlerContext` for tuples.

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);