Skip to content

Commit 6088f95

Browse files
committed
Refactor code, remove binary addition and add docstrings
Remove temporary linux build GH action
1 parent c7f5d2c commit 6088f95

File tree

11 files changed

+77
-161
lines changed

11 files changed

+77
-161
lines changed

.github/workflows/temp-linux.yml

-113
This file was deleted.

Cargo.toml

+5-2
Original file line numberDiff line numberDiff line change
@@ -23,9 +23,12 @@ path = "src/lib.rs"
2323
name = "rustream"
2424
path = "src/main.rs"
2525

26-
# [build]
26+
# https://docs.rs/releases/queue
27+
# https://docs.rs/about/metadata
28+
# https://doc.rust-lang.org/cargo/reference/config.html?highlight=RUSTDOCFLAGS
2729
# export RUSTDOCFLAGS="document-private-items no-deps"
28-
# rustdocflags = ["document-private-items no-deps"]
30+
[package.metadata.docs.rs]
31+
rustdoc-args = ["--document-private-items"]
2932

3033
[dependencies]
3134
actix-rt = "2.9.0"

README.md

+17-8
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,13 @@
11
# RuStream
22

3-
[![made-with-rust](https://img.shields.io/badge/Made%20with-Rust-black?style=for-the-badge&logo=Rust)][rust]
3+
[![made-with-rust][rust-logo]][rust-src-page]
44

5-
[![build](https://github.com/thevickypedia/RuStream/actions/workflows/rust.yml/badge.svg)][build]
5+
[![build][gh-logo]][build]
6+
[![crates.io][crates-logo]][crates]
7+
[![docs.rs][docs-logo]][docs]
68

79
#### Summary
8-
[`RuStream`][1] is an application written in Rust to stream videos using Actix API via authenticated sessions.
10+
[`RuStream`][repo] is an application written in Rust to stream videos using Actix API via authenticated sessions.
911

1012
## Usage
1113

@@ -63,7 +65,7 @@ async fn main() {
6365
- `--version` / `-v` - Get package version
6466

6567
#### Config file
66-
[RuStream][1] requires a JSON file with secrets loaded as key-value paris.
68+
[RuStream][repo] requires a JSON file with secrets loaded as key-value paris.
6769

6870
<details>
6971
<summary><i><strong>Sample content of JSON file</strong></i></summary>
@@ -96,9 +98,16 @@ cargo clippy --no-deps --fix --allow-dirty
9698

9799
&copy; Vignesh Rao
98100

99-
Licensed under the [MIT License][2]
101+
Licensed under the [MIT License][license]
100102

101-
[1]: https://github.com/thevickypedia/RuStream
102-
[2]: https://github.com/thevickypedia/RuStream/blob/main/LICENSE
103+
[repo]: https://github.com/thevickypedia/RuStream
104+
[license]: https://github.com/thevickypedia/RuStream/blob/main/LICENSE
103105
[build]: https://github.com/thevickypedia/RuStream/actions/workflows/rust.yml
104-
[rust]: https://www.rust-lang.org/
106+
[rust-src-page]: https://www.rust-lang.org/
107+
[rust-logo]: https://img.shields.io/badge/Made%20with-Rust-black?style=for-the-badge&logo=Rust
108+
[gh-logo]: https://github.com/thevickypedia/RuStream/actions/workflows/rust.yml/badge.svg
109+
[docs-logo]: https://docs.rs/RuStream/badge.svg
110+
[docs]: https://docs.rs/RuStream
111+
[crates]: https://crates.io/crates/RuStream
112+
[gh-checks]: https://github.com/thevickypedia/RuStream/actions/workflows/rust.yml
113+
[crates-logo]: https://img.shields.io/crates/v/RuStream.svg

src/constant.rs

+9-11
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,13 @@
1-
use std::{env, path};
1+
use std::env;
22
use std::collections::HashMap;
33
use std::sync::Mutex;
44

55
use fernet::Fernet;
66
use lazy_static::lazy_static;
77

8-
pub fn get_binary() -> String {
9-
let binary = env::args().next().unwrap();
10-
path::Path::new(&binary).file_name().unwrap().to_str().unwrap().to_string()
11-
}
12-
13-
/// Struct to store the cargo information
8+
/// Struct to store the cargo information gathered at compile time using the `env!` macro.
149
#[derive(Debug)]
1510
pub struct Cargo {
16-
pub binary: String,
1711
pub crate_name: String,
1812
pub manifest_dir: String,
1913
pub authors: Vec<String>,
@@ -36,7 +30,6 @@ pub struct Cargo {
3630
/// - [GitHub Issues](https://github.com/rust-lang/cargo/issues/11966#issue-1664748892)
3731
pub fn build_info() -> Cargo {
3832
let cargo = Cargo {
39-
binary: get_binary(),
4033
crate_name: env!("CARGO_CRATE_NAME").to_string(),
4134
manifest_dir: env!("CARGO_MANIFEST_DIR").to_string(),
4235
authors: env!("CARGO_PKG_AUTHORS").split(',').map(String::from).collect(),
@@ -54,11 +47,16 @@ pub fn build_info() -> Cargo {
5447
}
5548

5649
lazy_static! {
57-
pub static ref FERNET: Fernet = Fernet::new(&generate_key()).unwrap();
50+
pub static ref FERNET: Fernet = Fernet::new(&fernet_key()).unwrap();
5851
}
5952

6053
/// Create a [Fernet](https://docs.rs/fernet/latest/fernet/) object to encrypt and decrypt session token.
61-
fn generate_key() -> String {
54+
///
55+
/// Generates a random key, that can be safely passed to `Fernet::new()`
56+
///
57+
/// # Returns
58+
/// Random key as a `String`
59+
fn fernet_key() -> String {
6260
Fernet::generate_key()
6361
}
6462

src/lib.rs

+18-13
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,23 @@
1+
#![allow(rustdoc::bare_urls)]
2+
#![doc = include_str!("../README.md")]
3+
14
#[macro_use]
25
extern crate actix_web;
36

47
use std::io;
58

69
use actix_web::{App, HttpServer, middleware, web};
7-
use rand::prelude::SliceRandom;
810
use openssl::ssl::{SslAcceptor, SslFiletype, SslMethod};
11+
use rand::prelude::SliceRandom;
912

10-
mod squire;
11-
mod jinja;
13+
/// Module to load all the static values and required structs during startup.
1214
mod constant;
15+
/// Module to read the HTML files and load as Jinja templates.
16+
mod jinja;
17+
/// Module for all the API entry points.
1318
mod routes;
19+
/// Module to store all the helper functions.
20+
mod squire;
1421

1522
/// Contains entrypoint and initializer settings to trigger the asynchronous HTTPServer
1623
///
@@ -33,8 +40,8 @@ pub async fn start() -> io::Result<()> {
3340
let cargo = constant::build_info();
3441
let args = squire::parser::arguments();
3542

36-
squire::startup::init_logger(args.debug, &cargo);
37-
println!("{}[v{}] - {}", cargo.pkg_name, cargo.pkg_version, cargo.description);
43+
squire::startup::init_logger(args.debug, &cargo.crate_name);
44+
println!("{}[v{}] - {}", &cargo.pkg_name, &cargo.pkg_version, &cargo.description);
3845
let arts = [squire::ascii_art::DOG, squire::ascii_art::DOLPHIN, squire::ascii_art::HORSE];
3946
println!("{}", arts.choose(&mut rand::thread_rng()).unwrap());
4047

@@ -45,7 +52,7 @@ pub async fn start() -> io::Result<()> {
4552
let template_clone = template.clone();
4653
let host = format!("{}:{}", config.video_host, config.video_port);
4754
log::info!("{} [workers:{}] running on http://{} (Press CTRL+C to quit)",
48-
cargo.pkg_name, config.workers, host);
55+
&cargo.pkg_name, &config.workers, &host);
4956
/*
5057
|| syntax is creating a closure that serves as the argument to the HttpServer::new() method.
5158
The closure is defining the configuration for the Actix web server.
@@ -75,16 +82,14 @@ pub async fn start() -> io::Result<()> {
7582
if config.cert_file.exists() && config.key_file.exists() {
7683
log::info!("Binding SSL certificate to serve over HTTPS");
7784
let mut builder = SslAcceptor::mozilla_intermediate(SslMethod::tls()).unwrap();
78-
builder
79-
.set_private_key_file(&config.key_file, SslFiletype::PEM)
80-
.unwrap();
85+
builder.set_private_key_file(&config.key_file, SslFiletype::PEM).unwrap();
8186
builder.set_certificate_chain_file(&config.cert_file).unwrap();
8287
server.bind_openssl(host, builder)?
83-
.run()
84-
.await
88+
.run()
89+
.await
8590
} else {
8691
server.bind(host)?
87-
.run()
88-
.await
92+
.run()
93+
.await
8994
}
9095
}

src/routes/auth.rs

+9
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,11 @@ pub struct DetailError {
2828
///
2929
/// * `config` - Configuration data for the application.
3030
/// * `request` - Actix HttpRequest containing information about the incoming request.
31+
///
32+
/// # Returns
33+
///
34+
/// * `200` - HttpResponse with a session-token and redirect URL to the `/home` entrypoint.
35+
/// * `401` - HttpResponse with an error message for failed authentication.
3136
#[post("/login")]
3237
pub async fn login(config: web::Data<Arc<squire::settings::Config>>, request: HttpRequest) -> HttpResponse {
3338
let verified = routes::authenticator::verify_login(&request, &config);
@@ -145,6 +150,10 @@ pub async fn home(config: web::Data<Arc<squire::settings::Config>>,
145150
/// # Arguments
146151
///
147152
/// * `request` - Actix HttpRequest containing information about the incoming request.
153+
///
154+
/// # Returns
155+
///
156+
/// HttpResponse with either a session expiry or unauthorized message.
148157
#[get("/error")]
149158
pub async fn error(environment: web::Data<Arc<Mutex<minijinja::Environment<'static>>>>,
150159
request: HttpRequest) -> HttpResponse {

src/routes/authenticator.rs

+11-5
Original file line numberDiff line numberDiff line change
@@ -143,7 +143,7 @@ pub fn verify_token(request: &HttpRequest, config: &Data<Arc<squire::settings::C
143143
return AuthToken {
144144
ok: false,
145145
detail: "Server doesn't recognize your session".to_string(),
146-
username: "NA".to_string()
146+
username: "NA".to_string(),
147147
};
148148
}
149149
if let Some(cookie) = request.cookie("session_token") {
@@ -157,7 +157,9 @@ pub fn verify_token(request: &HttpRequest, config: &Data<Arc<squire::settings::C
157157
// Max time and expiry for session token is set in the Cookie, but this is a fallback mechanism
158158
if stored_key != *cookie_key {
159159
return AuthToken {
160-
ok: false, detail: "Invalid session token".to_string(), username
160+
ok: false,
161+
detail: "Invalid session token".to_string(),
162+
username,
161163
};
162164
}
163165
if current_time - timestamp > config.session_duration as i64 {
@@ -166,16 +168,20 @@ pub fn verify_token(request: &HttpRequest, config: &Data<Arc<squire::settings::C
166168
AuthToken {
167169
ok: true,
168170
detail: format!("Session valid for {}s", timestamp + config.session_duration as i64 - current_time),
169-
username
171+
username,
170172
}
171173
} else {
172174
AuthToken {
173-
ok: false, detail: "Invalid session token".to_string(), username: "NA".to_string()
175+
ok: false,
176+
detail: "Invalid session token".to_string(),
177+
username: "NA".to_string(),
174178
}
175179
}
176180
} else {
177181
AuthToken {
178-
ok: false, detail: "Session information not found".to_string(), username: "NA".to_string()
182+
ok: false,
183+
detail: "Session information not found".to_string(),
184+
username: "NA".to_string(),
179185
}
180186
}
181187
}

src/routes/mod.rs

+3
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,8 @@
1+
/// Module for the primary and health check entrypoints.
12
pub mod basics;
3+
/// Module for all the video based entrypoints.
24
pub mod video;
5+
/// Module for `/home`, `/login`, `/logout` and `/error` entrypoints.
36
pub mod auth;
47
pub mod authenticator;
58
pub mod images;

src/squire/secure.rs

-1
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,6 @@ use base64::{Engine as _, engine::general_purpose::URL_SAFE};
55
use rand::{Rng, thread_rng};
66
use sha2::{Digest, Sha512};
77

8-
98
/// Calculates the SHA-512 hash value for the given payload.
109
///
1110
/// # Arguments

src/squire/settings.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -36,10 +36,10 @@ pub struct Config {
3636
pub website: Vec<String>,
3737

3838
// Path to the full certificate chain file for SSL certificate
39-
#[serde(default="default_ssl")]
39+
#[serde(default = "default_ssl")]
4040
pub cert_file: path::PathBuf,
4141
// Path to the private key file for SSL certificate
42-
#[serde(default="default_ssl")]
42+
#[serde(default = "default_ssl")]
4343
pub key_file: path::PathBuf
4444
}
4545

0 commit comments

Comments
 (0)