diff --git a/.vscode/settings.json b/.vscode/settings.json index 94f199bd..6f482655 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -2,7 +2,8 @@ "[rust]": { "editor.formatOnSave": true }, - "rust-analyzer.checkOnSave.command": "clippy", - "rust-analyzer.checkOnSave.allTargets": true, - "rust-analyzer.checkOnSave.extraArgs": ["--","-W","clippy::pedantic"], + "rust-analyzer.checkOnSave": true, + "rust-analyzer.check.allTargets": true, + "rust-analyzer.check.command": "clippy", + "rust-analyzer.check.extraArgs": ["--","-W","clippy::pedantic"], } \ No newline at end of file diff --git a/Cargo.lock b/Cargo.lock index 8347362a..6677168e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -531,6 +531,37 @@ dependencies = [ "syn", ] +[[package]] +name = "derive_builder" +version = "0.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8d67778784b508018359cbc8696edb3db78160bab2c2a28ba7f56ef6932997f8" +dependencies = [ + "derive_builder_macro", +] + +[[package]] +name = "derive_builder_core" +version = "0.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c11bdc11a0c47bc7d37d582b5285da6849c96681023680b906673c5707af7b0f" +dependencies = [ + "darling", + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "derive_builder_macro" +version = "0.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebcda35c7a396850a55ffeac740804b40ffec779b98fffbb1738f4033f0ee79e" +dependencies = [ + "derive_builder_core", + "syn", +] + [[package]] name = "derive_more" version = "0.99.17" @@ -2836,6 +2867,7 @@ dependencies = [ "binascii", "chrono", "config", + "derive_builder", "derive_more", "fern", "futures", diff --git a/Cargo.toml b/Cargo.toml index cf90da8f..0681db0f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -61,6 +61,8 @@ uuid = { version = "1", features = ["v4"] } axum = "0.6.1" axum-server = { version = "0.4.4", features = ["tls-rustls"] } +derive_builder = "0.12" + [dev-dependencies] mockall = "0.11" diff --git a/src/apis/resources/mod.rs b/src/apis/resources/mod.rs index aa545954..8e275213 100644 --- a/src/apis/resources/mod.rs +++ b/src/apis/resources/mod.rs @@ -57,9 +57,9 @@ impl TryFrom<(&String, &Service)> for ApiServiceSettings { display_name: String); Ok(Self { - id: value.0.to_owned(), + id: value.0.clone(), enabled: value.1.enabled.unwrap(), - display_name: value.1.display_name.to_owned().unwrap(), + display_name: value.1.display_name.clone().unwrap(), socket: value.1.get_socket()?, access_tokens: value.1.get_api_tokens()?, }) diff --git a/src/databases/driver.rs b/src/databases/driver.rs index 6ed9c029..efc91962 100644 --- a/src/databases/driver.rs +++ b/src/databases/driver.rs @@ -2,11 +2,13 @@ use serde::{Deserialize, Serialize}; use super::error::Error; use super::mysql::Mysql; +use super::settings::Settings; use super::sqlite::Sqlite; use super::{Builder, Database}; -#[derive(Serialize, Deserialize, Hash, PartialEq, PartialOrd, Ord, Eq, Copy, Debug, Clone)] +#[derive(Default, Serialize, Deserialize, Hash, PartialEq, PartialOrd, Ord, Eq, Copy, Debug, Clone)] pub enum Driver { + #[default] Sqlite3, MySQL, } @@ -17,10 +19,10 @@ impl Driver { /// # Errors /// /// This function will return an error if unable to connect to the database. - pub fn build(&self, db_path: &str) -> Result, Error> { - let database = match self { - Driver::Sqlite3 => Builder::::build(db_path), - Driver::MySQL => Builder::::build(db_path), + pub fn build(settings: &Settings) -> Result, Error> { + let database = match settings.driver { + Driver::Sqlite3 => Builder::::build(settings), + Driver::MySQL => Builder::::build(settings), }?; database.create_database_tables().expect("Could not create database tables."); @@ -37,9 +39,3 @@ impl std::fmt::Display for Driver { } } } - -impl Default for Driver { - fn default() -> Self { - Driver::Sqlite3 - } -} diff --git a/src/databases/error.rs b/src/databases/error.rs index 4bee82f1..180d3f65 100644 --- a/src/databases/error.rs +++ b/src/databases/error.rs @@ -4,6 +4,7 @@ use std::sync::Arc; use r2d2_mysql::mysql::UrlError; use super::driver::Driver; +use super::settings::Settings; use crate::located_error::{Located, LocatedError}; #[derive(thiserror::Error, Debug, Clone)] @@ -44,6 +45,20 @@ pub enum Error { source: LocatedError<'static, r2d2::Error>, driver: Driver, }, + + #[error("Failed to convert to driver settings, expected: {expected}, actual {actual}, settings: {settings:?}, {location}")] + WrongDriver { + location: &'static Location<'static>, + expected: Driver, + actual: Driver, + settings: Settings, + }, + + #[error("Failed to get required felid from settings: {felid}, {location}")] + MissingFelid { + location: &'static Location<'static>, + felid: String, + }, } impl From for Error { diff --git a/src/databases/mod.rs b/src/databases/mod.rs index 809decc2..669e511f 100644 --- a/src/databases/mod.rs +++ b/src/databases/mod.rs @@ -1,6 +1,7 @@ pub mod driver; pub mod error; pub mod mysql; +pub mod settings; pub mod sqlite; use std::marker::PhantomData; @@ -8,6 +9,7 @@ use std::marker::PhantomData; use async_trait::async_trait; use self::error::Error; +use self::settings::Settings; use crate::protocol::info_hash::InfoHash; use crate::tracker::auth; @@ -27,8 +29,8 @@ where /// # Errors /// /// Will return `r2d2::Error` if `db_path` is not able to create a database. - pub(self) fn build(db_path: &str) -> Result, Error> { - Ok(Box::new(T::new(db_path)?)) + pub(self) fn build(settings: &Settings) -> Result, Error> { + Ok(Box::new(T::new(settings)?)) } } @@ -39,7 +41,7 @@ pub trait Database: Sync + Send { /// # Errors /// /// Will return `r2d2::Error` if `db_path` is not able to create a database. - fn new(db_path: &str) -> Result + fn new(settings: &Settings) -> Result where Self: std::marker::Sized; diff --git a/src/databases/mysql.rs b/src/databases/mysql.rs index ff32159f..de843494 100644 --- a/src/databases/mysql.rs +++ b/src/databases/mysql.rs @@ -9,38 +9,19 @@ use r2d2_mysql::mysql::{params, Opts, OptsBuilder}; use r2d2_mysql::MysqlConnectionManager; use super::driver::Driver; +use super::settings; use crate::databases::{Database, Error}; -use crate::errors::settings::DatabaseSettingsError; use crate::protocol::common::AUTH_KEY_LENGTH; use crate::protocol::info_hash::InfoHash; -use crate::settings::DatabaseSettings; use crate::tracker::auth; const DRIVER: Driver = Driver::MySQL; #[derive(Debug, Clone, Hash, PartialEq, Eq)] -pub struct MySqlDatabaseSettings { +pub struct Settings { pub connection_url: String, } -impl TryFrom<&DatabaseSettings> for MySqlDatabaseSettings { - type Error = DatabaseSettingsError; - - fn try_from(value: &DatabaseSettings) -> Result { - match value.get_driver()? { - Driver::MySQL => Ok(MySqlDatabaseSettings { - connection_url: value.get_my_sql_connection_url()?, - }), - driver => Err(DatabaseSettingsError::WrongDriver { - field: "driver".to_string(), - expected: Driver::MySQL, - actual: driver, - data: value.to_owned(), - }), - } - } -} - pub struct Mysql { pool: Pool, } @@ -50,8 +31,9 @@ impl Database for Mysql { /// # Errors /// /// Will return `r2d2::Error` if `db_path` is not able to create `MySQL` database. - fn new(db_path: &str) -> Result { - let opts = Opts::from_url(db_path)?; + fn new(settings: &settings::Settings) -> Result { + let mysql_settings = settings.get_mysql_settings()?; + let opts = Opts::from_url(mysql_settings.connection_url.as_str())?; let builder = OptsBuilder::from_opts(opts); let manager = MysqlConnectionManager::new(builder); let pool = r2d2::Pool::builder().build(manager).map_err(|e| (e, DRIVER))?; diff --git a/src/databases/settings.rs b/src/databases/settings.rs new file mode 100644 index 00000000..88b1bdd2 --- /dev/null +++ b/src/databases/settings.rs @@ -0,0 +1,141 @@ +use std::panic::Location; +use std::path::Path; + +use derive_builder::Builder; +use serde::{Deserialize, Serialize}; + +use super::driver::Driver::{self, Sqlite3}; +use super::driver::{self}; +use super::error::Error; +use super::{mysql, sqlite}; + +#[derive(Builder, Default, Serialize, Deserialize, PartialEq, PartialOrd, Ord, Eq, Debug, Clone, Hash)] +#[builder(default, pattern = "immutable")] +pub struct Settings { + #[builder(default = "driver::Driver::default()")] + pub driver: driver::Driver, + #[builder(default = "self.sql_lite_path_default()")] + sql_lite_3_db_file_path: Option>, + my_sql_connection_url: Option, +} + +impl SettingsBuilder { + // Private helper method that will set the default database path if the database is Sqlite. + #[allow(clippy::unused_self)] + fn sql_lite_path_default(&self) -> Option> { + if let Sqlite3 = driver::Driver::default() { + Some(Path::new("data.db").into()) + } else { + None + } + } +} + +impl Settings { + /// Returns the check of this [`Settings`]. + /// + /// # Errors + /// + /// This function will return an error if unable to transform into a definite database setting. + pub fn check(&self) -> Result<(), Error> { + match self.driver { + Driver::Sqlite3 => { + sqlite::Settings::try_from(self)?; + } + Driver::MySQL => { + mysql::Settings::try_from(self)?; + } + } + + Ok(()) + } + + pub fn get_sqlite_settings(&self) -> Result { + sqlite::Settings::try_from(self) + } + + pub fn get_mysql_settings(&self) -> Result { + mysql::Settings::try_from(self) + } +} + +#[derive(PartialEq, PartialOrd, Ord, Eq, Debug, Clone, Hash)] +pub struct OldConfig { + pub db_driver: driver::Driver, + pub db_path: String, +} + +impl TryFrom<&OldConfig> for Settings { + type Error = Error; + + fn try_from(value: &OldConfig) -> Result { + Ok(match value.db_driver { + Driver::Sqlite3 => SettingsBuilder::default() + .driver(Driver::Sqlite3) + .sql_lite_3_db_file_path(Some(Path::new(&value.db_path).into())) + .build() + .unwrap(), + Driver::MySQL => SettingsBuilder::default() + .driver(Driver::MySQL) + .my_sql_connection_url(Some(value.db_path.clone())) + .build() + .unwrap(), + }) + } +} + +impl TryFrom<&Settings> for sqlite::Settings { + type Error = Error; + + fn try_from(value: &Settings) -> Result { + Ok(Self { + database_file_path: match value.driver { + Driver::Sqlite3 => match &value.sql_lite_3_db_file_path { + Some(path) => path.clone(), + None => { + return Err(Error::MissingFelid { + location: Location::caller(), + felid: "sql_lite_3_db_file_path".to_string(), + }) + } + }, + driver => { + return Err(Error::WrongDriver { + location: Location::caller(), + expected: Driver::Sqlite3, + actual: driver, + settings: value.clone(), + }) + } + }, + }) + } +} + +impl TryFrom<&Settings> for mysql::Settings { + type Error = Error; + + fn try_from(value: &Settings) -> Result { + Ok(Self { + connection_url: match value.driver { + Driver::MySQL => match &value.my_sql_connection_url { + Some(url) => url.clone(), + None => { + return Err(Error::MissingFelid { + location: Location::caller(), + felid: "my_sql_connection_url".to_string(), + }) + } + }, + driver => { + return Err(Error::WrongDriver { + location: Location::caller(), + expected: Driver::MySQL, + actual: driver, + settings: value.clone(), + }) + } + }, + }) + } +} diff --git a/src/databases/sqlite.rs b/src/databases/sqlite.rs index fad047d3..1496f3d9 100644 --- a/src/databases/sqlite.rs +++ b/src/databases/sqlite.rs @@ -7,36 +7,18 @@ use r2d2::Pool; use r2d2_sqlite::SqliteConnectionManager; use super::driver::Driver; +use super::settings; use crate::databases::{Database, Error}; -use crate::errors::settings::DatabaseSettingsError; use crate::protocol::clock::DurationSinceUnixEpoch; use crate::protocol::info_hash::InfoHash; -use crate::settings::DatabaseSettings; use crate::tracker::auth; const DRIVER: Driver = Driver::Sqlite3; #[derive(Debug, Clone, Hash, PartialEq, Eq)] -pub struct Sqlite3DatabaseSettings { +pub struct Settings { pub database_file_path: Box, } -impl TryFrom<&DatabaseSettings> for Sqlite3DatabaseSettings { - type Error = DatabaseSettingsError; - - fn try_from(value: &DatabaseSettings) -> Result { - match value.get_driver()? { - Driver::Sqlite3 => Ok(Sqlite3DatabaseSettings { - database_file_path: value.get_slq_lite_3_file_path()?, - }), - driver => Err(DatabaseSettingsError::WrongDriver { - field: "driver".to_string(), - expected: Driver::Sqlite3, - actual: driver, - data: value.to_owned(), - }), - } - } -} pub struct Sqlite { pool: Pool, @@ -47,8 +29,9 @@ impl Database for Sqlite { /// # Errors /// /// Will return `r2d2::Error` if `db_path` is not able to create `SqLite` database. - fn new(db_path: &str) -> Result { - let cm = SqliteConnectionManager::file(db_path); + fn new(settings: &settings::Settings) -> Result { + let sqlite_settings = settings.get_sqlite_settings()?; + let cm = SqliteConnectionManager::file(sqlite_settings.database_file_path); Pool::new(cm).map_or_else(|err| Err((err, Driver::Sqlite3).into()), |pool| Ok(Sqlite { pool })) } diff --git a/src/errors/settings.rs b/src/errors/settings.rs index 75ee2959..ab11e3ac 100644 --- a/src/errors/settings.rs +++ b/src/errors/settings.rs @@ -2,9 +2,7 @@ use thiserror::Error; use super::FilePathError; use crate::databases; -use crate::settings::{ - CommonSettings, DatabaseSettings, GlobalSettings, ServiceNoSecrets, ServiceProtocol, TlsSettings, TrackerSettings, -}; +use crate::settings::{CommonSettings, GlobalSettings, ServiceNoSecrets, ServiceProtocol, TlsSettings, TrackerSettings}; #[derive(Error, Clone, Debug, Eq, Hash, PartialEq)] pub enum SettingsError { @@ -59,11 +57,12 @@ pub enum TrackerSettingsError { } impl TrackerSettingsError { + #[must_use] pub fn get_field(&self) -> String { match self { Self::MissingRequiredField { field, data: _ } => field, } - .to_owned() + .clone() } } @@ -82,17 +81,18 @@ pub enum GlobalSettingsError { } impl GlobalSettingsError { + #[must_use] pub fn get_field(&self) -> String { match self { - Self::MissingRequiredField { field, data: _ } => field, - Self::ExternalIpBadSyntax { + Self::MissingRequiredField { field, data: _ } + | Self::ExternalIpBadSyntax { field, input: _, message: _, data: _, } => field, } - .to_owned() + .clone() } } @@ -106,45 +106,52 @@ pub enum CommonSettingsError { } impl CommonSettingsError { + #[must_use] pub fn get_field(&self) -> String { match self { - Self::MissingRequiredField { field, data: _ } => field, - Self::EmptyRequiredField { field, data: _ } => field, + Self::MissingRequiredField { field, data: _ } | Self::EmptyRequiredField { field, data: _ } => field, } - .to_owned() + .clone() } } #[derive(Error, Clone, Debug, Eq, Hash, PartialEq)] pub enum DatabaseSettingsError { #[error("Required Field is missing (null)!")] - MissingRequiredField { field: String, data: DatabaseSettings }, + MissingRequiredField { + field: String, + data: databases::settings::Settings, + }, #[error("Required Field is empty (0 or \"\")!")] - EmptyRequiredField { field: String, data: DatabaseSettings }, + EmptyRequiredField { + field: String, + data: databases::settings::Settings, + }, #[error("Want {expected}, but have {actual}!")] WrongDriver { field: String, expected: databases::driver::Driver, actual: databases::driver::Driver, - data: DatabaseSettings, + data: databases::settings::Settings, }, } impl DatabaseSettingsError { + #[must_use] pub fn get_field(&self) -> String { match self { - Self::MissingRequiredField { field, data: _ } => field, - Self::EmptyRequiredField { field, data: _ } => field, - Self::WrongDriver { + Self::MissingRequiredField { field, data: _ } + | Self::EmptyRequiredField { field, data: _ } + | Self::WrongDriver { field, expected: _, actual: _, data: _, } => field, } - .to_owned() + .clone() } } @@ -186,32 +193,32 @@ pub enum ServiceSettingsError { } impl ServiceSettingsError { + #[must_use] pub fn get_field(&self) -> String { match self { - Self::MissingRequiredField { field, data: _ } => field, - Self::EmptyRequiredField { field, data: _ } => field, - Self::ApiRequiresAccessToken { field, data: _ } => field, - Self::TlsRequiresTlsConfig { field, data: _ } => field, - Self::TlsSettingsError { + Self::MissingRequiredField { field, data: _ } + | Self::EmptyRequiredField { field, data: _ } + | Self::ApiRequiresAccessToken { field, data: _ } + | Self::TlsRequiresTlsConfig { field, data: _ } + | Self::TlsSettingsError { field, source: _, data: _, - } => field, - Self::BindingAddressBadSyntax { + } + | Self::BindingAddressBadSyntax { field, input: _, message: _, data: _, - } => field, - - Self::WrongService { + } + | Self::WrongService { field, expected: _, found: _, data: _, } => field, } - .to_owned() + .clone() } } @@ -231,13 +238,14 @@ pub enum TlsSettingsError { } impl TlsSettingsError { + #[must_use] pub fn get_field(&self) -> String { match self { - Self::MissingRequiredField { field, data: _ } => field, - Self::EmptyRequiredField { field, data: _ } => field, - Self::BadCertificateFilePath { field, source: _ } => field, - Self::BadKeyFilePath { field, source: _ } => field, + Self::BadKeyFilePath { field, source: _ } + | Self::BadCertificateFilePath { field, source: _ } + | Self::EmptyRequiredField { field, data: _ } + | Self::MissingRequiredField { field, data: _ } => field, } - .to_owned() + .clone() } } diff --git a/src/http/mod.rs b/src/http/mod.rs index 42e3e4c7..d1ed6da4 100644 --- a/src/http/mod.rs +++ b/src/http/mod.rs @@ -69,9 +69,9 @@ impl TryFrom<(&String, &Service)> for HttpServiceSettings { display_name: String); Ok(Self { - id: value.0.to_owned(), + id: value.0.clone(), enabled: value.1.enabled.unwrap(), - display_name: value.1.display_name.to_owned().unwrap(), + display_name: value.1.display_name.clone().unwrap(), socket: value.1.get_socket()?, }) } @@ -119,18 +119,18 @@ impl TryFrom<(&String, &Service)> for TlsServiceSettings { check_field_is_not_empty!(value.1 => ServiceSettingsError; display_name: String); - let tls = value.1.tls.to_owned().unwrap(); + let tls = value.1.tls.clone().unwrap(); Ok(Self { - id: value.0.to_owned(), + id: value.0.clone(), enabled: value.1.enabled.unwrap(), - display_name: value.1.display_name.to_owned().unwrap(), + display_name: value.1.display_name.clone().unwrap(), socket: value.1.get_socket()?, certificate_file_path: tls .get_certificate_file_path() .map_err(|err| ServiceSettingsError::TlsSettingsError { - field: value.0.to_owned(), + field: value.0.clone(), source: err, data: value.1.into(), })?, @@ -138,7 +138,7 @@ impl TryFrom<(&String, &Service)> for TlsServiceSettings { key_file_path: tls .get_key_file_path() .map_err(|err| ServiceSettingsError::TlsSettingsError { - field: value.0.to_owned(), + field: value.0.clone(), source: err, data: value.1.into(), })?, diff --git a/src/lib.rs b/src/lib.rs index e080d63e..b6675587 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -26,6 +26,7 @@ pub mod config_const { #[macro_use] extern crate lazy_static; +extern crate derive_builder; pub mod static_time { use std::time::SystemTime; diff --git a/src/settings/manager.rs b/src/settings/manager.rs index 22414520..d96eab30 100644 --- a/src/settings/manager.rs +++ b/src/settings/manager.rs @@ -26,7 +26,7 @@ pub struct SettingsManager { impl Default for SettingsManager { fn default() -> Self { Self { - settings: Ok(Default::default()), + settings: Ok(Settings::default()), } } } @@ -52,15 +52,17 @@ impl From for SettingsManager { } impl SettingsManager { + #[must_use] pub fn empty() -> Self { Self { settings: Ok(Empty::empty()), } } + #[must_use] pub fn error(errored: &SettingsErrored) -> Self { Self { - settings: Err(errored.to_owned()), + settings: Err(errored.clone()), } } @@ -107,7 +109,7 @@ impl SettingsManager { }; // if nothing else, lets load the default. - Ok(Default::default()) + Ok(SettingsManager::default()) } pub fn save(&self, to: &Path, archive_folder: &Option>) -> Result<(), SettingsManagerError> { @@ -116,7 +118,7 @@ impl SettingsManager { if let Some(existing) = existing { if let Some(archive_folder) = archive_folder { - Self::archive(existing.0, &existing.1, archive_folder)? + Self::archive(existing.0, &existing.1, archive_folder)?; } } @@ -148,7 +150,7 @@ impl SettingsManager { where R: Read, { - let data: &mut Vec = &mut Default::default(); + let data: &mut Vec = &mut Vec::default(); rdr.read_to_end(data) .map_err(|err| SettingsManagerError::FailedToReadFromBuffer { @@ -205,7 +207,7 @@ impl SettingsManager { } fn backup(&self, to: &Path, folder: &Path) -> Result<(), SettingsManagerError> { - let ext = match to.extension().map(|f| f.to_os_string()) { + let ext = match to.extension().map(std::ffi::OsStr::to_os_string) { Some(mut ext) => { ext.push(".json"); ext @@ -213,7 +215,7 @@ impl SettingsManager { None => OsString::from("json"), }; - let data: &mut Vec = &mut Default::default(); + let data: &mut Vec = &mut Vec::default(); self.write_json(data.by_ref()) .map_err(|err| SettingsManagerError::FailedToWriteToFile { @@ -237,8 +239,8 @@ impl SettingsManager { source: IoError::from(err).into(), })?; - let mut hasher: DefaultHasher = Default::default(); - let data: &mut Vec = &mut Default::default(); + let mut hasher: DefaultHasher = DefaultHasher::default(); + let data: &mut Vec = &mut Vec::default(); // todo: lock and stream the file instead of loading the full file into memory. let _size = rdr @@ -288,14 +290,13 @@ impl SettingsManager { pub fn import_old(from: &Path, backup_folder: &Path, error_folder: &Path) -> Result, SettingsManagerError> { let import_error_folder = error_folder.join("import"); - let mut file = match get_file_at(from, OpenOptions::new().read(true)) { - Ok(rdr) => rdr, - Err(_) => { - return Ok(None); - } + let mut file = if let Ok(rdr) = get_file_at(from, OpenOptions::new().read(true)) { + rdr + } else { + return Ok(None); }; - let data: &mut Vec = &mut Default::default(); + let data: &mut Vec = &mut Vec::default(); let _ = file .0 @@ -303,7 +304,7 @@ impl SettingsManager { .map_err(|err| SettingsManagerError::FailedToProcessOldSettings { source: SettingsManagerError::FailedToReadFromFile { message: "(old_file)".to_string(), - from: file.1.to_owned(), + from: file.1.clone(), source: SettingsManagerError::FailedToReadFromBuffer { source: IoError::from(err).into(), } @@ -315,7 +316,7 @@ impl SettingsManager { let parsed = toml::de::from_slice(data.as_slice()).map_err(|err| SettingsManagerError::FailedToProcessOldSettings { source: SettingsManagerError::FailedToReadFromFile { message: "(old settings toml)".to_string(), - from: file.1.to_owned(), + from: file.1.clone(), source: SettingsManagerError::FailedToDeserializeFromToml { source: err.into() }.into(), } .into(), @@ -324,9 +325,9 @@ impl SettingsManager { let mut builder = TrackerSettingsBuilder::empty(); // Attempt One - let test_builder = builder.to_owned().import_old(&parsed); + let test_builder = builder.clone().import_old(&parsed); { - if let Err(err) = TryInto::::try_into(test_builder.to_owned()) { + if let Err(err) = TryInto::::try_into(test_builder.clone()) { Self::make_folder(error_folder)?; Self::make_folder(&import_error_folder)?; let test = "First"; @@ -340,7 +341,7 @@ impl SettingsManager { let broken = Self::error(&SettingsErrored::new(&test_builder.tracker_settings, &err)); - let ext = match file.1.extension().map(|f| f.to_os_string()) { + let ext = match file.1.extension().map(std::ffi::OsStr::to_os_string) { Some(mut ext) => { ext.push(format!(".{}", test.to_lowercase())); ext @@ -357,9 +358,9 @@ impl SettingsManager { } // Attempt with Defaults - let test_builder = builder.to_owned().import_old(&parsed); + let test_builder = builder.clone().import_old(&parsed); { - if let Err(err) = TryInto::::try_into(test_builder.to_owned()) { + if let Err(err) = TryInto::::try_into(test_builder.clone()) { Self::make_folder(error_folder)?; Self::make_folder(&import_error_folder)?; let test = "Second"; @@ -373,7 +374,7 @@ impl SettingsManager { let broken = Self::error(&SettingsErrored::new(&test_builder.tracker_settings, &err)); - let ext = match file.1.extension().map(|f| f.to_os_string()) { + let ext = match file.1.extension().map(std::ffi::OsStr::to_os_string) { Some(mut ext) => { ext.push(format!(".{}", test.to_lowercase())); ext @@ -388,7 +389,7 @@ impl SettingsManager { } // Final Attempt - let settings = match TryInto::::try_into(builder.to_owned()) { + let settings = match TryInto::::try_into(builder.clone()) { Ok(tracker) => Self { settings: Ok(tracker.into()), }, @@ -407,7 +408,7 @@ impl SettingsManager { let broken = Self::error(&SettingsErrored::new(&builder.tracker_settings, &err)); - let ext = match file.1.extension().map(|f| f.to_os_string()) { + let ext = match file.1.extension().map(std::ffi::OsStr::to_os_string) { Some(mut ext) => { ext.push(format!(".{}", test.to_lowercase())); ext @@ -458,9 +459,8 @@ impl SettingsManager { if let Ok(path) = folder.canonicalize() { if path.is_dir() { return Ok(()); - } else { - return Err(SettingsManagerError::FailedToResolveDirectory { at: folder.into() }); } + return Err(SettingsManagerError::FailedToResolveDirectory { at: folder.into() }); } match fs::create_dir(folder) { Ok(_) => Ok(()), @@ -517,7 +517,7 @@ mod tests { let manager = SettingsManager::read(&temp).unwrap(); - assert_eq!(manager, Default::default()) + assert_eq!(manager, SettingsManager::default()); } #[test] @@ -533,15 +533,15 @@ mod tests { #[test] fn it_should_write_and_read_errored_settings() { - let path = env::temp_dir().as_path().join(format!("test_errored.{}", Uuid::new_v4())); - let mut file_rw = get_file_at(&path, OpenOptions::new().write(true).read(true).create_new(true)).unwrap(); - #[derive(Error, Debug)] enum TestErrors { #[error("Test Error!")] Error, } + let path = env::temp_dir().as_path().join(format!("test_errored.{}", Uuid::new_v4())); + let mut file_rw = get_file_at(&path, OpenOptions::new().write(true).read(true).create_new(true)).unwrap(); + let errored: SettingsManager = SettingsErrored::new(&TrackerSettings::default(), &TestErrors::Error).into(); errored.write_json(std::io::Write::by_ref(&mut file_rw.0)).unwrap(); @@ -549,7 +549,7 @@ mod tests { let error_returned = SettingsManager::read_json(file_rw.0).unwrap(); - assert_eq!(errored, error_returned) + assert_eq!(errored, error_returned); } #[test] @@ -564,6 +564,6 @@ mod tests { let settings_returned = SettingsManager::read_json(file_rw.0).unwrap(); - assert_eq!(settings, settings_returned) + assert_eq!(settings, settings_returned); } } diff --git a/src/settings/mod.rs b/src/settings/mod.rs index a12a68c1..4ec684b2 100644 --- a/src/settings/mod.rs +++ b/src/settings/mod.rs @@ -12,11 +12,8 @@ use serde::{Deserialize, Serialize}; use self::old_settings::DatabaseDriversOld; use crate::apis::resources::{ApiServiceSettings, ApiTokens}; -use crate::databases::mysql::MySqlDatabaseSettings; -use crate::databases::sqlite::Sqlite3DatabaseSettings; use crate::errors::settings::{ - CommonSettingsError, DatabaseSettingsError, GlobalSettingsError, ServiceSettingsError, SettingsError, TlsSettingsError, - TrackerSettingsError, + CommonSettingsError, GlobalSettingsError, ServiceSettingsError, SettingsError, TlsSettingsError, TrackerSettingsError, }; use crate::helpers::get_file_at; use crate::http::{HttpServiceSettings, TlsServiceSettings}; @@ -118,7 +115,7 @@ impl SettingsErrored { namespace: SETTINGS_NAMESPACE_ERRORED.to_string(), version: SETTINGS_VERSION.to_string(), error: error.to_string(), - tracker: tracker.to_owned(), + tracker: tracker.clone(), } } } @@ -135,7 +132,7 @@ impl Default for Settings { Self { namespace: SETTINGS_NAMESPACE.to_string(), version: SETTINGS_VERSION.to_string(), - tracker: Default::default(), + tracker: TrackerSettings::default(), } } } @@ -143,8 +140,8 @@ impl Default for Settings { impl Empty for Settings { fn empty() -> Self { Self { - namespace: Default::default(), - version: Default::default(), + namespace: String::default(), + version: String::default(), tracker: Empty::empty(), } } @@ -199,17 +196,17 @@ impl Settings { pub struct TrackerSettings { pub global: Option, pub common: Option, - pub database: Option, + pub database: Option, pub services: Option, } impl Default for TrackerSettings { fn default() -> Self { Self { - global: Some(Default::default()), - common: Some(Default::default()), - database: Some(Default::default()), - services: Some(Default::default()), + global: Some(GlobalSettings::default()), + common: Some(CommonSettings::default()), + database: Some(databases::settings::SettingsBuilder::default().build().unwrap()), + services: Some(Services::default()), } } } @@ -227,7 +224,7 @@ impl Empty for TrackerSettings { impl TrackerSettings { fn check(&self) -> Result<(), TrackerSettingsError> { - check_field_is_not_none!(self.to_owned() => TrackerSettingsError; + check_field_is_not_none!(self.clone() => TrackerSettingsError; global, common, database, services ); Ok(()) @@ -256,7 +253,7 @@ impl From for TrackerSettingsBuilder { impl From> for TrackerSettingsBuilder { fn from(tracker_settings: Arc) -> Self { Self { - tracker_settings: (*tracker_settings).to_owned(), + tracker_settings: (*tracker_settings).clone(), } } } @@ -278,15 +275,15 @@ impl Fix for TrackerSettings { global: self .global .filter(|p| p.check().is_ok()) - .map_or_else(|| Some(Default::default()), |_f| None), + .map_or_else(|| Some(GlobalSettings::default()), |_f| None), common: self .common .filter(|p| p.check().is_ok()) - .map_or_else(|| Some(Default::default()), |_f| None), - database: self - .database - .filter(|p| p.check().is_ok()) - .map_or_else(|| Some(Default::default()), |_f| None), + .map_or_else(|| Some(CommonSettings::default()), |_f| None), + database: self.database.filter(|p| p.check().is_ok()).map_or_else( + || Some(databases::settings::SettingsBuilder::default().build().unwrap()), + |_f| None, + ), services: None, } } @@ -319,7 +316,7 @@ impl TryInto for TrackerSettingsBuilder { let settings = TrackerSettings { global: Some(GlobalSettingsBuilder::from(self.tracker_settings.global.unwrap()).try_into()?), common: Some(CommonSettingsBuilder::from(self.tracker_settings.common.unwrap()).try_into()?), - database: Some(DatabaseSettingsBuilder::from(self.tracker_settings.database.unwrap()).try_into()?), + database: Some(self.tracker_settings.database.unwrap()), services: match self.tracker_settings.services { Some(services) => Some(ServicesBuilder::from(services).try_into()?), None => None, @@ -331,10 +328,11 @@ impl TryInto for TrackerSettingsBuilder { } impl TrackerSettingsBuilder { + #[must_use] pub fn with_global(self, global: &GlobalSettings) -> Self { Self { tracker_settings: TrackerSettings { - global: Some(global.to_owned()), + global: Some(global.clone()), common: self.tracker_settings.common, database: self.tracker_settings.database, services: self.tracker_settings.services, @@ -342,43 +340,47 @@ impl TrackerSettingsBuilder { } } + #[must_use] pub fn with_common(self, common: &CommonSettings) -> Self { Self { tracker_settings: TrackerSettings { global: self.tracker_settings.global, - common: Some(common.to_owned()), + common: Some(common.clone()), database: self.tracker_settings.database, services: self.tracker_settings.services, }, } } - pub fn with_database(self, database: &DatabaseSettings) -> Self { + #[must_use] + pub fn with_database(self, database: &databases::settings::Settings) -> Self { Self { tracker_settings: TrackerSettings { global: self.tracker_settings.global, common: self.tracker_settings.common, - database: Some(database.to_owned()), + database: Some(database.clone()), services: self.tracker_settings.services, }, } } + #[must_use] pub fn with_services(self, services: &Services) -> Self { Self { tracker_settings: TrackerSettings { global: self.tracker_settings.global, common: self.tracker_settings.common, database: self.tracker_settings.database, - services: Some(services.to_owned()), + services: Some(services.clone()), }, } } + #[must_use] pub fn import_old(mut self, old_settings: &old_settings::Settings) -> Self { // Global let mut builder = match self.tracker_settings.global.as_ref() { - Some(settings) => GlobalSettingsBuilder::from(settings.to_owned()), + Some(settings) => GlobalSettingsBuilder::from(settings.clone()), None => GlobalSettingsBuilder::empty(), }; builder = builder.import_old(old_settings); @@ -387,7 +389,7 @@ impl TrackerSettingsBuilder { // Common let mut builder = match self.tracker_settings.common.as_ref() { - Some(settings) => CommonSettingsBuilder::from(settings.to_owned()), + Some(settings) => CommonSettingsBuilder::from(settings.clone()), None => CommonSettingsBuilder::empty(), }; builder = builder.import_old(old_settings); @@ -395,29 +397,22 @@ impl TrackerSettingsBuilder { self.tracker_settings.common = Some(builder.common_settings); // Database - if let Some(driver) = old_settings.db_driver { - self.tracker_settings.database = Some(DatabaseSettingsBuilder::empty().database_settings); - - self.tracker_settings.database.as_mut().unwrap().driver = Some(match driver { - DatabaseDriversOld::Sqlite3 => databases::driver::Driver::Sqlite3, - DatabaseDriversOld::MySQL => databases::driver::Driver::MySQL, - }); - - if let Some(val) = old_settings.db_path.as_ref() { - match driver { - DatabaseDriversOld::Sqlite3 => { - self.tracker_settings.database.as_mut().unwrap().sql_lite_3_db_file_path = Some(Path::new(val).into()); - } - DatabaseDriversOld::MySQL => { - self.tracker_settings.database.as_mut().unwrap().my_sql_connection_url = Some(val.to_owned()) - } - } - } - } + self.tracker_settings.database = old_settings.db_driver.map(|d| match d { + DatabaseDriversOld::Sqlite3 => databases::settings::SettingsBuilder::default() + .driver(databases::driver::Driver::Sqlite3) + .sql_lite_3_db_file_path(old_settings.db_path.as_ref().map(|p| Path::new(p).into())) + .build() + .unwrap(), + DatabaseDriversOld::MySQL => databases::settings::SettingsBuilder::default() + .driver(databases::driver::Driver::MySQL) + .my_sql_connection_url(old_settings.db_path.as_ref().cloned()) + .build() + .unwrap(), + }); // Services let mut builder = match self.tracker_settings.services.as_ref() { - Some(settings) => ServicesBuilder::from(settings.to_owned()), + Some(settings) => ServicesBuilder::from(settings.clone()), None => ServicesBuilder::empty(), }; builder = builder.import_old(old_settings); @@ -465,10 +460,12 @@ impl GlobalSettings { Ok(()) } + #[must_use] pub fn get_tracker_mode(&self) -> Mode { self.tracker_mode.unwrap_or_default() } + #[must_use] pub fn get_log_filter_level(&self) -> log::LevelFilter { match self.log_filter_level.unwrap_or(LogFilterLevel::Info) { LogFilterLevel::Off => log::LevelFilter::Off, @@ -480,12 +477,13 @@ impl GlobalSettings { } } + #[must_use] pub fn get_external_ip_opt(&self) -> Option { self.external_ip } pub fn is_on_reverse_proxy(&self) -> Result { - check_field_is_not_none!(self.to_owned() => GlobalSettingsError; on_reverse_proxy); + check_field_is_not_none!(self.clone() => GlobalSettingsError; on_reverse_proxy); Ok(self.on_reverse_proxy.unwrap()) } @@ -512,7 +510,7 @@ impl From for GlobalSettingsBuilder { impl From> for GlobalSettingsBuilder { fn from(global_settings: Arc) -> Self { Self { - global_settings: (*global_settings).to_owned(), + global_settings: (*global_settings).clone(), } } } @@ -533,26 +531,31 @@ impl TryInto for GlobalSettingsBuilder { } impl GlobalSettingsBuilder { + #[must_use] pub fn with_external_ip(mut self, external_ip: &IpAddr) -> Self { - self.global_settings.external_ip = Some(external_ip.to_owned()); + self.global_settings.external_ip = Some(*external_ip); self } + #[must_use] pub fn with_log_filter(mut self, log_filter: &LogFilterLevel) -> Self { self.global_settings.log_filter_level = Some(*log_filter); self } + #[must_use] pub fn with_mode(mut self, mode: Mode) -> Self { self.global_settings.tracker_mode = Some(mode); self } + #[must_use] pub fn with_reverse_proxy(mut self, reverse_proxy: bool) -> Self { self.global_settings.on_reverse_proxy = Some(reverse_proxy); self } + #[must_use] pub fn import_old(mut self, old_settings: &old_settings::Settings) -> Self { if let Some(val) = old_settings.mode.as_ref() { self.global_settings.tracker_mode = Some(match val { @@ -560,7 +563,7 @@ impl GlobalSettingsBuilder { old_settings::TrackerModeOld::Listed => Mode::Listed, old_settings::TrackerModeOld::Private => Mode::Private, old_settings::TrackerModeOld::PrivateListed => Mode::PrivateListed, - }) + }); } if let Some(val) = old_settings.log_level.as_ref() { @@ -629,13 +632,13 @@ impl Empty for CommonSettings { impl CommonSettings { fn check(&self) -> Result<(), CommonSettingsError> { - check_field_is_not_none!(self.to_owned() => CommonSettingsError; + check_field_is_not_none!(self.clone() => CommonSettingsError; enable_tracker_usage_statistics, enable_persistent_statistics, enable_peerless_torrent_pruning ); - check_field_is_not_empty!(self.to_owned() => CommonSettingsError; + check_field_is_not_empty!(self.clone() => CommonSettingsError; announce_interval_seconds: u32, announce_interval_seconds_minimum: u32, peer_timeout_seconds_maximum: u32, @@ -681,6 +684,7 @@ impl TryInto for CommonSettingsBuilder { } impl CommonSettingsBuilder { + #[must_use] pub fn import_old(mut self, old_settings: &old_settings::Settings) -> Self { old_to_new!(old_settings, self.common_settings; announce_interval: announce_interval_seconds, @@ -694,102 +698,6 @@ impl CommonSettingsBuilder { } } -#[derive(Serialize, Deserialize, PartialEq, PartialOrd, Ord, Eq, Debug, Clone, Hash)] -pub struct DatabaseSettings { - driver: Option, - sql_lite_3_db_file_path: Option>, - my_sql_connection_url: Option, -} - -impl Default for DatabaseSettings { - fn default() -> Self { - Self { - driver: Some(databases::driver::Driver::default()), - sql_lite_3_db_file_path: Some(Path::new("data.db").into()), - my_sql_connection_url: None, - } - } -} - -impl Empty for DatabaseSettings { - fn empty() -> Self { - Self { - driver: None, - sql_lite_3_db_file_path: None, - my_sql_connection_url: None, - } - } -} - -impl DatabaseSettings { - fn check(&self) -> Result<(), DatabaseSettingsError> { - match self.get_driver()? { - databases::driver::Driver::Sqlite3 => { - Sqlite3DatabaseSettings::try_from(self)?; - } - databases::driver::Driver::MySQL => { - MySqlDatabaseSettings::try_from(self)?; - } - } - - Ok(()) - } - - pub fn get_driver(&self) -> Result { - check_field_is_not_none!(self.to_owned() => DatabaseSettingsError; driver); - - Ok(self.driver.unwrap()) - } - - pub fn get_slq_lite_3_file_path(&self) -> Result, DatabaseSettingsError> { - check_field_is_not_none!(self.to_owned() => DatabaseSettingsError; sql_lite_3_db_file_path); - - // todo: more checks here. - Ok(self.sql_lite_3_db_file_path.as_deref().unwrap().into()) - } - - pub fn get_my_sql_connection_url(&self) -> Result { - check_field_is_not_empty!(self.to_owned() => DatabaseSettingsError; my_sql_connection_url: String); - - // todo: more checks here. - Ok(self.my_sql_connection_url.to_owned().unwrap()) - } -} - -#[derive(Debug, PartialEq, Eq, Clone, Hash, Default)] -pub struct DatabaseSettingsBuilder { - database_settings: DatabaseSettings, -} - -impl Empty for DatabaseSettingsBuilder { - fn empty() -> Self { - Self { - database_settings: Empty::empty(), - } - } -} - -impl From for DatabaseSettingsBuilder { - fn from(database_settings: DatabaseSettings) -> Self { - Self { database_settings } - } -} - -impl TryInto for DatabaseSettingsBuilder { - type Error = SettingsError; - - fn try_into(self) -> Result { - match self.database_settings.check() { - Ok(_) => Ok(self.database_settings), - Err(source) => Err(SettingsError::DatabaseSettingsError { - message: source.to_string(), - field: source.get_field(), - source, - }), - } - } -} - /// Special Service Settings with the Private Access Secrets Removed #[derive(Serialize, Deserialize, PartialEq, PartialOrd, Ord, Eq, Debug, Clone, Hash)] pub struct ServiceNoSecrets { @@ -805,15 +713,15 @@ impl From<&Service> for ServiceNoSecrets { fn from(services: &Service) -> Self { Self { enabled: services.enabled, - display_name: services.display_name.to_owned(), + display_name: services.display_name.clone(), service: services.service, socket: services.socket, - tls: services.tls.to_owned(), + tls: services.tls.clone(), access_tokens: { services.api_tokens.as_ref().map(|access_tokens| { access_tokens .iter() - .map(|pair| (pair.0.to_owned(), "SECRET_REMOVED".to_string())) + .map(|pair| (pair.0.clone(), "SECRET_REMOVED".to_string())) .collect() }) }, @@ -934,13 +842,13 @@ impl Service { pub fn get_api_tokens(&self) -> Result { check_field_is_not_empty!(self => ServiceSettingsError; api_tokens : ApiTokens); - Ok(self.api_tokens.to_owned().unwrap()) + Ok(self.api_tokens.clone().unwrap()) } pub fn get_tls_settings(&self) -> Result { check_field_is_not_empty!(self => ServiceSettingsError; api_tokens : ApiTokens); - Ok(self.api_tokens.to_owned().unwrap()) + Ok(self.api_tokens.clone().unwrap()) } } @@ -956,10 +864,10 @@ impl Default for Services { let mut services = Services::empty(); - services.insert(api.id.to_owned(), api.into()); - services.insert(udp.id.to_owned(), udp.into()); - services.insert(http.id.to_owned(), http.into()); - services.insert(tls.id.to_owned(), tls.into()); + services.insert(api.id.clone(), api.into()); + services.insert(udp.id.clone(), udp.into()); + services.insert(http.id.clone(), http.into()); + services.insert(tls.id.clone(), tls.into()); services } @@ -977,7 +885,7 @@ impl Clean for Services { Self( self.iter() .filter(|service| service.1.check(service.0).is_ok()) - .map(|pair| (pair.0.to_owned(), pair.1.to_owned())) + .map(|pair| (pair.0.clone(), pair.1.clone())) .collect(), ) } @@ -986,7 +894,7 @@ impl Clean for Services { impl Services { pub fn check(&self) -> Result<(), ServiceSettingsError> { for service in self.iter() { - service.1.check(service.0)? + service.1.check(service.0)?; } Ok(()) @@ -1032,25 +940,26 @@ impl From for ServicesBuilder { } impl ServicesBuilder { + #[must_use] pub fn import_old(mut self, old_settings: &old_settings::Settings) -> Self { let existing_service_map = self.services.clone(); - let existing_services: HashSet<&Service, RandomState> = HashSet::from_iter(existing_service_map.0.values()); + let existing_services: HashSet<&Service, RandomState> = existing_service_map.0.values().collect::>(); let mut new_values: HashSet<(Service, String)> = HashSet::new(); if let Some(service) = old_settings.http_api.as_ref() { - new_values.insert(service.to_owned().into()); + new_values.insert(service.clone().into()); }; if let Some(services) = old_settings.udp_trackers.as_ref() { for service in services { - new_values.insert(service.to_owned().into()); + new_values.insert(service.clone().into()); } }; if let Some(services) = old_settings.http_trackers.as_ref() { for service in services { - new_values.insert(service.to_owned().into()); + new_values.insert(service.clone().into()); } }; @@ -1062,8 +971,6 @@ impl ServicesBuilder { if let Vacant(e) = self.services.0.entry(key) { e.insert(value.clone()); break; - } else { - continue; } } } @@ -1096,7 +1003,7 @@ impl TlsSettings { } pub fn get_certificate_file_path(&self) -> Result, TlsSettingsError> { - check_field_is_not_none!(self.to_owned() => TlsSettingsError; certificate_file_path); + check_field_is_not_none!(self.clone() => TlsSettingsError; certificate_file_path); get_file_at(self.certificate_file_path.as_ref().unwrap(), OpenOptions::new().read(true)) .map(|at| at.1) @@ -1107,7 +1014,7 @@ impl TlsSettings { } pub fn get_key_file_path(&self) -> Result, TlsSettingsError> { - check_field_is_not_none!(self.to_owned() => TlsSettingsError; key_file_path); + check_field_is_not_none!(self.clone() => TlsSettingsError; key_file_path); get_file_at(self.key_file_path.as_ref().unwrap(), OpenOptions::new().read(true)) .map(|at| at.1) diff --git a/src/settings/old_settings.rs b/src/settings/old_settings.rs index 8f668dc2..a105db05 100644 --- a/src/settings/old_settings.rs +++ b/src/settings/old_settings.rs @@ -76,8 +76,7 @@ impl From for (Service, String) { socket: val .bind_address .as_ref() - .map(|socket| SocketAddr::from_str(socket.as_str()).ok()) - .unwrap_or(None), + .and_then(|socket| SocketAddr::from_str(socket.as_str()).ok()), tls: None, api_tokens: None, }, @@ -108,8 +107,7 @@ impl From for (Service, String) { socket: val .bind_address .as_ref() - .map(|socket| SocketAddr::from_str(socket.as_str()).ok()) - .unwrap_or(None), + .and_then(|socket| SocketAddr::from_str(socket.as_str()).ok()), tls: Some(TlsSettings { certificate_file_path: { val.ssl_cert_path.as_ref().map(|path| Path::new(path).into()) }, key_file_path: { val.ssl_key_path.as_ref().map(|path| Path::new(path).into()) }, @@ -127,8 +125,7 @@ impl From for (Service, String) { socket: val .bind_address .as_ref() - .map(|socket| SocketAddr::from_str(socket.as_str()).ok()) - .unwrap_or(None), + .and_then(|socket| SocketAddr::from_str(socket.as_str()).ok()), tls: None, api_tokens: None, }, @@ -155,8 +152,7 @@ impl From for (Service, String) { socket: val .bind_address .as_ref() - .map(|socket| SocketAddr::from_str(socket.as_str()).ok()) - .unwrap_or(None), + .and_then(|socket| SocketAddr::from_str(socket.as_str()).ok()), tls: None, api_tokens: val.access_tokens, }, diff --git a/src/tracker/mod.rs b/src/tracker/mod.rs index acbf7d53..8eda274d 100644 --- a/src/tracker/mod.rs +++ b/src/tracker/mod.rs @@ -19,6 +19,7 @@ use tokio::sync::{RwLock, RwLockReadGuard}; use self::error::Error; use crate::config::Configuration; use crate::databases::driver::Driver; +use crate::databases::settings::OldConfig; use crate::databases::{self, Database}; use crate::protocol::info_hash::InfoHash; @@ -50,7 +51,11 @@ impl Tracker { stats_event_sender: Option>, stats_repository: statistics::Repo, ) -> Result { - let database = Driver::build(&config.db_driver, &config.db_path)?; + let db_settings = databases::settings::Settings::try_from(&OldConfig { + db_driver: config.db_driver, + db_path: config.db_path.clone(), + })?; + let database = Driver::build(&db_settings)?; Ok(Tracker { config: config.clone(), diff --git a/src/tracker/mode.rs b/src/tracker/mode.rs index 0217ff98..402ddefb 100644 --- a/src/tracker/mode.rs +++ b/src/tracker/mode.rs @@ -2,13 +2,14 @@ use derive_more::Display; use serde; use serde::{Deserialize, Serialize}; -#[derive(Serialize, Deserialize, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug, Hash, Display)] +#[derive(Default, Serialize, Deserialize, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug, Hash, Display)] #[serde(rename_all = "snake_case")] pub enum Mode { // Will track every new info hash and serve every peer. Public, // Will only track whitelisted info hashes. + #[default] Listed, // Will only serve authenticated peers @@ -17,9 +18,3 @@ pub enum Mode { // Will only track whitelisted info hashes and serve authenticated peers PrivateListed, } - -impl Default for Mode { - fn default() -> Self { - Mode::Listed - } -} diff --git a/src/udp/mod.rs b/src/udp/mod.rs index 074fa67b..26b2d870 100644 --- a/src/udp/mod.rs +++ b/src/udp/mod.rs @@ -57,9 +57,9 @@ impl TryFrom<(&String, &Service)> for UdpServiceSettings { display_name: String); Ok(Self { - id: value.0.to_owned(), + id: value.0.clone(), enabled: value.1.enabled.unwrap(), - display_name: value.1.display_name.to_owned().unwrap(), + display_name: value.1.display_name.clone().unwrap(), socket: value.1.get_socket()?, }) }