Impl AsyncHandler for SessionDispatcher

This commit is contained in:
Temirkhan Myrzamadi 2020-01-30 01:10:02 +06:00
parent 6d737dabb4
commit c98b53b9a8

View file

@ -34,15 +34,22 @@ mod storage;
use crate::{dispatching::AsyncHandler, Bot};
pub use get_chat_id::*;
use std::{future::Future, pin::Pin, sync::Arc};
pub use storage::*;
/// A context of a private message handler.
pub struct SessionHandlerCtx<'a, Upd, Session> {
pub bot: &'a Bot,
pub struct SessionHandlerCtx<Upd, Session> {
pub bot: Arc<Bot>,
pub update: Upd,
pub session: Session,
}
/// A context of a session dispatcher.
pub struct SessionDispatcherCtx<Upd> {
pub bot: Arc<Bot>,
pub update: Upd,
}
/// Continue or terminate a user session.
#[derive(Debug, Copy, Clone, Eq, Hash, PartialEq)]
pub enum SessionState<Session> {
@ -83,17 +90,25 @@ where
handler,
}
}
}
/// Dispatches a single `message` from a private chat.
pub async fn dispatch<Upd>(&'a self, bot: &'a Bot, update: Upd)
impl<'a, Session, H, Upd> AsyncHandler<SessionDispatcherCtx<Upd>, ()>
for SessionDispatcher<'a, Session, H>
where
H: AsyncHandler<
SessionHandlerCtx<'a, Upd, Session>,
SessionState<Session>,
>,
H: AsyncHandler<SessionHandlerCtx<Upd, Session>, SessionState<Session>>,
Upd: GetChatId,
Session: Default,
{
let chat_id = update.chat_id();
/// Dispatches a single `message` from a private chat.
fn handle<'b>(
&'b self,
ctx: SessionDispatcherCtx<Upd>,
) -> Pin<Box<dyn Future<Output = ()> + 'b>>
where
Upd: 'b,
{
Box::pin(async move {
let chat_id = ctx.update.chat_id();
let session = self
.storage
@ -104,8 +119,8 @@ where
if let SessionState::Continue(new_session) = self
.handler
.handle(SessionHandlerCtx {
bot,
update,
bot: ctx.bot,
update: ctx.update,
session,
})
.await
@ -122,5 +137,6 @@ where
);
}
}
})
}
}