rustream/routes/
basics.rs

1use std::collections::HashMap;
2use std::path::Path;
3use std::sync::Arc;
4
5use actix_web::{HttpRequest, HttpResponse, web};
6use actix_web::http::StatusCode;
7use fernet::Fernet;
8
9use crate::{constant, routes, squire};
10
11/// Handles the health endpoint, returning a JSON response indicating the server is healthy.
12///
13/// # Returns
14///
15/// Returns an `HttpResponse` with a status of 200 (OK), content type "application/json",
16/// and a JSON body containing the string "Healthy".
17#[get("/health")]
18pub async fn health() -> HttpResponse {
19    HttpResponse::Ok()
20        .content_type("application/json")
21        .json("Healthy")
22}
23
24/// Handles the root endpoint, logging the connection and returning an HTML response.
25///
26/// # Arguments
27///
28/// * `request` - A reference to the Actix web `HttpRequest` object.
29/// * `session` - Session struct that holds the `session_mapping` and `session_tracker` to handle sessions.
30/// * `metadata` - Struct containing metadata of the application.
31/// * `template` - Configuration container for the loaded templates.
32///
33/// # Returns
34///
35/// Returns an `HttpResponse` with the index page as its body.
36#[get("/")]
37pub async fn root(request: HttpRequest,
38                  session: web::Data<Arc<constant::Session>>,
39                  metadata: web::Data<Arc<constant::MetaData>>,
40                  template: web::Data<Arc<minijinja::Environment<'static>>>) -> HttpResponse {
41    let (_host, _last_accessed) = squire::custom::log_connection(&request, &session);
42    let index = template.get_template("index").unwrap();
43    HttpResponse::build(StatusCode::OK)
44        .content_type("text/html; charset=utf-8")
45        .body(index.render(minijinja::context!(version => &metadata.pkg_version)).unwrap())
46}
47
48/// Handles the profile endpoint, and returns an HTML response.
49///
50/// # Arguments
51///
52/// * `request` - A reference to the Actix web `HttpRequest` object.
53/// * `fernet` - Fernet object to encrypt the auth payload that will be set as `session_token` cookie.
54/// * `session` - Session struct that holds the `session_mapping` and `session_tracker` to handle sessions.
55/// * `metadata` - Struct containing metadata of the application.
56/// * `config` - Configuration data for the application.
57/// * `template` - Configuration container for the loaded templates.
58///
59/// # Returns
60///
61/// Returns an `HttpResponse` with the profile page as its body.
62#[get("/profile")]
63pub async fn profile(request: HttpRequest,
64                     fernet: web::Data<Arc<Fernet>>,
65                     session: web::Data<Arc<constant::Session>>,
66                     metadata: web::Data<Arc<constant::MetaData>>,
67                     config: web::Data<Arc<squire::settings::Config>>,
68                     template: web::Data<Arc<minijinja::Environment<'static>>>) -> HttpResponse {
69    let auth_response = squire::authenticator::verify_token(&request, &config, &fernet, &session);
70    if !auth_response.ok {
71        return routes::auth::failed_auth(auth_response, &config);
72    }
73    let (_host, last_accessed) = squire::custom::log_connection(&request, &session);
74    let index = template.get_template("profile").unwrap();
75    let mut access_map = HashMap::new();
76    if !last_accessed.is_empty() {
77        let filepath = Path::new(&last_accessed);
78        let extn = filepath.extension().unwrap().to_str().unwrap();
79        let name = filepath.iter().last().unwrap().to_string_lossy().to_string();
80        let path = format!("/stream/{}", &last_accessed);
81        let font = if last_accessed.contains(constant::SECURE_INDEX) {
82            "fa-solid fa-lock".to_string()
83        } else {
84            squire::content::get_file_font(extn)
85        };
86        access_map = HashMap::from([
87            ("name", name), ("font", font), ("path", path)
88        ]);
89    }
90    HttpResponse::build(StatusCode::OK)
91        .content_type("text/html; charset=utf-8")
92        .body(index.render(minijinja::context!(
93            version => &metadata.pkg_version,
94            user => &auth_response.username,
95            time_left => &auth_response.time_left,
96            file => access_map,
97        )).unwrap())
98}