Skip to main content

faithea/data/
outbound.rs

1use std::{ffi::OsStr, path::Path};
2
3use bytes::Bytes;
4use http::{
5    HeaderValue,
6    header::{CONTENT_LENGTH, CONTENT_TYPE},
7};
8use serde::Serialize;
9
10use crate::{
11    data::Json,
12    handler::types::HttpHandlerError,
13    map_fu,
14    response::{HttpResponseModifier, HttpResponseModifierFuture, ResponseBody},
15};
16impl<T: Serialize> TryFrom<&Json<T>> for ResponseBody {
17    type Error = HttpHandlerError;
18    fn try_from(value: &Json<T>) -> Result<Self, Self::Error> {
19        let res = serde_json::to_vec(value)?;
20        Ok(Self::Simple(Bytes::from(res)))
21    }
22}
23impl<T: Serialize> TryFrom<&mut Json<T>> for ResponseBody {
24    type Error = HttpHandlerError;
25    fn try_from(value: &mut Json<T>) -> Result<Self, Self::Error> {
26        let im_ref = &(*value);
27        im_ref.try_into()
28    }
29}
30
31impl<T: Serialize + Send + Sync> HttpResponseModifier for Json<T> {
32    fn modify<'a>(
33        &'a mut self,
34        res: &'a mut crate::response::HttpResponse,
35    ) -> HttpResponseModifierFuture<'a> {
36        Box::pin(async move {
37            use ResponseBody::*;
38            res.add_header(
39                CONTENT_TYPE,
40                HeaderValue::from_maybe_shared("application/json").map_err(map_fu!())?,
41            );
42            let body = self.try_into()?;
43            if let Simple(ref b) = body {
44                res.add_header(
45                    CONTENT_LENGTH,
46                    HeaderValue::from_maybe_shared(b.len().to_string())?,
47                );
48            } else {
49                return Err(HttpHandlerError::after_handler_incompatible_body_type());
50            }
51            res.set_body(body);
52            Ok(())
53        })
54    }
55}
56
57impl HttpResponseModifier for &str {
58    fn modify<'a>(
59        &'a mut self,
60        res: &'a mut crate::response::HttpResponse,
61    ) -> HttpResponseModifierFuture<'a> {
62        Box::pin(async move {
63            // res.add_header(("content-type".to_string(), "text/plain".to_string()));
64            res.add_header(
65                CONTENT_TYPE,
66                HeaderValue::from_maybe_shared("text/plain").map_err(map_fu!())?,
67            );
68            // res.add_header(("content-length".to_string(), self.len().to_string()));
69            res.add_header(
70                CONTENT_LENGTH,
71                HeaderValue::from_maybe_shared(self.len().to_string()).map_err(map_fu!())?,
72            );
73            let b: Bytes = Bytes::from_iter(self.as_bytes().iter().copied());
74            res.set_body(ResponseBody::Simple(b));
75            Ok(())
76        })
77    }
78}
79impl HttpResponseModifier for String {
80    fn modify<'a>(
81        &'a mut self,
82        res: &'a mut crate::response::HttpResponse,
83    ) -> HttpResponseModifierFuture<'a> {
84        Box::pin(async move {
85            // res.add_header(("content-type".to_string(), "text/plain".to_string()));
86            res.add_header(
87                CONTENT_TYPE,
88                HeaderValue::from_maybe_shared("text/plain").map_err(map_fu!())?,
89            );
90            // res.add_header(("content-length".to_string(), self.len().to_string()));
91            res.add_header(
92                CONTENT_LENGTH,
93                HeaderValue::from_maybe_shared(self.len().to_string()).map_err(map_fu!())?,
94            );
95            let b: Bytes = Bytes::from_iter(self.as_bytes().iter().copied());
96            res.set_body(ResponseBody::Simple(b));
97            Ok(())
98        })
99    }
100}
101
102pub struct StaticFile<T: AsRef<Path>>(pub T);
103
104impl<T: AsRef<Path> + Send + Sync> HttpResponseModifier for StaticFile<T> {
105    fn modify<'a>(
106        &'a mut self,
107        res: &'a mut crate::response::HttpResponse,
108    ) -> HttpResponseModifierFuture<'a> {
109        Box::pin(async move {
110            let f = tokio::fs::File::open(self.0.as_ref()).await?;
111            let meta = f.metadata().await?;
112            if !meta.is_file() {
113                let err_msg = format!("{:?} is not a File!!", self.0.as_ref());
114                return Err(HttpHandlerError::after_handler_file_not_exists(err_msg));
115            }
116
117            let len = meta.len();
118            res.add_header(
119                CONTENT_LENGTH,
120                HeaderValue::from_maybe_shared(len.to_string()).map_err(map_fu!())?,
121            );
122            res.add_header(
123                CONTENT_TYPE,
124                HeaderValue::from_static(mime_type(self.0.as_ref())),
125            );
126            res.set_body(ResponseBody::File(f));
127            Ok(())
128        })
129    }
130}
131fn mime_type(path: &Path) -> &'static str {
132    match path.extension() {
133        Some(e) => get_mime_type_by_extention(e),
134        None => "application/octet-stream",
135    }
136}
137fn get_mime_type_by_extention(e: &OsStr) -> &'static str {
138    if let Some(e) = e.to_str() {
139        match e {
140            "html" => "text/html",
141            "htm" => "text/html",
142            "css" => "text/css",
143            "js" => "text/javascript",
144            "json" => "application/json",
145            "map" => "application/json",
146            // image
147            "png" => "image/png",
148            "jpg" => "image/jpeg",
149            "jpeg" => "image/jpeg",
150            "gif" => "image/gif",
151            "webp" => "image/webp",
152            "svg" => "image/svg+xml",
153            "ico" => "image/x-icon",
154            //file
155            "txt" => "text/plain",
156            "md" => "text/markdown",
157            "csv" => "text/csv",
158            "xml" => "application/xml",
159            "pdf" => "application/pdf",
160            // video
161            "mp3" => "audio/mpeg",
162            "wav" => "audio/wav",
163            "ogg" => "audio/ogg",
164            "mp4" => "video/mp4",
165            "webm" => "video/webm",
166            // zips
167            "zip" => "application/zip",
168            "tar" => "application/x-tar",
169            "gz" => "application/gzip",
170            "7z" => "application/x-7z-compressed",
171            // font
172            "woff" => "font/woff",
173            "woff2" => "font/woff2",
174            "ttf" => "font/ttf",
175            "otf" => "font/otf",
176            _ => "application/octet-stream",
177        }
178    } else {
179        "application/octet-stream"
180    }
181}