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
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
use std::{any::TypeId, convert::Infallible, error::Error, fmt, future::Future};

use crate::{
    core::{context::Ref, handler::HandlerInput},
    types::{
        CallbackQuery, Chat, ChatJoinRequest, ChatMemberUpdated, ChatPeerId, ChatUsername, ChosenInlineResult, Command,
        CommandError, InlineQuery, Message, Poll, PollAnswer, PreCheckoutQuery, ShippingQuery, Text, Update, User,
        UserPeerId, UserUsername,
    },
};

#[cfg(test)]
mod tests;

/// Allows to create a specific handler input.
pub trait TryFromInput: Send + Sized {
    /// An error when conversion failed.
    type Error: Error + Send;

    /// Performs conversion.
    ///
    /// # Arguments
    ///
    /// * `input` - An input to convert from.
    fn try_from_input(input: HandlerInput) -> impl Future<Output = Result<Option<Self>, Self::Error>> + Send;
}

impl TryFromInput for HandlerInput {
    type Error = Infallible;

    async fn try_from_input(input: HandlerInput) -> Result<Option<Self>, Self::Error> {
        Ok(Some(input))
    }
}

impl TryFromInput for () {
    type Error = Infallible;

    async fn try_from_input(_input: HandlerInput) -> Result<Option<Self>, Self::Error> {
        Ok(Some(()))
    }
}

impl<T> TryFromInput for Ref<T>
where
    T: Clone + Send + 'static,
{
    type Error = ConvertInputError;

    async fn try_from_input(input: HandlerInput) -> Result<Option<Self>, Self::Error> {
        input
            .context
            .get::<T>()
            .cloned()
            .map(Ref::new)
            .ok_or_else(ConvertInputError::context::<T>)
            .map(Some)
    }
}

impl TryFromInput for Update {
    type Error = Infallible;

    async fn try_from_input(input: HandlerInput) -> Result<Option<Self>, Self::Error> {
        Ok(Some(input.update))
    }
}

impl TryFromInput for ChatPeerId {
    type Error = Infallible;

    async fn try_from_input(input: HandlerInput) -> Result<Option<Self>, Self::Error> {
        Ok(input.update.get_chat_id())
    }
}

impl TryFromInput for ChatUsername {
    type Error = Infallible;

    async fn try_from_input(input: HandlerInput) -> Result<Option<Self>, Self::Error> {
        Ok(input.update.get_chat_username().cloned())
    }
}

impl TryFromInput for Chat {
    type Error = Infallible;

    async fn try_from_input(input: HandlerInput) -> Result<Option<Self>, Self::Error> {
        Ok(input.update.get_chat().cloned())
    }
}

impl TryFromInput for UserPeerId {
    type Error = Infallible;

    async fn try_from_input(input: HandlerInput) -> Result<Option<Self>, Self::Error> {
        Ok(input.update.get_user_id())
    }
}

impl TryFromInput for UserUsername {
    type Error = Infallible;

    async fn try_from_input(input: HandlerInput) -> Result<Option<Self>, Self::Error> {
        Ok(input.update.get_user_username().cloned())
    }
}

impl TryFromInput for User {
    type Error = Infallible;

    async fn try_from_input(input: HandlerInput) -> Result<Option<Self>, Self::Error> {
        Ok(input.update.get_user().cloned())
    }
}

impl TryFromInput for Text {
    type Error = Infallible;

    async fn try_from_input(input: HandlerInput) -> Result<Option<Self>, Self::Error> {
        Ok(Message::try_from(input.update).ok().and_then(|x| x.get_text().cloned()))
    }
}

impl TryFromInput for Message {
    type Error = Infallible;

    async fn try_from_input(input: HandlerInput) -> Result<Option<Self>, Self::Error> {
        Ok(input.update.try_into().ok())
    }
}

impl TryFromInput for Command {
    type Error = CommandError;

    async fn try_from_input(input: HandlerInput) -> Result<Option<Self>, Self::Error> {
        Message::try_from(input.update)
            .ok()
            .map(Command::try_from)
            .transpose()
            .or_else(|err| match err {
                CommandError::NotFound => Ok(None),
                err => Err(err),
            })
    }
}

impl TryFromInput for InlineQuery {
    type Error = Infallible;

    async fn try_from_input(input: HandlerInput) -> Result<Option<Self>, Self::Error> {
        Ok(input.update.try_into().ok())
    }
}

impl TryFromInput for ChosenInlineResult {
    type Error = Infallible;

    async fn try_from_input(input: HandlerInput) -> Result<Option<Self>, Self::Error> {
        Ok(input.update.try_into().ok())
    }
}

impl TryFromInput for CallbackQuery {
    type Error = Infallible;

    async fn try_from_input(input: HandlerInput) -> Result<Option<Self>, Self::Error> {
        Ok(input.update.try_into().ok())
    }
}

impl TryFromInput for ShippingQuery {
    type Error = Infallible;

    async fn try_from_input(input: HandlerInput) -> Result<Option<Self>, Self::Error> {
        Ok(input.update.try_into().ok())
    }
}

impl TryFromInput for PreCheckoutQuery {
    type Error = Infallible;

    async fn try_from_input(input: HandlerInput) -> Result<Option<Self>, Self::Error> {
        Ok(input.update.try_into().ok())
    }
}

impl TryFromInput for Poll {
    type Error = Infallible;

    async fn try_from_input(input: HandlerInput) -> Result<Option<Self>, Self::Error> {
        Ok(input.update.try_into().ok())
    }
}

impl TryFromInput for PollAnswer {
    type Error = Infallible;

    async fn try_from_input(input: HandlerInput) -> Result<Option<Self>, Self::Error> {
        Ok(input.update.try_into().ok())
    }
}

impl TryFromInput for ChatMemberUpdated {
    type Error = Infallible;

    async fn try_from_input(input: HandlerInput) -> Result<Option<Self>, Self::Error> {
        Ok(input.update.try_into().ok())
    }
}

impl TryFromInput for ChatJoinRequest {
    type Error = Infallible;

    async fn try_from_input(input: HandlerInput) -> Result<Option<Self>, Self::Error> {
        Ok(input.update.try_into().ok())
    }
}

macro_rules! convert_tuple {
    ($($T:ident),+) => {
        #[allow(non_snake_case)]
        impl<$($T),+> TryFromInput for ($($T,)+)
        where
            $(
                $T: TryFromInput,
                $T::Error: 'static,
            )+
        {
            type Error = ConvertInputError;

            async fn try_from_input(input: HandlerInput) -> Result<Option<Self>, Self::Error> {
                $(
                    let $T = match <$T>::try_from_input(
                        input.clone()
                    ).await.map_err(ConvertInputError::tuple)? {
                        Some(v) => v,
                        None => return Ok(None)
                    };
                )+
                Ok(Some(($($T,)+)))
            }
        }
    };
}

convert_tuple!(A);
convert_tuple!(A, B);
convert_tuple!(A, B, C);
convert_tuple!(A, B, C, D);
convert_tuple!(A, B, C, D, E);
convert_tuple!(A, B, C, D, E, F);
convert_tuple!(A, B, C, D, E, F, G);
convert_tuple!(A, B, C, D, E, F, G, H);
convert_tuple!(A, B, C, D, E, F, G, H, I);
convert_tuple!(A, B, C, D, E, F, G, H, I, J);

/// An error when converting a [`HandlerInput`].
#[derive(Debug)]
pub enum ConvertInputError {
    /// Object is not found in the [`crate::Context`].
    Context(TypeId),
    /// Unable to convert [`HandlerInput`] into a tuple of specific inputs.
    ///
    /// Contains a first occurred error.
    Tuple(Box<dyn Error + Send>),
}

impl ConvertInputError {
    fn context<T: 'static>() -> Self {
        Self::Context(TypeId::of::<T>())
    }

    fn tuple<E: Error + Send + 'static>(err: E) -> Self {
        Self::Tuple(Box::new(err))
    }
}

impl Error for ConvertInputError {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        use self::ConvertInputError::*;
        match self {
            Context(_) => None,
            Tuple(err) => err.source(),
        }
    }
}

impl fmt::Display for ConvertInputError {
    fn fmt(&self, out: &mut fmt::Formatter) -> fmt::Result {
        use self::ConvertInputError::*;
        match self {
            Context(type_id) => write!(out, "Object of type {:?} not found in context", type_id),
            Tuple(err) => write!(out, "Unable to convert HandlerInput into tuple: {}", err),
        }
    }
}