Skip to content

Commit

Permalink
Merge #86: Format World
Browse files Browse the repository at this point in the history
a39a0d9 ci: verify formating for pull requests (Cameron Garnham)
c982c4e fmt: add world format to git-blame-ignore file (Cameron Garnham)
9ddc079 fmt: format the world (Cameron Garnham)
06bb34b fmt: include rust format, same as torrust-index (Cameron Garnham)

Pull request description:

  Format all files in the Index Backend.

ACKs for top commit:
  da2ce7:
    ACK a39a0d9

Tree-SHA512: ec4b1e27e43b04b04595938f302edbe7801b49a2f3fd03df6728b54067ff0fb5fee8959e90954bd4859f8095e501a186c1eeda1ff08852c072eb4acef8ea8dab
  • Loading branch information
da2ce7 committed Nov 29, 2022
2 parents 29e2621 + a39a0d9 commit a5fcdeb
Show file tree
Hide file tree
Showing 35 changed files with 818 additions and 647 deletions.
4 changes: 4 additions & 0 deletions .git-blame-ignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
# https://git-scm.com/docs/git-blame#Documentation/git-blame.txt---ignore-revs-fileltfilegt

# Format the world!
9ddc079b00fc5d6ecd80199edc078d6793fb0a9c
20 changes: 20 additions & 0 deletions .github/workflows/develop.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
name: Development Checks

on: [pull_request]

jobs:
format:
runs-on: ubuntu-latest
env:
CARGO_TERM_COLOR: always
steps:
- uses: actions/checkout@v3
- uses: dtolnay/rust-toolchain@nightly
with:
components: rustfmt
- uses: Swatinem/rust-cache@v2
- name: Verify Formatting
uses: ClementTsang/cargo-action@main
with:
command: fmt
args: --all --check
4 changes: 4 additions & 0 deletions rustfmt.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
max_width = 130
imports_granularity = "Module"
group_imports = "StdExternalCrate"

42 changes: 17 additions & 25 deletions src/auth.rs
Original file line number Diff line number Diff line change
@@ -1,23 +1,22 @@
use actix_web::HttpRequest;
use crate::models::user::{UserClaims, UserCompact};
use jsonwebtoken::{decode, DecodingKey, Validation, Algorithm, encode, Header, EncodingKey};
use crate::utils::time::current_time;
use crate::errors::ServiceError;
use std::sync::Arc;

use actix_web::HttpRequest;
use jsonwebtoken::{decode, encode, Algorithm, DecodingKey, EncodingKey, Header, Validation};

use crate::config::Configuration;
use crate::databases::database::Database;
use crate::errors::ServiceError;
use crate::models::user::{UserClaims, UserCompact};
use crate::utils::time::current_time;

pub struct AuthorizationService {
cfg: Arc<Configuration>,
database: Arc<Box<dyn Database>>
database: Arc<Box<dyn Database>>,
}

impl AuthorizationService {
pub fn new(cfg: Arc<Configuration>, database: Arc<Box<dyn Database>>) -> AuthorizationService {
AuthorizationService {
cfg,
database
}
AuthorizationService { cfg, database }
}

pub async fn sign_jwt(&self, user: UserCompact) -> String {
Expand All @@ -28,17 +27,9 @@ impl AuthorizationService {
// TODO: create config option for setting the token validity in seconds
let exp_date = current_time() + 1_209_600; // two weeks from now

let claims = UserClaims {
user,
exp: exp_date,
};
let claims = UserClaims { user, exp: exp_date };

let token = encode(
&Header::default(),
&claims,
&EncodingKey::from_secret(key),
)
.unwrap();
let token = encode(&Header::default(), &claims, &EncodingKey::from_secret(key)).unwrap();

token
}
Expand All @@ -53,11 +44,11 @@ impl AuthorizationService {
) {
Ok(token_data) => {
if token_data.claims.exp < current_time() {
return Err(ServiceError::TokenExpired)
return Err(ServiceError::TokenExpired);
}
Ok(token_data.claims)
},
Err(_) => Err(ServiceError::TokenInvalid)
}
Err(_) => Err(ServiceError::TokenInvalid),
}
}

Expand All @@ -73,14 +64,15 @@ impl AuthorizationService {
Err(e) => Err(e),
}
}
None => Err(ServiceError::TokenNotFound)
None => Err(ServiceError::TokenNotFound),
}
}

pub async fn get_user_compact_from_request(&self, req: &HttpRequest) -> Result<UserCompact, ServiceError> {
let claims = self.get_claims_from_request(req).await?;

self.database.get_user_compact_from_id(claims.user.user_id)
self.database
.get_user_compact_from_id(claims.user.user_id)
.await
.map_err(|_| ServiceError::UserNotFound)
}
Expand Down
15 changes: 11 additions & 4 deletions src/common.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
use std::sync::Arc;
use crate::config::Configuration;

use crate::auth::AuthorizationService;
use crate::config::Configuration;
use crate::databases::database::Database;
use crate::tracker::TrackerService;
use crate::mailer::MailerService;
use crate::tracker::TrackerService;

pub type Username = String;

Expand All @@ -14,11 +15,17 @@ pub struct AppData {
pub database: Arc<Box<dyn Database>>,
pub auth: Arc<AuthorizationService>,
pub tracker: Arc<TrackerService>,
pub mailer: Arc<MailerService>
pub mailer: Arc<MailerService>,
}

impl AppData {
pub fn new(cfg: Arc<Configuration>, database: Arc<Box<dyn Database>>, auth: Arc<AuthorizationService>, tracker: Arc<TrackerService>, mailer: Arc<MailerService>) -> AppData {
pub fn new(
cfg: Arc<Configuration>,
database: Arc<Box<dyn Database>>,
auth: Arc<AuthorizationService>,
tracker: Arc<TrackerService>,
mailer: Arc<MailerService>,
) -> AppData {
AppData {
cfg,
database,
Expand Down
39 changes: 21 additions & 18 deletions src/config.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
use std::fs;
use config::{ConfigError, Config, File};
use std::path::Path;
use serde::{Serialize, Deserialize};

use config::{Config, ConfigError, File};
use serde::{Deserialize, Serialize};
use tokio::sync::RwLock;

#[derive(Debug, Clone, Serialize, Deserialize)]
Expand All @@ -14,7 +15,7 @@ pub enum TrackerMode {
Public,
Private,
Whitelisted,
PrivateWhitelisted
PrivateWhitelisted,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
Expand All @@ -36,7 +37,7 @@ pub struct Network {
pub enum EmailOnSignup {
Required,
Optional,
None
None,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
Expand Down Expand Up @@ -76,35 +77,35 @@ pub struct TorrustConfig {

#[derive(Debug)]
pub struct Configuration {
pub settings: RwLock<TorrustConfig>
pub settings: RwLock<TorrustConfig>,
}

impl Configuration {
pub fn default() -> Configuration {
let torrust_config = TorrustConfig {
website: Website {
name: "Torrust".to_string()
name: "Torrust".to_string(),
},
tracker: Tracker {
url: "udp://localhost:6969".to_string(),
mode: TrackerMode::Public,
api_url: "http://localhost:1212".to_string(),
token: "MyAccessToken".to_string(),
token_valid_seconds: 7257600
token_valid_seconds: 7257600,
},
net: Network {
port: 3000,
base_url: None
base_url: None,
},
auth: Auth {
email_on_signup: EmailOnSignup::Optional,
min_password_length: 6,
max_password_length: 64,
secret_key: "MaxVerstappenWC2021".to_string()
secret_key: "MaxVerstappenWC2021".to_string(),
},
database: Database {
connect_url: "sqlite://data.db?mode=rwc".to_string(),
torrent_info_update_interval: 3600
torrent_info_update_interval: 3600,
},
mail: Mail {
email_verification_enabled: false,
Expand All @@ -113,12 +114,12 @@ impl Configuration {
username: "".to_string(),
password: "".to_string(),
server: "".to_string(),
port: 25
}
port: 25,
},
};

Configuration {
settings: RwLock::new(torrust_config)
settings: RwLock::new(torrust_config),
}
}

Expand All @@ -134,7 +135,9 @@ impl Configuration {
eprintln!("Creating config file..");
let config = Configuration::default();
let _ = config.save_to_file().await;
return Err(ConfigError::Message(format!("Please edit the config.TOML in the root folder and restart the tracker.")))
return Err(ConfigError::Message(format!(
"Please edit the config.TOML in the root folder and restart the tracker."
)));
}

let torrust_config: TorrustConfig = match config.try_into() {
Expand All @@ -143,11 +146,11 @@ impl Configuration {
}?;

Ok(Configuration {
settings: RwLock::new(torrust_config)
settings: RwLock::new(torrust_config),
})
}

pub async fn save_to_file(&self) -> Result<(), ()>{
pub async fn save_to_file(&self) -> Result<(), ()> {
let settings = self.settings.read().await;

let toml_string = toml::to_string(&*settings).expect("Could not encode TOML value");
Expand Down Expand Up @@ -178,7 +181,7 @@ impl Configuration {
website_name: settings_lock.website.name.clone(),
tracker_url: settings_lock.tracker.url.clone(),
tracker_mode: settings_lock.tracker.mode.clone(),
email_on_signup: settings_lock.auth.email_on_signup.clone()
email_on_signup: settings_lock.auth.email_on_signup.clone(),
}
}
}
Expand All @@ -188,5 +191,5 @@ pub struct ConfigurationPublic {
website_name: String,
tracker_url: String,
tracker_mode: TrackerMode,
email_on_signup: EmailOnSignup
email_on_signup: EmailOnSignup,
}
40 changes: 29 additions & 11 deletions src/databases/database.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
use async_trait::async_trait;
use chrono::{NaiveDateTime};
use serde::{Serialize, Deserialize};
use chrono::NaiveDateTime;
use serde::{Deserialize, Serialize};

use crate::databases::mysql::MysqlDatabase;
use crate::databases::sqlite::SqliteDatabase;
use crate::models::response::{TorrentsResponse};
use crate::models::response::TorrentsResponse;
use crate::models::torrent::TorrentListing;
use crate::models::torrent_file::{DbTorrentInfo, Torrent, TorrentFile};
use crate::models::tracker_key::TrackerKey;
Expand All @@ -14,7 +14,7 @@ use crate::models::user::{User, UserAuthentication, UserCompact, UserProfile};
#[derive(PartialEq, Debug, Clone, Serialize, Deserialize)]
pub enum DatabaseDriver {
Sqlite3,
Mysql
Mysql,
}

/// Compact representation of torrent.
Expand All @@ -29,7 +29,7 @@ pub struct TorrentCompact {
pub struct Category {
pub category_id: i64,
pub name: String,
pub num_torrents: i64
pub num_torrents: i64,
}

/// Sorting options for torrents.
Expand Down Expand Up @@ -73,9 +73,7 @@ pub async fn connect_database(db_path: &str) -> Result<Box<dyn Database>, Databa
let db = MysqlDatabase::new(db_path).await;
Ok(Box::new(db))
}
_ => {
Err(DatabaseError::UnrecognizedDatabaseDriver)
}
_ => Err(DatabaseError::UnrecognizedDatabaseDriver),
}
}

Expand Down Expand Up @@ -137,10 +135,24 @@ pub trait Database: Sync + Send {
async fn delete_category(&self, category_name: &str) -> Result<(), DatabaseError>;

/// Get results of a torrent search in a paginated and sorted form as `TorrentsResponse` from `search`, `categories`, `sort`, `offset` and `page_size`.
async fn get_torrents_search_sorted_paginated(&self, search: &Option<String>, categories: &Option<Vec<String>>, sort: &Sorting, offset: u64, page_size: u8) -> Result<TorrentsResponse, DatabaseError>;
async fn get_torrents_search_sorted_paginated(
&self,
search: &Option<String>,
categories: &Option<Vec<String>>,
sort: &Sorting,
offset: u64,
page_size: u8,
) -> Result<TorrentsResponse, DatabaseError>;

/// Add new torrent and return the newly inserted `torrent_id` with `torrent`, `uploader_id`, `category_id`, `title` and `description`.
async fn insert_torrent_and_get_id(&self, torrent: &Torrent, uploader_id: i64, category_id: i64, title: &str, description: &str) -> Result<i64, DatabaseError>;
async fn insert_torrent_and_get_id(
&self,
torrent: &Torrent,
uploader_id: i64,
category_id: i64,
title: &str,
description: &str,
) -> Result<i64, DatabaseError>;

/// Get `Torrent` from `torrent_id`.
async fn get_torrent_from_id(&self, torrent_id: i64) -> Result<Torrent, DatabaseError>;
Expand All @@ -167,7 +179,13 @@ pub trait Database: Sync + Send {
async fn update_torrent_description(&self, torrent_id: i64, description: &str) -> Result<(), DatabaseError>;

/// Update the seeders and leechers info for a torrent with `torrent_id`, `tracker_url`, `seeders` and `leechers`.
async fn update_tracker_info(&self, torrent_id: i64, tracker_url: &str, seeders: i64, leechers: i64) -> Result<(), DatabaseError>;
async fn update_tracker_info(
&self,
torrent_id: i64,
tracker_url: &str,
seeders: i64,
leechers: i64,
) -> Result<(), DatabaseError>;

/// Delete a torrent with `torrent_id`.
async fn delete_torrent(&self, torrent_id: i64) -> Result<(), DatabaseError>;
Expand Down
2 changes: 1 addition & 1 deletion src/databases/mod.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
pub mod database;
pub mod sqlite;
pub mod mysql;
pub mod sqlite;
Loading

0 comments on commit a5fcdeb

Please sign in to comment.