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
#[cfg(feature = "file")]
use crate::file::FilePart;
use crate::{
    body::{Form, FromBytes, IncomingBody, Json, Query, QueryTrait},
    error::Error,
};
use cookie::{Cookie, CookieJar};
use headers::{Header, HeaderMapExt};
use http_body_util::BodyExt;
use hyper::body::Bytes;
#[cfg(feature = "file")]
use multimap::MultiMap;
use serde::de::DeserializeOwned;
use std::{
    collections::HashMap,
    net::SocketAddr,
    ops::{Deref, DerefMut},
};

pub struct Request {
    #[doc(hidden)]
    inner: hyper::Request<IncomingBody>,
    #[doc(hidden)]
    params: HashMap<String, String>,
    #[doc(hidden)]
    #[cfg(feature = "file")]
    files: MultiMap<String, FilePart>,
    #[doc(hidden)]
    cookies: CookieJar,
    #[doc(hidden)]
    peer_addr: SocketAddr,
}

impl Request {
    #[doc(hidden)]
    #[inline]
    pub fn new(inner: hyper::Request<IncomingBody>, remote_addr: SocketAddr) -> Self {
        Request {
            inner,
            params: Default::default(),
            #[cfg(feature = "file")]
            files: MultiMap::new(),
            cookies: Default::default(),
            peer_addr: remote_addr,
        }
    }

    #[inline]
    pub fn inner_request(&mut self) -> &mut hyper::Request<IncomingBody> {
        &mut self.inner
    }

    #[inline]
    pub fn header<T: Header>(&self) -> Option<T> {
        self.inner.headers().typed_get()
    }

    #[inline]
    pub fn peer_addr(&self) -> &SocketAddr {
        &self.peer_addr
    }

    #[inline]
    pub fn peer_addr_mut(&mut self) -> &mut SocketAddr {
        &mut self.peer_addr
    }

    #[inline]
    pub fn cookies(&self) -> &CookieJar {
        &self.cookies
    }

    #[inline]
    pub fn cookies_mut(&mut self) -> &mut CookieJar {
        &mut self.cookies
    }

    #[doc(hidden)]
    #[inline]
    pub fn take_cookies(&mut self) -> CookieJar {
        std::mem::take(&mut self.cookies)
    }

    #[inline]
    pub fn params(&self) -> &HashMap<String, String> {
        &self.params
    }

    #[inline]
    pub fn params_mut(&mut self) -> &mut HashMap<String, String> {
        &mut self.params
    }

    #[inline]
    pub fn param<T: std::str::FromStr>(&mut self, key: &str) -> Result<T, Error> {
        let value = self
            .params
            .remove(key)
            .ok_or_else(|| Error::MissingParameter(key.to_string(), false))?;
        Ok(value
            .parse::<T>()
            .map_err(|_| Error::InvalidParameter(key.to_string(), false))?)
    }

    #[inline]
    pub fn query<'de, B>(&'de self) -> Result<B, Error>
    where
        B: serde::Deserialize<'de>,
    {
        let query = self.uri().query().unwrap_or("");
        serde_urlencoded::from_str::<B>(query).map_err(Error::SerdeUrlDe)
    }

    #[inline]
    pub fn content_type(&self) -> Option<&str> {
        let content_type = self.headers().get("content-type")?;
        let content_type = content_type.to_str().ok()?;
        Some(content_type)
    }

    /// Take body form the request, and set the body to None in the request.
    pub fn take_body(&mut self) -> IncomingBody {
        std::mem::replace(self.body_mut(), IncomingBody::Empty)
    }

    /// Get the request body as raw bytes in a `Vec<u8>`
    #[inline]
    pub async fn body_bytes(&mut self) -> Result<Bytes, Error> {
        let bytes = self.body_mut().collect().await?.to_bytes();
        Ok(bytes)
    }
    /// Get the request body as UTF-8 data in String
    #[inline]
    pub async fn body_string(&mut self) -> Result<String, Error> {
        let bytes = self.body_bytes().await?;
        Ok(String::from_utf8(bytes.to_vec())?)
    }

    #[cfg(feature = "file")]
    #[inline]
    async fn form_data(&mut self) -> Result<(), Error> {
        let c_type = self.content_type().expect("bad request");
        let boundary = multer::parse_boundary(c_type)?;
        let boundary = boundary.as_str();
        let mut multipart = multer::Multipart::new(self.take_body(), boundary);
        while let Some(mut field) = multipart.next_field().await? {
            if let Some(name) = field.name().map(|s| s.to_owned()) {
                if field.headers().get("content-type").is_some() {
                    self.files.insert(name, FilePart::new(&mut field).await?);
                }
            }
        }
        Ok(())
    }

    #[cfg(feature = "file")]
    #[inline]
    pub async fn file(&mut self, key: &str) -> Result<&FilePart, Error> {
        self.form_data().await?;
        let file_part = self.files.get(key).unwrap();
        Ok(file_part)
    }

    #[cfg(feature = "file")]
    #[inline]
    pub async fn files(&mut self, key: &str) -> Result<&Vec<FilePart>, Error> {
        self.form_data().await?;
        let file_part = self.files.get_vec(key).unwrap();
        Ok(file_part)
    }

    #[cfg(feature = "file")]
    #[inline]
    pub async fn upload(&mut self, key: &str, save_path: &str) -> Result<u64, Error> {
        let file = self.file(key).await?;
        std::fs::create_dir_all(save_path)?;
        let dest = format!("{}/{}", save_path, file.name().unwrap());
        Ok(std::fs::copy(file.path(), std::path::Path::new(&dest))?)
    }

    #[cfg(feature = "file")]
    #[inline]
    pub async fn uploads(&mut self, key: &str, save_path: &str) -> Result<String, Error> {
        let 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().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")))
    }

    #[inline]
    pub async fn parse<T>(&mut self) -> Result<T, Error>
    where
        T: DeserializeOwned,
    {
        let data = self.body_mut().collect().await?.to_bytes();
        let essence = self.content_type();
        match essence {
            Some("application/json") => serde_json::from_slice(&data).map_err(Error::SerdeJson),
            Some("application/x-www-form-urlencoded") => {
                serde_urlencoded::from_bytes(&data).map_err(Error::SerdeUrlDe)
            }
            #[cfg(feature = "cbor")]
            Some("application/cbor") => {
                ciborium::de::from_reader(&data[..]).map_err(|e| Error::Other(e.to_string()))
            }
            #[cfg(feature = "msgpack")]
            Some("application/msgpack") => {
                rmp_serde::from_slice(&data).map_err(Error::MsgpackDeserialization)
            }
            _ => Err(Error::Other(String::from("Invalid Context-Type"))),
        }
    }

    #[inline]
    pub async fn parse_query<T: QueryTrait>(&mut self) -> Result<Query<T::Output>, Error> {
        let query = self.uri().query().unwrap_or("");
        let value = T::from_str(query)?;
        Ok(Query(value))
    }

    #[inline]
    pub async fn parse_body<T: FromBytes>(&mut self) -> Result<T::Output, Error> {
        let bytes = self.body_mut().collect().await?.to_bytes();
        let value = T::from_bytes(bytes)?;
        Ok(value)
    }

    #[inline]
    pub async fn parse_json<T: FromBytes>(&mut self) -> Result<Json<T::Output>, Error> {
        let bytes = self.body_mut().collect().await?.to_bytes();
        let value = T::from_bytes(bytes)?;
        Ok(Json(value))
    }

    #[inline]
    pub async fn parse_form<T: FromBytes>(&mut self) -> Result<Form<T::Output>, Error> {
        let bytes = self.body_mut().collect().await?.to_bytes();
        let value = T::from_bytes(bytes)?;
        Ok(Form(value))
    }

    #[inline]
    pub fn parse_cookies(&mut self) {
        let jar = &mut self.cookies;
        if let Some(cookie_iter) = self
            .inner
            .headers()
            .get("Cookie")
            .and_then(|cookies| cookies.to_str().ok())
            .map(|cookies_str| cookies_str.split("; "))
            .map(|cookie_iter| {
                cookie_iter.filter_map(|cookie_s| Cookie::parse(cookie_s.to_string()).ok())
            })
        {
            cookie_iter.for_each(|c| jar.add_original(c));
        }
    }
}

impl Deref for Request {
    type Target = hyper::Request<IncomingBody>;
    #[inline]
    fn deref(&self) -> &Self::Target {
        &self.inner
    }
}

impl DerefMut for Request {
    #[inline]
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.inner
    }
}

impl From<Request> for hyper::Request<IncomingBody> {
    #[inline]
    fn from(request: Request) -> Self {
        request.inner
    }
}

#[inline]
#[doc(hidden)]
#[allow(dead_code)]
pub fn query_str_to_hashmap(
    query_str: &str,
) -> Result<HashMap<String, String>, serde_urlencoded::de::Error> {
    serde_urlencoded::from_str::<HashMap<String, String>>(query_str)
}

#[inline]
#[doc(hidden)]
#[allow(dead_code)]
pub fn query_str_to_type<T>(query_str: &str) -> Result<T, serde_urlencoded::de::Error>
where
    T: for<'a> serde::Deserialize<'a>,
{
    serde_urlencoded::from_str::<T>(query_str)
}