menemen 1.0.3

A streaming http request library
Documentation
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
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
use crate::{error, response::Response, response::ResponseInfo, transport::Transport, url::Url};
use anyhow::Context;
use bufstream::BufStream;
use native_tls::TlsConnector;
use std::{
    io::{Read, Write},
    net::TcpStream,
    time::Duration,
};

/// HTTP Header
/// ##### [https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers]
#[derive(Debug, Clone)]
pub struct Header {
    /// The name of the header
    pub name: String,
    /// The value of the header
    pub value: String,
}

impl Header {
    /// Parse raw http header response to [`Header`] struct
    /// ## Parameters
    /// * `line` - The raw http header response
    /// ## Returns
    /// [`Header`] if the header was successfully parsed else [`error::Error`]
    /// ## Example
    /// ```
    /// use menemen::request::Header;
    /// let header = Header::parse("Content-Type: text/html; charset=utf-8").unwrap();
    /// assert_eq!(header.name.clone(), "Content-Type");
    /// assert_eq!(header.value, "text/html; charset=utf-8");
    /// ```
    pub fn parse(line: &str) -> anyhow::Result<Header> {
        if !line.contains(":") {
            return Err(anyhow::anyhow!("Failed to parse response info"));
        }
        let parts = line.split(": ").collect::<Vec<_>>();
        let name = parts[0].to_string();
        let value = if parts.len() == 1 {
            String::new()
        } else {
            parts[1].to_string()
        };
        Ok(Header { name, value })
    }
}

/// List of RequestTypes
/// #### https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods
#[derive(Debug)]
pub enum RequestTypes {
    /// GET Method
    GET,
    /// POST Method
    POST,
    /// PUT Method
    PUT,
    /// DELETE Method
    DELETE,
}

impl RequestTypes {
    /// Get the string representation of the RequestType
    pub fn get_type(&self) -> String {
        match self {
            RequestTypes::GET => "GET".to_string(),
            RequestTypes::POST => "POST".to_string(),
            RequestTypes::PUT => "PUT".to_string(),
            RequestTypes::DELETE => "DELETE".to_string(),
        }
    }
}

/// ContentTypes
/// #### https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types
#[derive(Clone, Debug)]
pub enum ContentTypes {
    /// application/json
    JSON,
    /// text/html
    HTML,
    /// text/plain
    Text,
    /// image/png
    Png,
    /// audio/mp3
    MP3,
    /// text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
    Any,
    /// application/octet-stream
    OctetStream,
}

impl Default for ContentTypes {
    fn default() -> Self {
        ContentTypes::Any
    }
}

impl ContentTypes {
    /// Get the string representation of the ContentType
    /// ## Example
    /// ```
    /// use menemen::request::ContentTypes;
    /// let content_type = ContentTypes::JSON;
    /// assert_eq!(content_type.get_type(), "application/json");
    /// ```
    pub fn get_type(&self) -> &str {
        match self {
            ContentTypes::JSON => "application/json",
            ContentTypes::HTML => "text/html",
            ContentTypes::Text => "text/plain",
            ContentTypes::Png => "image/png",
            ContentTypes::MP3 => "audio/mp3",
            ContentTypes::Any => "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
            ContentTypes::OctetStream => "application/octet-stream",
        }
    }
}

/// Request struct
#[derive(Debug)]
pub struct Request {
    /// Url of the request [`Url`]
    url: Url,
    request_type: RequestTypes,
    /// ContentType of the request [`ContentTypes`]
    pub content_type: ContentTypes,
    /// Headers of the request [`Vec<Header>`]
    headers: Vec<Header>,
    /// Timeout of the request [`u64`]
    timeout: u64,
    redirect: bool,
    /// Is the request sent
    sent: bool,
}

impl Request {
    /// Create a new [`Request`]
    /// ## Parameters
    /// * `url` - The url to send the request to
    /// * `request_type` - The type of request to send takes [`RequestTypes`]
    /// ## Returns
    /// [`Request`] if the request was successfully created else [`error::Error`]
    pub fn new(url: &str, request_type: RequestTypes) -> anyhow::Result<Request> {
        let url = crate::url::Url::build_from_string(url.to_string())
            .with_context(|| "Failed to parse url")?;
        let headers = Vec::new();
        let mut request = Request {
            url: url.clone(),
            request_type,
            content_type: ContentTypes::default(),
            headers,
            timeout: 5000,
            redirect: true,
            sent: false,
        };
        request.set_header(
            "Host",
            &format!(
                "{}{}{}",
                url.host,
                if url.port == 443 || url.port == 80 {
                    ""
                } else {
                    ":"
                },
                if url.port == 443 || url.port == 80 {
                    "".to_string()
                } else {
                    url.port.to_string()
                },
            ),
        );
        request.set_header("Connection", "close");
        request.set_header("Cache-Control", "max-age=0");
        request.set_header(
            "User-Agent",
            &format!("Menemen/{}", env!("CARGO_PKG_VERSION")),
        );
        Ok(request)
    }

    /// Builds the request body
    fn build_request_body(&mut self) -> String {
        self.set_header("Content-Type", &self.content_type.clone().get_type());
        //{protocol}://{host}{port}
        format!(
            "{request_type} /{path}{queryParams} HTTP/1.1\r\n\
            {headers}\r\n\r\n",
            request_type = self.request_type.get_type(),
            path = self.url.paths.join("/"),
            queryParams = if self.url.query_params.is_empty() {
                "".to_owned()
            } else {
                "?".to_owned() + &self.url.join_query_params()
            },
            headers = self
                .headers
                .iter()
                .map(|x| format!("{}:{}", x.name, x.value))
                .collect::<Vec<_>>()
                .join("\r\n")
        )
    }

    /// Builds the request body
    fn build_post_request_body(&mut self) -> String {
        self.set_header("Content-Type", &self.content_type.clone().get_type());

        //{protocol}://{host}{port}
        format!(
            "{request_type} /{path}{queryParams} HTTP/1.1\r\n\
            {headers}\r\n\r\n",
            request_type = self.request_type.get_type(),
            path = self.url.paths.join("/"),
            queryParams = if self.url.query_params.is_empty() {
                "".to_owned()
            } else {
                "?".to_owned() + &self.url.join_query_params()
            },
            headers = self
                .headers
                .iter()
                .map(|x| format!("{}:{}", x.name, x.value))
                .collect::<Vec<_>>()
                .join("\r\n")
        )
    }

    /// Set timeout for the request
    /// ## Parameters
    /// * `timeout` - The timeout in milliseconds
    /// ## Returns
    /// [`Request`] if the timeout set before the request sent else [`error::Error`]
    /// ## Example
    /// ```
    /// use menemen::request::{Request, RequestTypes};
    ///
    /// let mut request = Request::new("https://behemehal.org/test", RequestTypes::GET).unwrap();
    /// request.set_timeout(5000);
    /// ```
    pub fn set_timeout(&mut self, timeout: u64) -> Option<error::RequestErrors> {
        if self.sent {
            Some(error::RequestErrors::CantSetHeadersAfterRequestSent)
        } else {
            self.timeout = timeout;
            None
        }
    }

    /// Get headers of the request
    /// ## Returns
    /// [`Vec<Header>`]
    pub fn get_headers(&self) -> Vec<Header> {
        self.headers.clone()
    }

    /// Get header for the request
    /// ## Parameters
    /// * `key` - The name of the header
    /// ## Returns
    /// [`String`] if the header exists else [`None`]
    pub fn get_header(&self, key: &str) -> Option<Header> {
        self.headers.clone().into_iter().find(|h| h.name == key)
    }

    /// Set header for the request
    /// ## Parameters
    /// * `key` - The name of the header
    /// * `value` - The value of the header
    /// ## Returns
    /// [`Request`] if the header was set before the request sent else [`error::Error`]
    /// ## Example
    /// ```
    /// use menemen::request::{Request, RequestTypes};
    ///
    /// let mut request = Request::new("https://behemehal.org/test", RequestTypes::GET).unwrap();
    /// request.set_header("Host", "behemehal.org");
    /// ```
    pub fn set_header(&mut self, key: &str, value: &str) -> Option<error::RequestErrors> {
        if self.sent {
            Some(error::RequestErrors::CantSetHeadersAfterRequestSent)
        } else {
            let q = self.headers.iter_mut().find(|h| h.name == key);
            match q {
                Some(mut header) => {
                    header.value = value.to_string();
                }
                None => {
                    self.headers.push(Header {
                        name: key.to_string(),
                        value: value.to_string(),
                    });
                }
            }
            None
        }
    }

    /// Send the request with body stream [NotImplemented]
    pub fn send_with_body(
        &mut self,
        body: &mut dyn Read,
    ) -> Result<Response, error::RequestErrors> {
        if self.sent {
            return Err(error::RequestErrors::AlreadySent);
        } else {
            let socket_addr = (self.url.host.clone(), self.url.port);

            match TcpStream::connect(socket_addr) {
                Ok(mut _tcp_stream) => {
                    _tcp_stream
                        .set_read_timeout(Some(Duration::from_millis(self.timeout)))
                        .unwrap();

                    let mut tcp_stream = if self.url.is_https {
                        Transport::Ssl(BufStream::new(
                            TlsConnector::new()
                                .unwrap()
                                .connect(&self.url.host, _tcp_stream)
                                .unwrap(),
                        ))
                    } else {
                        Transport::Tcp(BufStream::new(_tcp_stream))
                    };
                    let mut cbody = String::new();
                    body.read_to_string(&mut cbody).unwrap();
                    self.set_header("content-length", &cbody.len().to_string());
                    let request_body = self.build_post_request_body();
                    self.sent = true;
                    tcp_stream.write(request_body.as_bytes()).unwrap();
                    tcp_stream.write(cbody.as_bytes()).unwrap();
                    tcp_stream.write(b"\r\n").unwrap();
                    tcp_stream.flush().unwrap();

                    let mut lines = vec![String::new()];
                    let mut new_line = false;
                    let mut connection_info_collected = false;
                    let mut connection_info = ResponseInfo::default();
                    let mut headers: Vec<Header> = Vec::new();
                    let mut last_char = '\0';
                    loop {
                        let mut buffer = [0; 1];
                        tcp_stream.read(&mut buffer).unwrap();
                        //Convert byte to char
                        let cchar = char::from(buffer[0]);
                        //If its a line break
                        if last_char == '\r' && cchar == '\n' {
                            //If newline used again collect body
                            if new_line {
                                for line in &lines {
                                    match Header::parse(line) {
                                        Ok(header_line) => {
                                            headers.push(header_line);
                                        }
                                        Err(_) => {
                                            return Err(error::RequestErrors::ConnectionError(
                                                "Malformed response header".to_string(),
                                            ));
                                        }
                                    }
                                }
                                return Ok(Response {
                                    response_info: connection_info,
                                    headers,
                                    stream: tcp_stream,
                                });
                            } else {
                                if !connection_info_collected {
                                    if let Ok(con_info) =
                                        ResponseInfo::parse_response_info(&lines[0])
                                    {
                                        connection_info = con_info;
                                        connection_info_collected = true;
                                        lines = Vec::new();
                                    } else {
                                        return Err(error::RequestErrors::ConnectionError(
                                            "Malformed response".to_string(),
                                        ));
                                    }
                                }
                                new_line = true;
                            }
                        } else {
                            //If coming line is \r dont reset 'new_line'
                            if cchar != '\r' {
                                if new_line {
                                    lines.push(String::new());
                                }
                                let line_len = lines.len();
                                lines[line_len - 1] += &cchar.to_string();
                                new_line = false;
                            }
                        }
                        last_char = cchar;
                    }
                }
                Err(e) => Err(error::RequestErrors::ConnectionError(e.to_string())),
            }
        }
    }

    /// Send the request without body stream
    /// ## Returns
    /// [`Response`] if the request was sent successfully else [`error::RequestErrors`]
    pub fn send(&mut self) -> Result<Response, error::RequestErrors> {
        if self.sent {
            return Err(error::RequestErrors::AlreadySent);
        } else {
            let socket_addr = (self.url.host.clone(), self.url.port);

            match TcpStream::connect(socket_addr) {
                Ok(mut _tcp_stream) => {
                    _tcp_stream
                        .set_read_timeout(Some(Duration::from_millis(self.timeout)))
                        .unwrap();

                    let mut tcp_stream = if self.url.is_https {
                        Transport::Ssl(BufStream::new(
                            TlsConnector::new()
                                .unwrap()
                                .connect(&self.url.host, _tcp_stream)
                                .unwrap(),
                        ))
                    } else {
                        Transport::Tcp(BufStream::new(_tcp_stream))
                    };

                    let request_body = self.build_request_body();
                    self.sent = true;
                    tcp_stream.write(request_body.as_bytes()).unwrap();
                    tcp_stream.flush().unwrap();

                    let mut lines = vec![String::new()];
                    let mut new_line = false;
                    let mut connection_info_collected = false;
                    let mut connection_info = ResponseInfo::default();
                    let mut headers: Vec<Header> = Vec::new();
                    let mut last_char = '\0';
                    loop {
                        let mut buffer = [0; 1];
                        tcp_stream.read(&mut buffer).unwrap();
                        //Convert byte to char
                        let cchar = char::from(buffer[0]);
                        //If its a line break
                        if last_char == '\r' && cchar == '\n' {
                            //If newline used again collect body
                            if new_line {
                                for line in &lines {
                                    match Header::parse(line) {
                                        Ok(header_line) => {
                                            headers.push(header_line);
                                        }
                                        Err(_) => {
                                            return Err(error::RequestErrors::ConnectionError(
                                                "Malformed response header".to_string(),
                                            ));
                                        }
                                    }
                                }
                                let redirected_location =
                                    headers.iter().find(|x| x.name == "Location");
                                if self.redirect
                                    && redirected_location.is_some()
                                    && (connection_info.status_code == 302
                                        || connection_info.status_code == 303
                                        || connection_info.status_code == 307
                                        || connection_info.status_code == 308)
                                {
                                    return match Url::build_from_string(
                                        redirected_location.unwrap().value.clone(),
                                    ) {
                                        Ok(new_url) => {
                                            self.url = new_url.clone();
                                            self.sent = false;
                                            self.set_header(
                                                "Host",
                                                &format!(
                                                    "{}{}{}",
                                                    new_url.host,
                                                    if new_url.port == 443 || new_url.port == 80 {
                                                        ""
                                                    } else {
                                                        ":"
                                                    },
                                                    if new_url.port == 443 || new_url.port == 80 {
                                                        "".to_string()
                                                    } else {
                                                        new_url.port.to_string()
                                                    },
                                                ),
                                            );
                                            self.send()
                                        }
                                        Err(_) => {
                                            Err(error::RequestErrors::ConnectionError(format!(
                                                "Redirect url is not correct '{}'",
                                                redirected_location.unwrap().value.clone()
                                            )))
                                        }
                                    };
                                } else {
                                    return Ok(Response {
                                        response_info: connection_info,
                                        headers,
                                        stream: tcp_stream,
                                    });
                                }
                            } else {
                                if !connection_info_collected {
                                    if let Ok(con_info) =
                                        ResponseInfo::parse_response_info(&lines[0])
                                    {
                                        connection_info = con_info;
                                        connection_info_collected = true;
                                        lines = Vec::new();
                                    } else {
                                        return Err(error::RequestErrors::ConnectionError(
                                            "Malformed response".to_string(),
                                        ));
                                    }
                                }
                                new_line = true;
                            }
                        } else {
                            //If coming line is \r dont reset 'new_line'
                            if cchar != '\r' {
                                if new_line {
                                    lines.push(String::new());
                                }
                                let line_len = lines.len();
                                lines[line_len - 1] += &cchar.to_string();
                                new_line = false;
                            }
                        }
                        last_char = cchar;
                    }
                }
                Err(e) => Err(error::RequestErrors::ConnectionError(e.to_string())),
            }
        }
    }
}