relay/src/routes/index.rs

91 lines
2.5 KiB
Rust
Raw Normal View History

2021-09-18 17:55:39 +00:00
use crate::{
config::Config,
data::{Node, State},
2021-09-18 17:55:39 +00:00
error::{Error, ErrorKind},
};
2020-03-23 17:38:39 +00:00
use actix_web::{web, HttpResponse};
use rand::{seq::SliceRandom, thread_rng};
2020-03-23 17:38:39 +00:00
use std::io::BufWriter;
2022-11-23 17:51:51 +00:00
const MINIFY_CONFIG: minify_html::Cfg = minify_html::Cfg {
do_not_minify_doctype: true,
ensure_spec_compliant_unquoted_attribute_values: true,
keep_closing_tags: true,
keep_html_and_head_opening_tags: false,
keep_spaces_between_attributes: true,
keep_comments: false,
minify_css: true,
2023-05-24 15:19:34 +00:00
minify_css_level_1: true,
minify_css_level_2: false,
minify_css_level_3: false,
minify_js: true,
2022-11-23 17:51:51 +00:00
remove_bangs: true,
remove_processing_instructions: true,
};
fn open_reg(node: &Node) -> bool {
node.instance
.as_ref()
.map(|i| i.reg)
.or_else(|| node.info.as_ref().map(|i| i.reg))
.unwrap_or(false)
}
2022-11-01 20:57:33 +00:00
#[tracing::instrument(name = "Index", skip(config, state))]
2021-02-10 04:17:20 +00:00
pub(crate) async fn route(
2020-03-23 17:38:39 +00:00
state: web::Data<State>,
config: web::Data<Config>,
2021-09-18 17:55:39 +00:00
) -> Result<HttpResponse, Error> {
let all_nodes = state.node_cache.nodes().await?;
2022-11-21 20:23:37 +00:00
let mut nodes = Vec::new();
let mut local = Vec::new();
for node in all_nodes {
if !state.is_connected(&node.base) {
continue;
}
2022-11-21 20:23:37 +00:00
if node
.base
.authority_str()
.map(|authority| {
config
.local_domains()
.iter()
2022-11-21 20:25:24 +00:00
.any(|domain| domain.as_str() == authority)
2022-11-21 20:23:37 +00:00
})
.unwrap_or(false)
{
local.push(node);
} else {
nodes.push(node);
}
}
nodes.sort_by(|lhs, rhs| match (open_reg(lhs), open_reg(rhs)) {
(true, true) | (false, false) => std::cmp::Ordering::Equal,
(true, false) => std::cmp::Ordering::Less,
(false, true) => std::cmp::Ordering::Greater,
});
if let Some((i, _)) = nodes.iter().enumerate().find(|(_, node)| !open_reg(node)) {
nodes[..i].shuffle(&mut thread_rng());
nodes[i..].shuffle(&mut thread_rng());
} else {
nodes.shuffle(&mut thread_rng());
}
2020-03-23 17:38:39 +00:00
let mut buf = BufWriter::new(Vec::new());
2023-01-23 14:38:55 +00:00
crate::templates::index_html(&mut buf, &local, &nodes, &config)?;
2022-11-23 17:51:51 +00:00
let html = buf.into_inner().map_err(|e| {
2022-11-02 18:55:45 +00:00
tracing::error!("Error rendering template, {}", e.error());
2021-09-18 17:55:39 +00:00
ErrorKind::FlushBuffer
2020-03-23 17:38:39 +00:00
})?;
2022-11-23 17:51:51 +00:00
let html = minify_html::minify(&html, &MINIFY_CONFIG);
Ok(HttpResponse::Ok().content_type("text/html").body(html))
2020-03-23 17:38:39 +00:00
}