rustream/squire/
custom.rs

1use actix_web::{HttpRequest, HttpResponse};
2use actix_web::http::StatusCode;
3use minijinja::Template;
4
5use crate::constant;
6
7/// Logs connection information for an incoming HTTP request.
8///
9/// # Arguments
10///
11/// * `request` - A reference to the Actix web `HttpRequest` object.
12/// * `session` - Session struct that holds the `session_mapping` and `session_tracker` to handle sessions.
13///
14/// This function logs the host and user agent information of the incoming connection.
15///
16/// # Returns
17///
18/// Returns a tuple of the host, and the last streamed file path.
19pub fn log_connection(request: &HttpRequest, session: &constant::Session) -> (String, String) {
20    let host = request.connection_info().host().to_string();
21    let mut tracker = session.tracker.lock().unwrap();
22    if tracker.get(&host).is_none() {
23        tracker.insert(host.clone(), "".to_string());
24        log::info!("Connection received from {}", host);
25        if let Some(user_agent) = request.headers().get("user-agent") {
26            log::info!("User agent: {}", user_agent.to_str().unwrap())
27        }
28    }
29    return (host.clone(), tracker.get(&host).map_or("".to_string(), |s| s.to_string()));
30}
31
32/// Frames a custom response into an error page.
33///
34/// # Arguments
35///
36/// * `title` - Title to be displayed in the error page.
37/// * `error` - Jinja template for the error page.
38/// * `version` - Application's version in the title tag of the webpage.
39/// * `description` - Description to be displayed in the error page.
40/// * `status_code` - Status code of the response.
41///
42/// # Returns
43///
44/// Returns an HTTPResponse with the appropriate status code formatted as HTML.
45pub fn error(title: &str,
46             error: Template,
47             version: &String,
48             description: String,
49             status_code: StatusCode) -> HttpResponse {
50    HttpResponse::build(status_code)
51        .content_type("text/html; charset=utf-8")
52        .body(error.render(minijinja::context!(
53            version => version,
54            title => title,
55            description => description,
56            help => r"Lost your way?\n\nHit the HOME button to navigate back to home page.",
57            button_text => "HOME", button_link => "/home",
58            block_navigation => true
59        )).unwrap())
60}