aboutsummaryrefslogtreecommitdiff
path: root/src/modules/web.rs
blob: 48433229de18495a7a4979abc734018bc85384d0 (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
use {
  crate::{
    response::success,
    route::track_mount,
    url::{ROOT_GEMINI_URL, ROOT_HTTPS_URL},
  },
  windmark::{context::RouteContext, response::Response},
};

fn error(message: &str, context: &windmark::context::RouteContext) -> Response {
  success(
    &format!(
      "# World Wide Web-to-Gemini Gateway\n\n{message}\n\n=> /web Go back"
    ),
    context,
  )
}

pub fn module(router: &mut windmark::router::Router) {
  track_mount(router, "/web", "-World-Wide-Web to Gemini Gateway", |context| {
    success(
      &format!(
        r"# World Wide Web to Gemini Gateway

To use this gateway, simply append the address of your target resource to the end of the current route, minus the protocol.

To visit the web version of this exact page, <{ROOT_HTTPS_URL}/web>, you would visit <{ROOT_GEMINI_URL}/web/fuwn.net/web>.

=> /web/example.com Try it!"
      ),
      &context,
    )
  });
  track_mount(
    router,
    "/web/*url",
    "-World-Wide-Web to Gemini Gateway Router",
    async move |context: RouteContext| {
      let queries = windmark::utilities::queries_from_url(&context.url);

      Response::success({
        let Ok(url) = url::Url::parse(&format!(
          "https://{}",
          if let Some(url_choice) = context.parameters.get("url") {
            url_choice
          } else {
            return error("Looks like you didn't provide a URL!", &context);
          }
        )) else {
          return error("The URL you provided is invalid.", &context);
        };
        let mut contents = vec![format!("=> {url} {url}\n")];
        let website = if let Ok(website) = reqwest::get(url.clone()).await {
          if let Ok(text) = website.text().await {
            text
          } else {
            return error(
              "The website you provided could not be reached.",
              &context,
            );
          }
        } else {
          return error(
            "The website you provided could not be reached.",
            &context,
          );
        };
        let Ok(dom) = tl::parse(&website, tl::ParserOptions::default()) else {
          return error(
            "The website you provided could not be properly parsed.",
            &context,
          );
        };
        let parser = dom.parser();
        let mut nodes = dom.nodes().iter().peekable();

        if let Some(id) = queries.get("id") {
          nodes = if let Some(element) = dom.get_element_by_id(id.as_str()) {
            element
              .get(parser)
              .unwrap()
              .children()
              .map_or(nodes, |children| children.all(parser).iter().peekable())
          } else {
            nodes
          };
        }

        if let Some(id) = queries.get("class") {
          nodes = if let Some(element) =
            dom.get_elements_by_class_name(id.as_str()).next()
          {
            element
              .get(parser)
              .unwrap()
              .children()
              .map_or(nodes, |children| children.all(parser).iter().peekable())
          } else {
            nodes
          };
        }

        while let Some(element) = nodes.next() {
          let text = String::new();

          let () = element.as_tag().map_or((), |tag| {
            match tag.name().as_utf8_str().to_string().as_str() {
              "p" => {
                if tag.inner_html(parser).contains("<img") {
                  return;
                }

                contents.push(format!(
                  "{}\n\n",
                  tag
                    .inner_text(parser)
                    .lines()
                    .collect::<Vec<_>>()
                    .first()
                    .unwrap_or(&"A parse error occurred in this location.")
                ));
              }
              "a" => {
                contents.pop();
                contents.push(format!(
                  "=> {} {}\n{}",
                  tag.attributes().get("href").flatten().map_or(
                    "A parse error occurred in this location.".to_string(),
                    |href| href.as_utf8_str().to_string()
                  ),
                  tag.inner_text(parser),
                  nodes.peek().map_or("", |next_node| {
                    next_node.as_tag().map_or("", |next_tag| {
                      if next_tag.name().as_utf8_str().to_string().as_str()
                        == "a"
                      {
                        ""
                      } else {
                        "\n"
                      }
                    })
                  })
                ));
              }
              "h1" => {
                contents.push(format!(
                  "{}# {}\n\n",
                  if contents.is_empty() { "\n" } else { "" },
                  tag.inner_text(parser)
                ));
              }
              "h2" => {
                contents.push(format!("\n## {}\n\n", tag.inner_text(parser)));
              }
              "h3" => {
                contents.push(format!("\n### {}\n\n", tag.inner_text(parser)));
              }
              "pre" => {
                contents.push(format!("```\n{}```\n", tag.inner_text(parser)));
              }
              "blockquote" => {
                contents.push(format!("> {}\n\n", tag.inner_text(parser)));
              }
              "li" => {
                contents.push(format!("* {}\n", tag.inner_text(parser)));
              }
              "img" => {
                contents.push(format!(
                  "=> {} {}\n\n",
                  tag.attributes().get("src").flatten().map_or(
                    "A parse error occurred in this location.".to_string(),
                    |src| src.as_utf8_str().to_string()
                  ),
                  tag.attributes().get("alt").flatten().map_or(
                    "A parse error occurred in this location.".to_string(),
                    |alt| alt.as_utf8_str().to_string()
                  ),
                ));
              }
              #[allow(clippy::match_same_arms)]
              "html" | "head" | "script" | "link" | "title" | "body" | "ul"
              | "style" => {}
              _ => {
                // text = tag.inner_text(parser).to_string();

                // if !(text.contains("Proxy Information")
                //   || text.contains("Proxied content from"))
                // {
                //   contents.push(format!("{text}\n\n"));
                // }
              }
            }
          });

          if text.contains("Proxy Information")
            || text.contains("Proxied content from")
          {
            break;
          }
        }

        contents.join("")
      })
    },
  );
}