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
use crate::dispatcher::Dispatcher;
use crate::types::Update;
use futures::{future::ok, Future, Stream};
use hyper::{
header::{HeaderValue, ALLOW},
service::{MakeService, Service},
Body, Error, Method, Request, Response, Server, StatusCode,
};
use std::error::Error as StdError;
use std::fmt;
use std::net::SocketAddr;
use std::sync::Arc;
struct WebhookServiceFactory {
path: String,
update_handler: Arc<Box<UpdateHandler + Send + Sync>>,
}
impl WebhookServiceFactory {
fn new<S: Into<String>>(
path: S,
update_handler: Box<UpdateHandler + Send + Sync>,
) -> WebhookServiceFactory {
WebhookServiceFactory {
path: path.into(),
update_handler: Arc::new(update_handler),
}
}
}
#[derive(Debug)]
struct WebhookServiceFactoryError;
impl fmt::Display for WebhookServiceFactoryError {
fn fmt(&self, out: &mut fmt::Formatter) -> fmt::Result {
write!(out, "Failed to create webhook service")
}
}
impl StdError for WebhookServiceFactoryError {}
impl<Ctx> MakeService<Ctx> for WebhookServiceFactory {
type ReqBody = Body;
type ResBody = Body;
type Error = Error;
type Service = WebhookService;
type Future = Box<Future<Item = Self::Service, Error = Self::MakeError> + Send>;
type MakeError = WebhookServiceFactoryError;
fn make_service(&mut self, _ctx: Ctx) -> Self::Future {
Box::new(ok(WebhookService {
path: self.path.clone(),
update_handler: self.update_handler.clone(),
}))
}
}
struct WebhookService {
path: String,
update_handler: Arc<Box<UpdateHandler + Send + Sync>>,
}
impl Service for WebhookService {
type ReqBody = Body;
type ResBody = Body;
type Error = Error;
type Future = Box<Future<Item = Response<Body>, Error = Error> + Send>;
fn call(&mut self, req: Request<Self::ReqBody>) -> Self::Future {
let mut rep = Response::new(Body::empty());
if let Method::POST = *req.method() {
if req.uri().path() == self.path {
let update_handler = self.update_handler.clone();
return Box::new(req.into_body().concat2().map(move |body| {
match serde_json::from_slice::<Update>(&body) {
Ok(update) => {
update_handler.handle(update);
}
Err(err) => {
*rep.status_mut() = StatusCode::BAD_REQUEST;
*rep.body_mut() = err.to_string().into();
}
}
rep
}));
} else {
*rep.status_mut() = StatusCode::NOT_FOUND;
}
} else {
*rep.status_mut() = StatusCode::METHOD_NOT_ALLOWED;
rep.headers_mut()
.insert(ALLOW, HeaderValue::from_static("POST"));
}
Box::new(ok(rep))
}
}
pub trait UpdateHandler {
fn handle(&self, update: Update);
}
pub struct WebhookDispatcher {
dispatcher: Dispatcher,
}
impl WebhookDispatcher {
pub fn new(dispatcher: Dispatcher) -> WebhookDispatcher {
WebhookDispatcher { dispatcher }
}
}
impl UpdateHandler for WebhookDispatcher {
fn handle(&self, update: Update) {
tokio::spawn(self.dispatcher.dispatch(&update).then(|r| {
if let Err(e) = r {
log::error!("Failed to dispatch update: {:?}", e)
}
Ok(())
}));
}
}
pub fn run_server<A, S, H>(addr: A, path: S, update_handler: H)
where
A: Into<SocketAddr>,
S: Into<String>,
H: UpdateHandler + Send + Sync + 'static,
{
let server = Server::bind(&addr.into())
.serve(WebhookServiceFactory::new(path, Box::new(update_handler)))
.map_err(|e| log::error!("Server error: {}", e));
tokio::run(server)
}