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
//! Middleware for serving project assets
use actix_files::file_extension_to_mime;
use awc::body::EitherBody;
use futures_util::future::LocalBoxFuture;
use std::future::{ready, Ready};

use actix_web::{
    dev::{forward_ready, Service, ServiceRequest, ServiceResponse, Transform},
    Error, HttpResponse,
};

use crate::pages::base;

pub struct ServeAssets;

impl<S, B> Transform<S, ServiceRequest> for ServeAssets
where
    S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error>,
    S::Future: 'static,
    B: 'static,
{
    type Response = ServiceResponse<EitherBody<B>>;
    type Error = Error;
    type InitError = ();
    type Transform = ServeMiddleware<S>;
    type Future = Ready<Result<Self::Transform, Self::InitError>>;

    fn new_transform(&self, service: S) -> Self::Future {
        ready(Ok(ServeMiddleware { service }))
    }
}

pub struct ServeMiddleware<S> {
    service: S,
}

impl<S, B> Service<ServiceRequest> for ServeMiddleware<S>
where
    S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error>,
    S::Future: 'static,
    B: 'static,
{
    type Response = ServiceResponse<EitherBody<B>>;
    type Error = Error;
    type Future = LocalBoxFuture<'static, Result<Self::Response, Self::Error>>;

    forward_ready!(service);

    fn call(&self, req: ServiceRequest) -> Self::Future {
        let site_host = std::env::var("HOST");

        // process response as normal
        let cookie = req.request().cookie("__Secure-Token");
        let fut = self.service.call(req);

        Box::pin(async move {
            let res = fut.await?;

            // get host
            let host = res.request().headers().get("host");

            // custom domain
            // if host.is_some()
            //     && site_host.is_ok()
            //     && std::str::from_utf8(host.as_ref().unwrap().as_bytes()).unwrap()
            //         != site_host.as_ref().unwrap()
            // {
            //     dbg!(&site_host);
            //     // implement get_project_by_custom_domain
            //     // return error if not found
            // }
            // // subdomain
            // else
            if host.is_some() && site_host.is_ok()
            // && std::str::from_utf8(host.as_ref().unwrap().as_bytes())
            //     .unwrap()
            //     .contains(".get.")
            {
                let site_host = site_host.unwrap();

                // serve project asset
                let data = res
                    .request()
                    .app_data::<actix_web::web::Data<crate::db::AppData>>()
                    .unwrap();

                // ...
                let host = std::str::from_utf8(host.as_ref().unwrap().as_bytes()).unwrap();
                // let host_split = host.split(".get.").collect::<Vec<&str>>();
                let host_split = host.split(&format!(".{site_host}")).collect::<Vec<&str>>();

                let project = host_split.get(0);
                if project.is_some() {
                    let project = project
                        .unwrap()
                        .replace("https://", "")
                        .replace("http://", "");

                    let project = project.as_str();

                    // make sure project is not the host and is not "www"
                    if [host, "www", ""].contains(&project) {
                        return Ok(res.map_into_left_body());
                    }

                    // ...
                    let mut path = res.request().path().to_string();

                    // check path
                    if path == "/" {
                        path = String::from("/index.html");
                    } else if !path.starts_with("/") {
                        path = format!("/{}", path);
                    }

                    // verify auth status
                    let (set_cookie, _, token_user) =
                        base::check_auth_status_with_cookie(cookie, data.clone()).await;

                    // fetch asset
                    let file = data
                        .db
                        .get_file_in_project(
                            project.to_string(),
                            path.clone(),
                            if token_user.is_some() {
                                let user = token_user.unwrap().payload.unwrap();
                                Option::Some(user.user.username)
                            } else {
                                Option::None
                            },
                            false,
                            false,
                        )
                        .await;

                    if file.success == false {
                        let new_res = ServiceResponse::new(
                            res.request().clone(),
                            HttpResponse::NotAcceptable()
                                .append_header(("Content-Type", "text/html"))
                                .body(format!("<!DOCTYPE html>

                                <html lang=\"en\">
                                    <head>
                                        <meta charset=\"UTF-8\" />
                                        <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />
                                        <title>Error! (Vibrant)</title>

                                        <link rel=\"stylesheet\" href=\"//{site_host}/static/style.css\" />
                                    </head>
                                
                                    <body>
                                        <main class=\"small flex flex-column g-4\">
                                            <div class=\"card secondary border round full flex justify-center align-center\">
                                                <h3 class=\"no-margin text-center\">{}</h3>
                                            </div>

                                            <div class=\"flex justify-center footernav\">
                                                <span class=\"item\"><a href=\"/\">Root</a></span>
                                                <span class=\"item\"><a href=\"//{site_host}\">🌸 Homepage</a></span>
                                                <span class=\"item\"><a href=\"https://code.stellular.org/stellular/vibrant\">Source Code</a></span>
                                            </div>
                                        </main>
                                    </body>
                                </html>", file.message)),
                        )
                        .map_into_right_body();

                        return Ok(new_res);
                    }

                    data.db.incr_project_requests(project.to_string()).await;

                    // get file extension from path
                    let ext = file
                        .message
                        .split(".")
                        .collect::<Vec<&str>>()
                        .pop()
                        .unwrap_or("txt");

                    // return
                    let new_res = ServiceResponse::new(
                        res.request().clone(),
                        HttpResponse::Ok()
                            .append_header(("Set-Cookie", set_cookie))
                            .append_header(("Content-Type", file_extension_to_mime(ext)))
                            .body(file.payload.unwrap()),
                    )
                    .map_into_right_body();

                    return Ok(new_res);
                }
            }

            // normal res
            Ok(res.map_into_left_body())
        })
    }
}