Skip to content

Commit

Permalink
Small fixes and better code
Browse files Browse the repository at this point in the history
  • Loading branch information
Stridsvagn69420 committed Dec 4, 2022
1 parent b49ab10 commit f29e138
Show file tree
Hide file tree
Showing 4 changed files with 30 additions and 10 deletions.
14 changes: 9 additions & 5 deletions src/bin/cyrkensia.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ use std::process::exit;
use cyrkensia::Config;
use cyrkensia::meta::WIKI_HELP_URL;
use cyrkensia::server::CyrkensiaState;
use cyrkensia::server::redirect::trail_slash;
use cyrkensia::server::routes::{index, hostinfo};
use cyrkensia::server::middleware::{cors_everywhere, source_headers, license_headers};
use actix_web::{web, App, HttpServer};
Expand Down Expand Up @@ -31,11 +32,12 @@ fn init() -> io::Result<Config> {
/// Server startup.
async fn server(cfg: Config) -> io::Result<()> {
// ---- Server Init ----
let mut printer = Printer::default();
let bindaddr = cfg.bindaddr.clone();
let unbound_server = HttpServer::new(move || {
// Initialize state
let Ok(state) = CyrkensiaState::new(cfg.clone()) else {
Printer::default().errorln("Cyrkensia failed trying to initialize!", Colors::YellowBright);
eprintln!("Cyrkensia failed trying to initialize!");
exit(1);
};

Expand All @@ -49,7 +51,8 @@ async fn server(cfg: Config) -> io::Result<()> {
.wrap(license_headers())
//Routes
.route("/", web::get().to(hostinfo))
.route("/{album}", web::get().to(index))
.route("/{album}/", web::get().to(index))
.route("/{album}", web::get().to(trail_slash))
});

// ---- Server Bind ----
Expand All @@ -64,6 +67,7 @@ async fn server(cfg: Config) -> io::Result<()> {
let server = unbound_server.bind(bindaddr)?;

// ---- Ignite ----
printer.println("Cyrkensia server successfully started!", Colors::CyanBright);
server.run().await
}

Expand All @@ -73,17 +77,17 @@ async fn main() {
let mut console = Printer::default();
let Ok(config) = init() else {
console.errorln("Failed to read the config file for Cyrkensia!", Colors::RedBright);
console.errorln(&("See ".to_owned() + WIKI_HELP_URL + " for more."), Colors::Yellow);
console.errorln(&("See ".to_owned() + WIKI_HELP_URL + " for more."), Colors::YellowBright);
exit(1);
};

// Start
if let Err(serv) = server(config).await {
console.errorln("An error occured while running the server:", Colors::Red);
console.errorln("An error occured while running the server:", Colors::RedBright);
eprintln!("{serv}");
}

// Exit
console.println("Successfully stopped the Cyrkensia server!", Colors::Cyan);
console.println("Cyrkensia server successfully stopped!", Colors::CyanBright);
exit(0)
}
2 changes: 1 addition & 1 deletion src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ pub struct Config {

/// Maximum Age
///
/// The maximum age of the [Hostinfo] in milliseconds as a [u64]. If [None], the Hostinfo will always be regenerated when its route is accessed.
/// The maximum age of the [Hostinfo] in *seconds* as a [u64]. If [None], the Hostinfo will always be regenerated when its route is accessed.
/// This basically activates caching.
pub max_age: Option<u64>
}
Expand Down
13 changes: 12 additions & 1 deletion src/server/redirect.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use actix_web::{HttpResponse, Responder, http::header::LOCATION};
use actix_web::{HttpResponse, Responder, http::header::LOCATION, HttpRequest};
use crate::meta;
use super::uri_noquery;

/// Redirect
///
Expand All @@ -22,4 +23,14 @@ pub fn repository() -> impl Responder {
/// Redirects to the license text.
pub fn license() -> impl Responder {
redirect(meta::LICENSE_URL)
}

/// Trailing slash redirect
///
/// Redirects the user to a URL with a trailing slash.
pub async fn trail_slash(req: HttpRequest) -> impl Responder {
let uri = uri_noquery(req.uri());
HttpResponse::Found()
.insert_header(("Location", uri + "/"))
.finish()
}
11 changes: 8 additions & 3 deletions src/server/routes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ pub async fn hostinfo(req: HttpRequest, data: web::Data<CyrkensiaState>) -> impl
///
/// Simple struct containing the param-name and param-type needed for the [index] route.
pub struct IndexParams {
album: String
pub album: String
}

/// Album Index Route
Expand Down Expand Up @@ -106,11 +106,16 @@ pub async fn index(p: web::Path<IndexParams>, data: web::Data<CyrkensiaState>) -
};

// Codegen
let headstr = format!("<h3>{} ({})</h3>\n", meta.0, meta.1);
let headmeta = r"<style>
h2 { color: white; text-decoration: underline; }
a { color: cyan; margin: 8px; }
body { font-family: sans-serif, system-ui; background-color: #252545; }
</style>";
let headstr = format!("<h2>{} ({})</h2>", meta.0, meta.1);
let bodystr = meta.2.into_iter().fold(String::new(), |total, item| total + &format!("<a href=\"{}\">{}</a><br>\n", item, item));

// Send response
HttpResponse::Ok()
.content_type(ContentType::html())
.body(headstr + &bodystr)
.body(format!("<html><head>{}</head><body>{}{}</body></html>", headmeta, headstr, bodystr))
}

0 comments on commit f29e138

Please sign in to comment.