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
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
#[cfg(feature = "multipart")]
use crate::multipart::FilePart;
use crate::{
    body::HttpBody,
    error::Error,
    extract::Extract,
    multipart::FormData,
    serde_request::{
        from_str_map, from_str_multi_map, from_str_multi_val, from_str_val, RequestDeserializer,
    },
};
#[cfg(feature = "cookie")]
use cookie::{Cookie, CookieJar};
use headers::{Header, HeaderMapExt};
use http_body_util::{BodyExt, Limited};
use hyper::{body::Bytes, header::AsHeaderName};
use multimap::MultiMap;
use once_cell::sync::OnceCell;
use serde::{de::DeserializeOwned, Deserialize};
use std::{
    any::Any,
    collections::HashMap,
    net::SocketAddr,
    ops::{Deref, DerefMut},
    sync::Arc,
};

pub struct Request {
    inner: hyper::http::Request<HttpBody>,
    pub params: HashMap<String, String>,
    queries: OnceCell<MultiMap<String, String>>,
    pub(crate) form_data: tokio::sync::OnceCell<FormData>,
    pub(crate) payload: tokio::sync::OnceCell<Bytes>,
    #[cfg(feature = "cookie")]
    pub cookies: CookieJar,
    depot: HashMap<String, Box<dyn Any + Send + Sync>>,
}
impl Request {
    #[inline]
    pub(crate) fn new(inner: hyper::http::Request<HttpBody>) -> Self {
        // Set the request cookies, if they exist.
        #[cfg(feature = "cookie")]
        let cookies = if let Some(cookie_iter) = inner
            .headers()
            .get("Cookie")
            .and_then(|cookies| cookies.to_str().ok())
            .map(|cookies_str| cookies_str.split(';').map(|s| s.trim()))
            .map(|cookie_iter| {
                cookie_iter.filter_map(|cookie_s| Cookie::parse_encoded(cookie_s.to_string()).ok())
            }) {
            let mut jar = CookieJar::new();
            cookie_iter.for_each(|c| jar.add_original(c));
            jar
        } else {
            CookieJar::new()
        };
        Request {
            inner,
            params: HashMap::new(),
            queries: OnceCell::new(),
            form_data: tokio::sync::OnceCell::new(),
            payload: tokio::sync::OnceCell::new(),
            #[cfg(feature = "cookie")]
            cookies,
            depot: HashMap::new(),
        }
    }
    /// Get `Cookie` from cookies.
    #[cfg(feature = "cookie")]
    #[inline]
    pub fn cookie(&self, name: &str) -> Option<&Cookie<'static>> {
        self.cookies.get(name)
    }
    /// Parse cookies as type `T` from request.
    #[cfg(feature = "cookie")]
    #[inline]
    pub fn parse_cookies<'de, T>(&'de self) -> Result<T, Error>
    where
        T: Deserialize<'de>,
    {
        let iter = self.cookies.iter().map(|c| c.name_value());
        from_str_map(iter).map_err(Error::Deserialize)
    }
    /// Get accept.
    #[inline]
    pub fn accept(&self) -> Vec<mime::Mime> {
        let mut list: Vec<mime::Mime> = vec![];
        if let Some(accept) = self
            .inner
            .headers()
            .get("accept")
            .and_then(|h| h.to_str().ok())
        {
            let parts: Vec<&str> = accept.split(',').collect();
            for part in parts {
                if let Ok(mt) = part.parse() {
                    list.push(mt);
                }
            }
        }
        list
    }
    /// Get first accept.
    #[inline]
    pub fn first_accept(&self) -> Option<mime::Mime> {
        let mut accept = self.accept();
        if !accept.is_empty() {
            Some(accept.remove(0))
        } else {
            None
        }
    }
    /// Tries to find the header by name, and then decode it into `headers::Header`.
    #[inline]
    pub fn headers_typed_get<T: Header>(&self) -> Option<T> {
        self.inner.headers().typed_get()
    }
    /// Get header with supplied name and try to parse to a 'T', returns None if failed or not found.
    #[inline]
    pub fn header<'de, T>(&'de self, key: impl AsHeaderName) -> Option<T>
    where
        T: Deserialize<'de>,
    {
        let values = self
            .inner
            .headers()
            .get_all(key)
            .iter()
            .filter_map(|v| v.to_str().ok())
            .collect::<Vec<_>>();
        from_str_multi_val(values).ok()
    }
    /// Parse headers as type `T` from request.
    #[inline]
    pub fn parse_header<'de, T>(&'de self) -> Result<T, Error>
    where
        T: Deserialize<'de>,
    {
        let iter = self
            .inner
            .headers()
            .iter()
            .map(|(k, v)| (k.as_str(), v.to_str().unwrap_or_default()));
        from_str_map(iter).map_err(Error::Deserialize)
    }
    /// Get request remote address.
    #[inline]
    pub fn remote_addr(&self) -> SocketAddr {
        **self.extensions().get::<Arc<SocketAddr>>().unwrap()
    }
    /// Get param value from params.
    #[inline]
    pub fn param<'de, T>(&'de self, key: &str) -> Option<T>
    where
        T: serde::Deserialize<'de>,
    {
        self.params.get(key).and_then(|v| from_str_val(v).ok())
    }
    /// Parse url params as type `T` from request.
    #[inline]
    pub fn parse_param<'de, T>(&'de self) -> Result<T, Error>
    where
        T: serde::Deserialize<'de>,
    {
        let params = self.params.iter();
        from_str_map(params).map_err(Error::Deserialize)
    }
    /// Get queries reference.
    #[inline]
    pub fn queries(&self) -> &MultiMap<String, String> {
        self.queries.get_or_init(|| {
            form_urlencoded::parse(self.inner.uri().query().unwrap_or("").as_bytes())
                .into_owned()
                .collect()
        })
    }
    /// Get query value from queries.
    #[inline]
    pub fn query<'de, T>(&'de self, key: &str) -> Option<T>
    where
        T: serde::Deserialize<'de>,
    {
        self.queries()
            .get_vec(key)
            .and_then(|vs| from_str_multi_val(vs).ok())
    }
    /// Parse queries as type `T` from request.
    #[inline]
    pub fn parse_query<'de, T>(&'de self) -> Result<T, Error>
    where
        T: serde::Deserialize<'de>,
    {
        let queries = self.queries().iter_all();
        from_str_multi_map(queries).map_err(Error::Deserialize)
    }
    /// Get content type. return Option<mime::Mime>
    #[inline]
    pub fn content_type(&self) -> Option<mime::Mime> {
        self.inner
            .headers()
            .get("content-type")
            .and_then(|h| h.to_str().ok())
            .and_then(|v| v.parse().ok())
    }
    /// Get content type. return Option<&str>
    #[inline]
    pub fn content_type_str(&self) -> Option<&str> {
        self.inner
            .headers()
            .get("content-type")
            .and_then(|h| h.to_str().ok())
    }
    /// Get Bytes from request body
    #[inline]
    pub async fn payload(&mut self) -> Result<&Bytes, Error> {
        let body = std::mem::replace(self.body_mut(), HttpBody::Empty);
        self.payload
            .get_or_try_init(|| async {
                Ok(Limited::new(body, 64 * 1024)
                    .collect()
                    .await
                    .map_err(Error::Boxed)?
                    .to_bytes())
            })
            .await
    }
    /// Get `FormData` reference from request.
    #[inline]
    pub async fn form_data(&mut self) -> Result<&FormData, Error> {
        let body = std::mem::replace(self.body_mut(), HttpBody::Empty);
        let ctype = self.content_type_str();
        self.form_data
            .get_or_try_init(|| async { FormData::new(ctype, body).await })
            .await
    }
    /// Get field data from form.
    #[inline]
    pub async fn form<'de, T>(&'de mut self, key: &str) -> Option<T>
    where
        T: serde::Deserialize<'de>,
    {
        self.form_data()
            .await
            .ok()
            .and_then(|ps| ps.fields.get_vec(key))
            .and_then(|vs| from_str_multi_val(vs).ok())
    }
    #[cfg(feature = "multipart")]
    /// Get [`FilePart`] reference from request.
    #[inline]
    pub async fn file<'a>(&'a mut self, key: &'a str) -> Option<&'a FilePart> {
        self.form_data().await.ok().and_then(|ps| ps.files.get(key))
    }
    #[cfg(feature = "multipart")]
    /// Get [`FilePart`] list reference from request.
    #[inline]
    pub async fn files<'a>(&'a mut self, key: &'a str) -> Option<&'a Vec<FilePart>> {
        self.form_data()
            .await
            .ok()
            .and_then(|ps| ps.files.get_vec(key))
    }
    #[cfg(feature = "multipart")]
    #[inline]
    pub async fn upload(&mut self, key: &str, save_path: &str) -> Result<u64, Error> {
        if let Some(file) = self.file(key).await {
            std::fs::create_dir_all(save_path)?;
            let dest = format!("{}/{}", save_path, file.name.as_deref().unwrap());
            Ok(std::fs::copy(&file.path, std::path::Path::new(&dest))?)
        } else {
            Err(Error::Other(String::from(
                "File not resolved from current request",
            )))
        }
    }
    #[cfg(feature = "multipart")]
    #[inline]
    pub async fn uploads(&mut self, key: &str, save_path: &str) -> Result<String, Error> {
        if let Some(files) = self.files(key).await {
            std::fs::create_dir_all(save_path)?;
            let mut msgs = Vec::with_capacity(files.len());
            for file in files {
                let dest = format!("{}/{}", save_path, file.name.as_deref().unwrap());
                if let Err(e) = std::fs::copy(&file.path, std::path::Path::new(&dest)) {
                    return Ok(format!("file not found in request: {e}"));
                } else {
                    msgs.push(dest);
                }
            }
            Ok(format!("Files uploaded:\n\n{}", msgs.join("\n")))
        } else {
            Err(Error::Other(String::from(
                "Files not resolved from current request",
            )))
        }
    }
    #[inline]
    async fn inner_parse_json<'de, T>(&'de mut self) -> Result<T, Error>
    where
        T: Deserialize<'de>,
    {
        self.payload()
            .await
            .and_then(|payload| serde_json::from_slice::<T>(payload).map_err(Error::SerdeJson))
    }
    /// Parse json body as type `T` from request with default max size limit.
    #[inline]
    pub async fn parse_json<'de, T>(&'de mut self) -> Result<T, Error>
    where
        T: Deserialize<'de>,
    {
        let ctype = self.content_type();
        if let Some(ctype) = ctype {
            if ctype.subtype() == mime::JSON {
                return self.inner_parse_json().await;
            }
        }
        Err(Error::Other(String::from("Invalid request Context-Type")))
    }
    #[inline]
    async fn inner_parse_form<'de, T>(&'de mut self) -> Result<T, Error>
    where
        T: Deserialize<'de>,
    {
        from_str_multi_map(self.form_data().await?.fields.iter_all()).map_err(Error::Deserialize)
    }
    /// Parse form body as type `T` from request.
    #[inline]
    pub async fn parse_form<'de, T>(&'de mut self) -> Result<T, Error>
    where
        T: Deserialize<'de>,
    {
        if let Some(ctype) = self.content_type() {
            if ctype.subtype() == mime::WWW_FORM_URLENCODED || ctype.subtype() == mime::FORM_DATA {
                return self.inner_parse_form().await;
            }
        }
        Err(Error::Other(String::from("Invalid request Context-Type")))
    }
    /// Parse Request Body as type `T`
    #[inline]
    pub async fn parse_body<T>(&mut self) -> Result<T, Error>
    where
        T: DeserializeOwned,
    {
        let ctype = self.content_type_str();
        match ctype {
            Some(ctype) if ctype == "application/json" => self.inner_parse_json().await,
            Some(ctype)
                if ctype == "application/x-www-form-urlencoded"
                    || ctype.starts_with("multipart/form-data") =>
            {
                self.inner_parse_form().await
            }
            #[cfg(feature = "cbor")]
            Some(ctype) if ctype == "application/cbor" => {
                self.payload().await.and_then(|payload| {
                    ciborium::de::from_reader(&payload[..]).map_err(|e| Error::Other(e.to_string()))
                })
            }
            #[cfg(feature = "msgpack")]
            Some(ctype) if ctype == "application/msgpack" => self
                .payload()
                .await
                .and_then(|payload| rmp_serde::from_slice(&payload).map_err(Error::MsgpackDe)),
            _ => Err(Error::Other(String::from("Invalid request Context-Type"))),
        }
    }
    /// Extract request as type `T` from request's different parts.
    #[inline]
    pub async fn extract<'de, T>(&'de mut self) -> Result<T, Error>
    where
        T: Extract<'de> + Send,
    {
        Ok(T::deserialize(
            RequestDeserializer::new(self, T::metadata()).await?,
        )?)
    }
    /// Inserts a key-value pair into the request depot.
    #[inline]
    pub fn insert<K, V>(&mut self, key: K, value: V)
    where
        K: Into<String>,
        V: Any + Send + Sync,
    {
        self.depot.insert(key.into(), Box::new(value));
    }
    /// Immutably borrows value from request depot.
    #[inline]
    pub fn get<V: Any + Send + Sync>(&self, key: &str) -> Option<&V> {
        if let Some(value) = self.depot.get(key) {
            value.downcast_ref::<V>()
        } else {
            None
        }
    }
    /// Mutably borrows value from request depot.
    #[inline]
    pub fn get_mut<V: Any + Send + Sync>(&mut self, key: &str) -> Option<&mut V> {
        if let Some(value) = self.depot.get_mut(key) {
            value.downcast_mut::<V>()
        } else {
            None
        }
    }
    /// Remove value from depot and returning the value at the key if the key was previously in the request depot.
    #[inline]
    pub fn remove<V: Any + Send + Sync>(&mut self, key: &str) -> Option<V> {
        if let Some(value) = self.depot.remove(key) {
            value.downcast::<V>().ok().map(|b| *b)
        } else {
            None
        }
    }
}
impl Deref for Request {
    type Target = hyper::Request<HttpBody>;
    #[inline]
    fn deref(&self) -> &Self::Target {
        &self.inner
    }
}
impl DerefMut for Request {
    #[inline]
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.inner
    }
}
#[cfg(feature = "session")]
impl Request {
    /// Set session into this depot
    #[inline]
    pub fn set_session(&mut self, session: async_session::Session) -> &mut Self {
        self.insert("::hypers::session", session);
        self
    }
    /// Take session from this depot
    #[inline]
    pub fn take_session(&mut self) -> Option<async_session::Session> {
        self.remove("::hypers::session")
    }
    /// Get session reference from this depot
    #[inline]
    pub fn session(&self) -> Option<&async_session::Session> {
        self.get("::hypers::session")
    }
    /// Get session mutable reference from this depot
    #[inline]
    pub fn session_mut(&mut self) -> Option<&mut async_session::Session> {
        self.get_mut("::hypers::session")
    }
}