aboutsummaryrefslogtreecommitdiff
path: root/src/response.rs
blob: 779bebc9a58bcdec3f9a53196a8a21a39e1ba1e2 (plain) (blame)
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
pub mod configuration;

use {
  crate::{
    environment::ENVIRONMENT,
    url::{from_path as url_from_path, matches_pattern},
  },
  actix_web::{Error, HttpResponse},
  std::{fmt::Write, time::Instant},
};

const CSS: &str = include_str!("../default.css");

#[allow(clippy::future_not_send, clippy::too_many_lines)]
pub async fn default(
  http_request: actix_web::HttpRequest,
) -> Result<HttpResponse, Error> {
  if ["/proxy", "/proxy/", "/x", "/x/", "/raw", "/raw/", "/nocss", "/nocss/"]
    .contains(&http_request.path())
  {
    return Ok(HttpResponse::Ok()
        .content_type("text/html")
      .body(r"<h1>September</h1>
<p>This is a proxy path. Specify a Gemini URL without the protocol (<code>gemini://</code>) to proxy it.</p>
<p>To proxy <code>gemini://fuwn.me/uptime</code>, visit <code>https://fuwn.me/proxy/fuwn.me/uptime</code>.</p>
<p>Additionally, you may visit <code>/raw</code> to view the raw Gemini content, or <code>/nocss</code> to view the content without CSS.</p>
      "));
  }

  let mut configuration = configuration::Configuration::new();
  let url = match url_from_path(
    &format!("{}{}", http_request.path(), {
      if !http_request.query_string().is_empty()
        || http_request.uri().to_string().ends_with('?')
      {
        format!("?{}", http_request.query_string())
      } else {
        String::new()
      }
    }),
    false,
    &mut configuration,
  ) {
    Ok(url) => url,
    Err(e) => {
      return Ok(
        HttpResponse::BadRequest()
          .content_type("text/plain")
          .body(format!("{e}")),
      );
    }
  };
  let mut timer = Instant::now();
  let mut response = match germ::request::request(&url).await {
    Ok(response) => response,
    Err(e) => {
      return Ok(HttpResponse::Ok().body(e.to_string()));
    }
  };
  let mut redirect_response_status = None;
  let mut redirect_url = None;

  if *response.status() == germ::request::Status::PermanentRedirect
    || *response.status() == germ::request::Status::TemporaryRedirect
  {
    redirect_response_status = Some(*response.status());
    redirect_url = Some(
      url::Url::parse(&if response.meta().starts_with('/') {
        format!(
          "gemini://{}{}",
          url.domain().unwrap_or_default(),
          response.meta()
        )
      } else {
        response.meta().to_string()
      })
      .unwrap(),
    );
    response =
      match germ::request::request(&redirect_url.clone().unwrap()).await {
        Ok(response) => response,
        Err(e) => {
          return Ok(HttpResponse::Ok().body(e.to_string()));
        }
      }
  }

  let response_time_taken = timer.elapsed();
  let meta = germ::meta::Meta::from_string(response.meta().to_string());
  let charset = meta
    .parameters()
    .get("charset")
    .map_or_else(|| "utf-8".to_string(), ToString::to_string);
  let language =
    meta.parameters().get("lang").map_or_else(String::new, ToString::to_string);

  timer = Instant::now();

  if response.meta().starts_with("image/") {
    if let Some(content_bytes) = &response.content_bytes() {
      return Ok(
        HttpResponse::build(actix_web::http::StatusCode::OK)
          .content_type(response.meta().as_ref())
          .body(content_bytes.to_vec()),
      );
    }
  }

  let mut html_context = if configuration.is_raw() {
    String::new()
  } else {
    format!(
      r#"<!DOCTYPE html><html{}><head><meta name="viewport" content="width=device-width, initial-scale=1.0">"#,
      if language.is_empty() {
        String::new()
      } else {
        format!(" lang=\"{language}\"")
      }
    )
  };
  let gemini_html =
    crate::html::from_gemini(&response, &url, &configuration).unwrap();
  let gemini_title = gemini_html.0;
  let convert_time_taken = timer.elapsed();

  if configuration.is_raw() {
    html_context.push_str(
      &response.content().as_ref().map_or_else(String::default, String::clone),
    );

    return Ok(
      HttpResponse::Ok()
        .content_type(format!("{}; charset={charset}", meta.mime()))
        .body(html_context),
    );
  }

  if configuration.is_no_css() {
    html_context.push_str(&gemini_html.1);

    return Ok(
      HttpResponse::Ok()
        .content_type(format!("text/html; charset={charset}"))
        .body(html_context),
    );
  }

  if let Some(css) = &ENVIRONMENT.css_external {
    for stylesheet in css.split(',').filter(|s| !s.is_empty()) {
      let _ = write!(
        &mut html_context,
        "<link rel=\"stylesheet\" type=\"text/css\" href=\"{stylesheet}\">",
      );
    }
  } else if !configuration.is_no_css() {
    let _ = write!(
      &mut html_context,
      r#"<link rel="stylesheet" href="https://latex.vercel.app/style.css"><style>{CSS}</style>"#
    );

    if let Some(primary) = &ENVIRONMENT.primary_colour {
      let _ = write!(
        &mut html_context,
        "<style>:root {{ --primary: {primary} }}</style>"
      );
    } else {
      let _ = write!(
        &mut html_context,
        "<style>:root {{ --primary: var(--base0D); }}</style>"
      );
    }
  }

  if let Some(favicon) = &ENVIRONMENT.favicon_external {
    let _ = write!(
      &mut html_context,
      "<link rel=\"icon\" type=\"image/x-icon\" href=\"{favicon}\">",
    );
  }

  if ENVIRONMENT.mathjax {
    html_context.push_str(
      r#"<script type="text/javascript" id="MathJax-script" async
        src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js">
    </script>"#,
    );
  }

  if let Some(head) = &ENVIRONMENT.head {
    html_context.push_str(head);
  }

  let _ = write!(&mut html_context, "<title>{gemini_title}</title>");
  let _ = write!(&mut html_context, "</head><body>");

  if !http_request.path().starts_with("/proxy") {
    if let Some(header) = &ENVIRONMENT.header {
      let _ = write!(
        &mut html_context,
        "<big><blockquote>{header}</blockquote></big>"
      );
    }
  }

  match response.status() {
    germ::request::Status::Success => {
      if let (Some(status), Some(url)) =
        (redirect_response_status, redirect_url)
      {
        let _ = write!(
          &mut html_context,
          "<blockquote>This page {} redirects to <a \
           href=\"{}\">{}</a>.</blockquote>",
          if status == germ::request::Status::PermanentRedirect {
            "permanently"
          } else {
            "temporarily"
          },
          url,
          url
        );
      }

      html_context.push_str(&gemini_html.1);
    }
    _ => {
      let _ = write!(&mut html_context, "<p>{}</p>", response.meta());
    }
  }

  let _ = write!(
    &mut html_context,
    "<details>\n<summary>Proxy Information</summary>
<dl>
<dt>Original URL</dt><dd><a href=\"{}\">{0}</a></dd>
<dt>Status Code</dt><dd>{} ({})</dd>
<dt>Meta</dt><dd><code>{}</code></dd>
<dt>Capsule Response Time</dt><dd>{} milliseconds</dd>
<dt>Gemini-to-HTML Time</dt><dd>{} milliseconds</dd>
</dl>
<p>This content has been proxied by <a \
     href=\"https://github.com/gemrest/september{}\">September ({})</a>.</p>
</details></body></html>",
    url,
    response.status(),
    i32::from(*response.status()),
    response.meta(),
    response_time_taken.as_nanos() as f64 / 1_000_000.0,
    convert_time_taken.as_nanos() as f64 / 1_000_000.0,
    format_args!("/tree/{}", env!("VERGEN_GIT_SHA")),
    env!("VERGEN_GIT_SHA").get(0..5).unwrap_or("UNKNOWN"),
  );

  if let Some(plain_texts) = &ENVIRONMENT.plain_text_route {
    if plain_texts.split(',').any(|r| {
      matches_pattern(r, http_request.path())
        || matches_pattern(r, http_request.path().trim_end_matches('/'))
    }) {
      return Ok(HttpResponse::Ok().body(
        response.content().as_ref().map_or_else(String::default, String::clone),
      ));
    }
  }

  Ok(
    HttpResponse::Ok()
      .content_type(format!("text/html; charset={charset}"))
      .body(html_context),
  )
}