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
use std::{
convert::Infallible,
io::Write,
net::{IpAddr, SocketAddr},
};
use crate::{
model::Update,
utils::result::{Result as TelegramResult, TelegramError},
};
use hyper::{
body::HttpBody,
service::{make_service_fn, service_fn},
Body, Method, Request, Response, Server, StatusCode, Uri,
};
use tokio::sync::mpsc::{channel, Receiver, Sender};
#[derive(Debug)]
pub struct Webhook {
opts: WebhookOptions,
}
impl Webhook {
pub fn new(opts: &WebhookOptions) -> Self {
Self { opts: opts.clone() }
}
pub fn start(self) -> Receiver<TelegramResult<Update>> {
let (tx, rx) = channel(1000);
tokio::spawn(start_ws(self.opts, tx));
rx
}
}
async fn handle_update(
payload: HandlingPayload,
req: Request<Body>,
) -> TelegramResult<Response<Body>> {
let mut response = Response::new(Body::empty());
let mut raw_body = req.into_body();
let mut body: Vec<u8> = Vec::new();
while let Some(chunk) = raw_body.data().await {
body.write_all(&chunk?)?;
}
let update: Update = serde_json::from_slice(&body)?;
let send_res = payload.chan.send(Ok(update)).await;
if send_res.is_err() {
return Err(TelegramError::WebhookError.into());
}
*response.status_mut() = StatusCode::OK;
Ok(response)
}
async fn handle_req(
payload: HandlingPayload,
req: Request<Body>,
) -> Result<Response<Body>, Infallible> {
let mut response = Response::new(Body::empty());
match (req.method(), req.uri().path()) {
(&Method::POST, path) if path == payload.path => {
let result = handle_update(payload, req).await;
if result.is_err() {
*response.status_mut() = StatusCode::INTERNAL_SERVER_ERROR;
} else {
response = result.unwrap();
}
}
_ => {
*response.status_mut() = StatusCode::NOT_FOUND;
}
}
Ok(response)
}
async fn start_ws(
opts: WebhookOptions,
chan: Sender<TelegramResult<Update>>,
) -> TelegramResult<()> {
let addr = SocketAddr::from((opts.ip, opts.port));
let payload = HandlingPayload::new(&opts, chan.clone());
let make_svc = make_service_fn(move |_conn| {
let inner_payload = payload.clone();
async move {
Ok::<_, Infallible>(service_fn(move |req| {
handle_req(inner_payload.clone(), req)
}))
}
});
let server = Server::bind(&addr).serve(make_svc);
let graceful = server.with_graceful_shutdown(shutdown_signal());
if let Err(e) = graceful.await {
let send_res = chan
.send(Err(TelegramError::Unknown(e.to_string()).into()))
.await;
if send_res.is_err() {
return Err(TelegramError::WebhookError.into());
}
}
Ok(())
}
async fn shutdown_signal() {
tokio::signal::ctrl_c()
.await
.expect("failed to install CTRL+C signal handler");
}
#[derive(Clone, Debug)]
pub struct WebhookOptions {
pub url: Option<Uri>,
pub path: String,
pub port: u16,
pub ip: IpAddr,
}
impl WebhookOptions {
pub fn new() -> Self {
Self {
url: None,
path: "/".to_owned(),
port: 8006,
ip: [127, 0, 0, 1].into(),
}
}
pub fn set_path(&mut self, path: &str) -> &mut Self {
self.path = path.to_owned();
self
}
pub fn set_port(&mut self, port: u16) -> &mut Self {
self.port = port;
self
}
pub fn set_ip<T: Into<IpAddr>>(&mut self, ip: T) -> &mut Self {
self.ip = ip.into();
self
}
pub fn set_url(&mut self, url: &str) -> TelegramResult<&mut Self> {
self.url = Some(url.parse()?);
Ok(self)
}
fn get_path(&self) -> &str {
self.url
.as_ref()
.map_or_else(|| self.path.as_str(), |url| url.path())
}
}
impl Default for WebhookOptions {
fn default() -> Self {
Self::new()
}
}
#[derive(Clone, Debug)]
struct HandlingPayload {
path: String,
chan: Sender<TelegramResult<Update>>,
}
impl HandlingPayload {
fn new(opts: &WebhookOptions, sender: Sender<TelegramResult<Update>>) -> Self {
Self {
path: opts.get_path().to_owned(),
chan: sender,
}
}
}