From 2707e204e6c7339fc3465d9140490b67a6628dd7 Mon Sep 17 00:00:00 2001 From: SamTV12345 <40429738+SamTV12345@users.noreply.github.com> Date: Tue, 10 Dec 2024 17:52:38 +0100 Subject: [PATCH] Feat/database encapsulation (#1052) * Use better connection management * Use clippy * Only print error that id3v2 tag is not supported. * Updated frankenstein --- Cargo.toml | 4 +- diesel.toml | 2 +- .../api/controllers/device_controller.rs | 10 +- src/adapters/persistence/dbconfig/db.rs | 94 +++++++++++ src/adapters/persistence/dbconfig/mod.rs | 54 ++++++ .../dbconfig/schemas/sqlite/schema.rs | 0 src/adapters/persistence/mod.rs | 3 +- .../persistence/model/device/device_entity.rs | 14 +- .../repositories/device/device_repository.rs | 21 +-- .../repositories/device_repository.rs | 7 +- src/application/services/device/service.rs | 13 +- .../usecases/devices/create_use_case.rs | 3 +- .../usecases/devices/edit_use_case.rs | 3 +- .../usecases/devices/query_use_case.rs | 3 +- src/auth_middleware.rs | 14 +- src/command_line_runner.rs | 73 +++----- src/config/dbconfig.rs | 38 ----- src/controllers/notification_controller.rs | 9 +- src/controllers/playlist_controller.rs | 18 +- src/controllers/podcast_controller.rs | 85 +++------- src/controllers/podcast_episode_controller.rs | 19 +-- src/controllers/settings_controller.rs | 18 +- src/controllers/sys_info_controller.rs | 5 +- src/controllers/tags_controller.rs | 40 ++--- src/controllers/user_controller.rs | 37 +--- src/controllers/watch_time_controller.rs | 11 +- src/controllers/websocket_controller.rs | 17 +- src/db.rs | 34 ++-- src/dbconfig/mod.rs | 39 ----- src/gpodder/auth/authentication.rs | 23 +-- src/gpodder/episodes/gpodder_episodes.rs | 9 +- src/gpodder/session_middleware.rs | 6 +- src/gpodder/subscription/subscriptions.rs | 9 +- src/main.rs | 80 ++------- src/models/episode.rs | 122 +++++++------- src/models/favorites.rs | 65 ++++--- src/models/file_path.rs | 5 +- src/models/filter.rs | 25 ++- src/models/invite.rs | 28 ++- src/models/notification.rs | 22 +-- src/models/playlist.rs | 71 ++++---- src/models/playlist_item.rs | 33 ++-- src/models/podcast_episode.rs | 159 ++++++++---------- src/models/podcast_settings.rs | 27 ++- src/models/podcasts.rs | 91 +++++----- src/models/session.rs | 17 +- src/models/settings.rs | 23 ++- src/models/subscription.rs | 26 ++- src/models/tag.rs | 49 +++--- src/models/tags_podcast.rs | 36 ++-- src/models/user.rs | 61 +++---- src/service/download_service.rs | 46 +++-- src/service/file_service.rs | 21 +-- src/service/notification_service.rs | 7 +- src/service/path_service.rs | 5 +- src/service/podcast_episode_service.rs | 104 +++++------- src/service/rust_service.rs | 65 +++---- src/service/settings_service.rs | 12 +- src/service/user_management_service.rs | 41 ++--- src/utils/podcast_key_checker.rs | 4 +- 60 files changed, 831 insertions(+), 1149 deletions(-) create mode 100644 src/adapters/persistence/dbconfig/db.rs create mode 100644 src/adapters/persistence/dbconfig/mod.rs rename src/{ => adapters/persistence}/dbconfig/schemas/sqlite/schema.rs (100%) delete mode 100644 src/dbconfig/mod.rs diff --git a/Cargo.toml b/Cargo.toml index a3e90406..91f79b03 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -39,7 +39,7 @@ env_logger = "0.11.5" chrono = {version = "0.4.38", default-features=false, features = ["serde"]} rss = "2.0.11" actix-ws = "0.3.0" -frankenstein = "0.35.0" +frankenstein = "0.37.0" regex = "1.11.0" xml-builder = "0.5.2" diesel = { version = "2.2.5", features = ["chrono", "r2d2"] } @@ -60,7 +60,7 @@ sha1 = "0.10.6" sha256 = "1.5.0" strfmt="0.2.4" urlencoding="2.1.3" -id3 = "1.16.0" +id3 = "1.15.0" mp4ameta = "0.11.0" file-format = "0.26.0" diff --git a/diesel.toml b/diesel.toml index b8b00995..238b0884 100644 --- a/diesel.toml +++ b/diesel.toml @@ -2,7 +2,7 @@ # see https://diesel.rs/guides/configuring-diesel-cli [print_schema] -file = "src/dbconfig/schemas/sqlite/schema.rs" +file = "src/adapters/persistence/dbconfig/schemas/sqlite/schema.rs" [migrations_directory] dir = "migrations" diff --git a/src/adapters/api/controllers/device_controller.rs b/src/adapters/api/controllers/device_controller.rs index 0b3a9524..41601e16 100644 --- a/src/adapters/api/controllers/device_controller.rs +++ b/src/adapters/api/controllers/device_controller.rs @@ -1,8 +1,6 @@ use crate::gpodder::device::dto::device_post::DevicePost; use crate::models::session::Session; use crate::utils::error::CustomError; -use crate::DbPool; -use actix_web::web::Data; use actix_web::{get, post, Scope}; use actix_web::{web, HttpResponse}; use crate::adapters::api::models::device::device_response::DeviceResponse; @@ -15,8 +13,7 @@ use crate::application::usecases::devices::query_use_case::QueryUseCase; pub async fn post_device( query: web::Path<(String, String)>, device_post: web::Json, - opt_flag: Option>, - conn: Data, + opt_flag: Option> ) -> Result { match opt_flag { Some(flag) => { @@ -33,8 +30,7 @@ pub async fn post_device( caption: device_post.caption.clone(), }; - let pool = conn.get_ref(); - let device = DeviceService::create(device_create.into(), pool)?; + let device = DeviceService::create(device_create.into())?; let result = DeviceResponse::from(&device); Ok(HttpResponse::Ok().json(result)) @@ -47,7 +43,6 @@ pub async fn post_device( pub async fn get_devices_of_user( query: web::Path, opt_flag: Option>, - pool: Data, ) -> Result { match opt_flag { Some(flag) => { @@ -56,7 +51,6 @@ pub async fn get_devices_of_user( } let devices = DeviceService::query_by_username( query.clone(), - pool.get_ref(), )?; let dtos = devices diff --git a/src/adapters/persistence/dbconfig/db.rs b/src/adapters/persistence/dbconfig/db.rs new file mode 100644 index 00000000..470b163f --- /dev/null +++ b/src/adapters/persistence/dbconfig/db.rs @@ -0,0 +1,94 @@ +use std::process::exit; +use std::sync::OnceLock; +use std::time::Duration; +use diesel::Connection; +use diesel::r2d2::ConnectionManager; +use r2d2::Pool; +use crate::adapters::persistence::dbconfig::DBType; +use crate::constants::inner_constants::ENVIRONMENT_SERVICE; +use crate::DbPool; + +#[derive(Debug)] +pub struct ConnectionOptions { + pub enable_wal: bool, + pub enable_foreign_keys: bool, + pub busy_timeout: Option, +} + +impl r2d2::CustomizeConnection for ConnectionOptions { + fn on_acquire(&self, conn: &mut DBType) -> Result<(), diesel::r2d2::Error> { + use diesel::connection::SimpleConnection; + (|| { + if self.enable_wal { + conn.batch_execute("PRAGMA journal_mode = WAL; PRAGMA synchronous = NORMAL;")?; + } + if self.enable_foreign_keys { + conn.batch_execute("PRAGMA foreign_keys = ON;")?; + } + if let Some(d) = self.busy_timeout { + conn.batch_execute(&format!("PRAGMA busy_timeout = {};", d.as_millis()))?; + } + Ok(()) + })() + .map_err(diesel::r2d2::Error::QueryError) + } +} + +pub fn establish_connection() -> DBType { + let database_url = &ENVIRONMENT_SERVICE.get().unwrap().database_url; + DBType::establish(database_url).unwrap_or_else(|e| { + log::error!("Error connecting to {} with reason {}", database_url, e); + exit(1) + }) +} + +static POOL: OnceLock = OnceLock::new(); + + +pub fn get_connection() -> r2d2::PooledConnection> { + POOL.get_or_init(init_pool).get().unwrap() +} + +fn init_pool() -> DbPool { + let conn = establish_connection(); + match conn { + DBType::Postgresql(_) => { + init_postgres_db_pool(&ENVIRONMENT_SERVICE.get().unwrap().database_url) + .expect("Failed to connect to database") + } + DBType::Sqlite(_) => { + init_sqlite_db_pool(&ENVIRONMENT_SERVICE.get().unwrap().database_url) + .expect("Failed to connect to database") + } + } +} + + +fn init_postgres_db_pool( + database_url: &str, +) -> Result>, String> { + let env_service = ENVIRONMENT_SERVICE.get().unwrap(); + let db_connections = env_service.conn_number; + let manager = ConnectionManager::::new(database_url); + let pool = Pool::builder() + .max_size(db_connections as u32) + .build(manager) + .expect("Failed to create pool."); + Ok(pool) +} + +fn init_sqlite_db_pool( + database_url: &str, +) -> Result>, String> { + let manager = ConnectionManager::::new(database_url); + let pool = Pool::builder() + .max_size(16) + .connection_customizer(Box::new(ConnectionOptions { + enable_wal: true, + enable_foreign_keys: true, + busy_timeout: Some(Duration::from_secs(120)), + })) + .build(manager) + .unwrap(); + Ok(pool) +} \ No newline at end of file diff --git a/src/adapters/persistence/dbconfig/mod.rs b/src/adapters/persistence/dbconfig/mod.rs new file mode 100644 index 00000000..a0649679 --- /dev/null +++ b/src/adapters/persistence/dbconfig/mod.rs @@ -0,0 +1,54 @@ +#[path = "schemas/sqlite/schema.rs"] +pub mod schema; +pub mod db; + +use diesel::QueryResult; + +#[derive(diesel::MultiConnection)] +pub enum DBType { + Postgresql(diesel::PgConnection), + Sqlite(diesel::SqliteConnection), +} + +#[macro_export] +macro_rules! import_database_config { + () => { + pub const SQLITE_MIGRATIONS: EmbeddedMigrations = embed_migrations!("./migrations/sqlite"); + + pub const POSTGRES_MIGRATIONS: EmbeddedMigrations = + embed_migrations!("./migrations/postgres"); + }; +} + +#[macro_export] +macro_rules! execute_with_conn { + ($diesel_func:expr) => { + { + use $crate::get_connection; + use std::ops::DerefMut; + + let mut conn = get_connection(); + let _ = match conn.deref_mut() { + $crate::adapters::persistence::dbconfig::DBType::Sqlite(conn) => return $diesel_func + (conn), + $crate::adapters::persistence::dbconfig::DBType::Postgresql(conn) => return $diesel_func(conn), + }; + } + }; +} + +#[macro_export] +macro_rules! insert_with_conn { + ($diesel_func:expr) => { + { + + use $crate::get_connection; + use std::ops::DerefMut; + let mut conn = get_connection(); + let _ = match conn.deref_mut() { + $crate::adapters::persistence::dbconfig::DBType::Sqlite(conn) => $diesel_func(conn), + $crate::adapters::persistence::dbconfig::DBType::Postgresql(conn) => $diesel_func(conn), + }; + } + }; +} diff --git a/src/dbconfig/schemas/sqlite/schema.rs b/src/adapters/persistence/dbconfig/schemas/sqlite/schema.rs similarity index 100% rename from src/dbconfig/schemas/sqlite/schema.rs rename to src/adapters/persistence/dbconfig/schemas/sqlite/schema.rs diff --git a/src/adapters/persistence/mod.rs b/src/adapters/persistence/mod.rs index 06da8922..3c6310d5 100644 --- a/src/adapters/persistence/mod.rs +++ b/src/adapters/persistence/mod.rs @@ -1,2 +1,3 @@ pub mod repositories; -pub mod model; \ No newline at end of file +pub mod model; +pub mod dbconfig; \ No newline at end of file diff --git a/src/adapters/persistence/model/device/device_entity.rs b/src/adapters/persistence/model/device/device_entity.rs index 98bddca9..afb08117 100644 --- a/src/adapters/persistence/model/device/device_entity.rs +++ b/src/adapters/persistence/model/device/device_entity.rs @@ -1,4 +1,4 @@ -use crate::dbconfig::schema::devices; +use crate::adapters::persistence::dbconfig::schema::devices; use crate::gpodder::device::dto::device_post::DevicePost; use crate::{execute_with_conn, DBType as DbConnection}; use diesel::QueryDsl; @@ -55,10 +55,10 @@ impl DeviceEntity { } #[allow(clippy::redundant_closure_call)] - pub fn save(&self, conn: &mut DbConnection) -> Result { - use crate::dbconfig::schema::devices::dsl::*; - - execute_with_conn!(conn, |conn| diesel::insert_into(devices) + pub fn save(&self) -> Result { + use crate::adapters::persistence::dbconfig::schema::devices::dsl::*; + + execute_with_conn!(|conn| diesel::insert_into(devices) .values(self) .get_result(conn)); } @@ -67,7 +67,7 @@ impl DeviceEntity { conn: &mut DbConnection, username_to_insert: String, ) -> Result, diesel::result::Error> { - use crate::dbconfig::schema::devices::dsl::*; + use crate::adapters::persistence::dbconfig::schema::devices::dsl::*; devices .filter(username.eq(username_to_insert)) .load::(conn) @@ -78,7 +78,7 @@ impl DeviceEntity { username1: &str, conn: &mut DbConnection, ) -> Result { - use crate::dbconfig::schema::devices::dsl::*; + use crate::adapters::persistence::dbconfig::schema::devices::dsl::*; diesel::delete(devices.filter(username.eq(username1))).execute(conn) } } diff --git a/src/adapters/persistence/repositories/device/device_repository.rs b/src/adapters/persistence/repositories/device/device_repository.rs index 9ca979f3..3150a5ed 100644 --- a/src/adapters/persistence/repositories/device/device_repository.rs +++ b/src/adapters/persistence/repositories/device/device_repository.rs @@ -1,7 +1,6 @@ use diesel::RunQueryDsl; use crate::adapters::persistence::model::device::device_entity::DeviceEntity; use crate::application::repositories::device_repository::DeviceRepository; -use crate::dbconfig::DBType; use crate::domain::models::device::model::Device; use crate::execute_with_conn; use crate::utils::error::{map_db_error, CustomError}; @@ -9,14 +8,14 @@ use crate::utils::error::{map_db_error, CustomError}; pub struct DeviceRepositoryImpl; use diesel::QueryDsl; -use crate::dbconfig::schema::devices::dsl::*; +use crate::adapters::persistence::dbconfig::schema::devices::dsl::*; use diesel::ExpressionMethods; -use DBType as DbConnection; +use crate::adapters::persistence::dbconfig::db::get_connection; impl DeviceRepository for DeviceRepositoryImpl { - fn create(device: Device, conn: &mut DBType) -> Result { + fn create(device: Device) -> Result { let device_entity: DeviceEntity = device.into(); - execute_with_conn!(conn, |conn| diesel::insert_into(devices) + execute_with_conn!(|conn| diesel::insert_into(devices) .values(device_entity) .get_result(conn) .map_err(map_db_error) @@ -24,17 +23,19 @@ impl DeviceRepository for DeviceRepositoryImpl { } - fn get_devices_of_user(username_to_find: String, conn: &mut DBType) -> Result, + fn get_devices_of_user(username_to_find: String) -> Result, CustomError> { devices .filter(username.eq(username_to_find)) - .load::(conn) + .load::(&mut get_connection()) .map(|device_entity| device_entity.into_iter().map(|device_entity| device_entity.into()).collect()) .map_err(map_db_error) } - fn delete_by_username(username1: &str, conn: &mut DBType) -> Result<(), CustomError> { - use crate::dbconfig::schema::devices::dsl::*; - diesel::delete(devices.filter(username.eq(username1))).execute(conn).map(|_|()).map_err(map_db_error) + fn delete_by_username(username1: &str) -> Result<(), CustomError> { + use crate::adapters::persistence::dbconfig::schema::devices::dsl::*; + diesel::delete(devices.filter(username.eq(username1))).execute(&mut get_connection()).map(|_|()) + .map_err + (map_db_error) } } \ No newline at end of file diff --git a/src/application/repositories/device_repository.rs b/src/application/repositories/device_repository.rs index 9d387b88..4ab3d149 100644 --- a/src/application/repositories/device_repository.rs +++ b/src/application/repositories/device_repository.rs @@ -1,9 +1,8 @@ -use crate::dbconfig::DBType; use crate::domain::models::device::model::Device; use crate::utils::error::CustomError; pub trait DeviceRepository { - fn create(device: Device, conn: &mut DBType) -> Result; - fn get_devices_of_user(username: String, conn: &mut DBType) -> Result, CustomError>; - fn delete_by_username(username: &str, conn: &mut DBType) -> Result<(), CustomError>; + fn create(device: Device) -> Result; + fn get_devices_of_user(username: String) -> Result, CustomError>; + fn delete_by_username(username: &str) -> Result<(), CustomError>; } \ No newline at end of file diff --git a/src/application/services/device/service.rs b/src/application/services/device/service.rs index 3c8b8c9a..6ac3b69c 100644 --- a/src/application/services/device/service.rs +++ b/src/application/services/device/service.rs @@ -3,7 +3,6 @@ use crate::application::repositories::device_repository::DeviceRepository; use crate::application::usecases::devices::create_use_case::CreateUseCase; use crate::application::usecases::devices::edit_use_case::EditUseCase; use crate::application::usecases::devices::query_use_case::QueryUseCase; -use crate::DbPool; use crate::domain::models::device::model::Device; use crate::utils::error::CustomError; @@ -11,19 +10,19 @@ pub struct DeviceService; impl CreateUseCase for DeviceService { - fn create(device_to_safe: Device, pool: &DbPool) -> Result { - DeviceRepositoryImpl::create(device_to_safe, &mut pool.get().unwrap()) + fn create(device_to_safe: Device) -> Result { + DeviceRepositoryImpl::create(device_to_safe) } } impl QueryUseCase for DeviceService { - fn query_by_username(username: String, pool: &DbPool) -> Result, CustomError> { - DeviceRepositoryImpl::get_devices_of_user(username, &mut pool.get().unwrap()) + fn query_by_username(username: String) -> Result, CustomError> { + DeviceRepositoryImpl::get_devices_of_user(username) } } impl EditUseCase for DeviceService { - fn delete_by_username(username: &str, conn: &DbPool) -> Result<(), CustomError> { - DeviceRepositoryImpl::delete_by_username(username, &mut conn.get().unwrap()) + fn delete_by_username(username: &str) -> Result<(), CustomError> { + DeviceRepositoryImpl::delete_by_username(username) } } \ No newline at end of file diff --git a/src/application/usecases/devices/create_use_case.rs b/src/application/usecases/devices/create_use_case.rs index da1fdd29..da6a0d74 100644 --- a/src/application/usecases/devices/create_use_case.rs +++ b/src/application/usecases/devices/create_use_case.rs @@ -1,7 +1,6 @@ -use crate::DbPool; use crate::domain::models::device::model::Device; use crate::utils::error::CustomError; pub trait CreateUseCase { - fn create(device_to_safe: Device, conn: &DbPool) -> Result; + fn create(device_to_safe: Device) -> Result; } \ No newline at end of file diff --git a/src/application/usecases/devices/edit_use_case.rs b/src/application/usecases/devices/edit_use_case.rs index 0581f3a1..7cd79f16 100644 --- a/src/application/usecases/devices/edit_use_case.rs +++ b/src/application/usecases/devices/edit_use_case.rs @@ -1,6 +1,5 @@ -use crate::DbPool; use crate::utils::error::CustomError; pub trait EditUseCase { - fn delete_by_username(username: &str, conn: &DbPool) -> Result<(), CustomError>; + fn delete_by_username(username: &str) -> Result<(), CustomError>; } \ No newline at end of file diff --git a/src/application/usecases/devices/query_use_case.rs b/src/application/usecases/devices/query_use_case.rs index 6f655a47..68d1d2bc 100644 --- a/src/application/usecases/devices/query_use_case.rs +++ b/src/application/usecases/devices/query_use_case.rs @@ -1,7 +1,6 @@ -use crate::DbPool; use crate::domain::models::device::model::Device; use crate::utils::error::CustomError; pub trait QueryUseCase { - fn query_by_username(username: String, pool: &DbPool) -> Result, CustomError>; + fn query_by_username(username: String) -> Result, CustomError>; } \ No newline at end of file diff --git a/src/auth_middleware.rs b/src/auth_middleware.rs index 01bcf8ba..d4b1e686 100644 --- a/src/auth_middleware.rs +++ b/src/auth_middleware.rs @@ -6,7 +6,6 @@ use std::rc::Rc; use crate::constants::inner_constants::ENVIRONMENT_SERVICE; use crate::models::user::User; -use crate::DbPool; use actix::fut::ok; use actix_web::body::{EitherBody, MessageBody}; use actix_web::error::{ErrorForbidden, ErrorUnauthorized}; @@ -100,9 +99,8 @@ where Some(header) => match header.to_str() { Ok(auth) => { let (username, password) = AuthFilter::extract_basic_auth(auth); - let res = req.app_data::>().unwrap(); let found_user = - User::find_by_username(username.as_str(), &mut res.get().unwrap()); + User::find_by_username(username.as_str()); if found_user.is_err() { return Box::pin(ok(req @@ -184,8 +182,7 @@ where .unwrap() .as_str() .unwrap(); - let pool = req.app_data::>().cloned().unwrap(); - let found_user = User::find_by_username(username, &mut pool.get().unwrap()); + let found_user = User::find_by_username(username); let service = Rc::clone(&self.service); match found_user { @@ -211,8 +208,7 @@ where explicit_consent: false, created_at: chrono::Utc::now().naive_utc(), api_key: None, - }, - &mut pool.get().unwrap(), + } ) .expect("Error inserting user"); req.extensions_mut().insert(user); @@ -251,8 +247,7 @@ where let token_res = header_val.to_str(); return match token_res { Ok(token) => { - let pool = req.app_data::>().cloned().unwrap(); - let found_user = User::find_by_username(token, &mut pool.get().unwrap()); + let found_user = User::find_by_username(token); let service = Rc::clone(&self.service); return match found_user { @@ -275,7 +270,6 @@ where created_at: chrono::Utc::now().naive_utc(), api_key: None, }, - &mut pool.get().unwrap(), ) .expect("Error inserting user"); req.extensions_mut().insert(user); diff --git a/src/command_line_runner.rs b/src/command_line_runner.rs index e90b90d9..3ae0c475 100644 --- a/src/command_line_runner.rs +++ b/src/command_line_runner.rs @@ -1,5 +1,4 @@ -use crate::config::dbconfig::establish_connection; -use crate::constants::inner_constants::{Role, ENVIRONMENT_SERVICE}; +use crate::constants::inner_constants::Role; use crate::controllers::sys_info_controller::built_info; use crate::models::episode::Episode; use crate::models::favorites::Favorite; @@ -18,31 +17,14 @@ use std::env::Args; use std::io::{stdin, stdout, Error, ErrorKind, Write}; use std::process::exit; use std::str::FromStr; +use crate::adapters::persistence::dbconfig::db::get_connection; use crate::application::services::device::service::DeviceService; use crate::application::usecases::devices::edit_use_case::EditUseCase; -use crate::dbconfig::DBType; -use crate::{init_postgres_db_pool, init_sqlite_db_pool}; pub async fn start_command_line(mut args: Args) { - - let pool; - { - let conn = establish_connection(); - match conn { - DBType::Postgresql(_) => { - pool = init_postgres_db_pool(&ENVIRONMENT_SERVICE.get().unwrap().database_url) - .await - .expect("Failed to connect to database"); - } - DBType::Sqlite(_) => { - pool = init_sqlite_db_pool(&ENVIRONMENT_SERVICE.get().unwrap().database_url) - .await - .expect("Failed to connect to database"); - } - } - } println!("Starting from command line"); // This needs to be nth(1) because the first argument is the binary name + let conn = &mut get_connection(); match args.nth(1).unwrap().as_str() { "help" | "--help" => { println!( @@ -61,7 +43,7 @@ pub async fn start_command_line(mut args: Args) { match podcast_rss_feed { Some(feed) => { let mut podcast_service = PodcastService::new(); - let conn = &mut establish_connection(); + let conn = &mut get_connection(); let replaced_feed = feed.replace(['\'', ' '], ""); println!("Refreshing podcast {}", replaced_feed); @@ -69,10 +51,10 @@ pub async fn start_command_line(mut args: Args) { let podcast = Podcast::get_podcast_by_rss_feed(replaced_feed, conn) .expect("Error getting podcast"); - PodcastEpisodeService::insert_podcast_episodes(conn, podcast.clone()) + PodcastEpisodeService::insert_podcast_episodes(podcast.clone()) .unwrap(); podcast_service - .schedule_episode_download(podcast, None, conn) + .schedule_episode_download(podcast, None) .unwrap(); } None => { @@ -82,24 +64,22 @@ pub async fn start_command_line(mut args: Args) { } } "refresh-all" => { - let conn = &mut establish_connection(); - let podcasts = Podcast::get_all_podcasts(&mut establish_connection()); + let podcasts = Podcast::get_all_podcasts(); let mut podcast_service = PodcastService::new(); for podcast in podcasts.unwrap() { println!("Refreshing podcast {}", podcast.name); PodcastEpisodeService::insert_podcast_episodes( - &mut establish_connection(), podcast.clone(), ) .unwrap(); podcast_service - .schedule_episode_download(podcast, None, conn) + .schedule_episode_download(podcast, None) .unwrap(); } } "list" => { - let podcasts = Podcast::get_all_podcasts(&mut establish_connection()); + let podcasts = Podcast::get_all_podcasts(); match podcasts { Ok(podcasts) => { println!("Id - Name - RSS Feed"); @@ -139,20 +119,18 @@ pub async fn start_command_line(mut args: Args) { if ask_for_confirmation().is_ok() { user.password = Some(digest(user.password.unwrap())); - if User::insert_user(&mut user, &mut establish_connection()).is_ok() { + if User::insert_user(&mut user).is_ok() { println!("User succesfully created") } } } "generate" => match args.next().unwrap().as_str() { "apiKey" => { - let conn = &mut establish_connection(); User::find_all_users(conn).iter().for_each(|u| { log::info!("Updating api key of user {}", &u.username); User::update_api_key_of_user( &u.username, uuid::Uuid::new_v4().to_string(), - conn, ) .expect("Error updating api key"); }) @@ -172,34 +150,31 @@ pub async fn start_command_line(mut args: Args) { username = trim_string(&username); match available_users.iter().find(|u| u.username == username) { Some(..) => { - Episode::delete_by_username(&mut establish_connection(), &username) + Episode::delete_by_username(&username) .expect("Error deleting entries for podcast history item"); - DeviceService::delete_by_username(&username, &pool) + DeviceService::delete_by_username(&username) .expect("Error deleting devices"); Episode::delete_by_username_and_episode( &username, - &mut establish_connection(), + conn, ) .expect("Error deleting episodes"); Favorite::delete_by_username( trim_string(&username), - &mut establish_connection(), + conn, ) .expect("Error deleting favorites"); Session::delete_by_username( - &trim_string(&username), - &mut establish_connection(), + &trim_string(&username) ) .expect("Error deleting sessions"); Subscription::delete_by_username( &trim_string(&username), - &mut establish_connection(), + &mut get_connection() ) .expect("TODO: panic message"); User::delete_by_username( - trim_string(&username), - &mut establish_connection(), - ) + trim_string(&username), &mut get_connection()) .expect("Error deleting user"); println!("User deleted") } @@ -220,7 +195,7 @@ pub async fn start_command_line(mut args: Args) { username = trim_string(&username); println!(">{}<", username); let user = - User::find_by_username(username.as_str(), &mut establish_connection()) + User::find_by_username(username.as_str()) .unwrap(); do_user_update(user) @@ -258,7 +233,7 @@ pub async fn start_command_line(mut args: Args) { } fn list_users() -> Vec { - let users = User::find_all_users(&mut establish_connection()); + let users = User::find_all_users(&mut get_connection()); users.iter().for_each(|u| { println!("|Username|Role|Explicit Consent|Created at|",); @@ -276,7 +251,7 @@ pub fn read_user_account() -> Result { let role = Role::VALUES.map(|v| v.to_string()).join(", "); retry_read("Enter your username: ", &mut username); - let user = User::find_by_username(&username, &mut establish_connection()); + let user = User::find_by_username(&username); if user.is_err() { println!("User does not exist"); @@ -386,19 +361,19 @@ fn do_user_update(mut user: User) { "Enter the new role [user,\ uploader or admin]", )); - User::update_user(user, &mut establish_connection()).expect("Error updating role"); + User::update_user(user).expect("Error updating role"); println!("Role updated"); } "password" => { let mut password = retry_read_secret("Enter the new password"); password = digest(password); user.password = Some(password); - User::update_user(user, &mut establish_connection()).expect("Error updating password"); + User::update_user(user).expect("Error updating password"); println!("Password updated"); } "consent" => { user.explicit_consent = !user.explicit_consent; - User::update_user(user, &mut establish_connection()).expect("Error switching consent"); + User::update_user(user).expect("Error switching consent"); println!("Consent preference switched"); } _ => { @@ -425,7 +400,7 @@ pub fn create_debug_message() { println!("Rustc Version: {}", built_info::RUSTC_VERSION); println!("Rustc: {}", built_info::RUSTC_VERSION); - let podcasts = Podcast::get_all_podcasts(&mut establish_connection()); + let podcasts = Podcast::get_all_podcasts(); match podcasts { Ok(podcasts) => { diff --git a/src/config/dbconfig.rs b/src/config/dbconfig.rs index fc83df45..139597f9 100644 --- a/src/config/dbconfig.rs +++ b/src/config/dbconfig.rs @@ -1,40 +1,2 @@ -use crate::constants::inner_constants::ENVIRONMENT_SERVICE; -use crate::dbconfig::DBType; -use crate::DBType as DbConnection; -use diesel::prelude::*; -use std::process::exit; -use std::time::Duration; -#[derive(Debug)] -pub struct ConnectionOptions { - pub enable_wal: bool, - pub enable_foreign_keys: bool, - pub busy_timeout: Option, -} -impl r2d2::CustomizeConnection for ConnectionOptions { - fn on_acquire(&self, conn: &mut DbConnection) -> Result<(), diesel::r2d2::Error> { - use diesel::connection::SimpleConnection; - (|| { - if self.enable_wal { - conn.batch_execute("PRAGMA journal_mode = WAL; PRAGMA synchronous = NORMAL;")?; - } - if self.enable_foreign_keys { - conn.batch_execute("PRAGMA foreign_keys = ON;")?; - } - if let Some(d) = self.busy_timeout { - conn.batch_execute(&format!("PRAGMA busy_timeout = {};", d.as_millis()))?; - } - Ok(()) - })() - .map_err(diesel::r2d2::Error::QueryError) - } -} - -pub fn establish_connection() -> DBType { - let database_url = &ENVIRONMENT_SERVICE.get().unwrap().database_url; - DBType::establish(database_url).unwrap_or_else(|e| { - log::error!("Error connecting to {} with reason {}", database_url, e); - exit(1) - }) -} diff --git a/src/controllers/notification_controller.rs b/src/controllers/notification_controller.rs index 8e1ceb13..785d41e4 100644 --- a/src/controllers/notification_controller.rs +++ b/src/controllers/notification_controller.rs @@ -1,12 +1,10 @@ -use crate::DbPool; use actix_web::web::Data; use actix_web::{get, put, web, HttpResponse}; -use std::ops::DerefMut; use std::sync::Mutex; use utoipa::ToSchema; use crate::mutex::LockResultExt; use crate::service::notification_service::NotificationService; -use crate::utils::error::{map_r2d2_error, CustomError}; +use crate::utils::error::CustomError; use crate::models::notification::Notification; #[utoipa::path( context_path="/api/v1", @@ -17,12 +15,11 @@ tag="notifications" #[get("/notifications/unread")] pub async fn get_unread_notifications( notification_service: Data>, - conn: Data, ) -> Result { let notifications = notification_service .lock() .ignore_poison() - .get_unread_notifications(conn.get().map_err(map_r2d2_error)?.deref_mut())?; + .get_unread_notifications()?; Ok(HttpResponse::Ok().json(notifications)) } @@ -41,7 +38,6 @@ tag="notifications" pub async fn dismiss_notifications( id: web::Json, notification_service: Data>, - conn: Data, ) -> Result { notification_service .lock() @@ -49,7 +45,6 @@ pub async fn dismiss_notifications( .update_status_of_notification( id.id, "dismissed", - conn.get().map_err(map_r2d2_error)?.deref_mut(), )?; Ok(HttpResponse::Ok().body("")) } diff --git a/src/controllers/playlist_controller.rs b/src/controllers/playlist_controller.rs index 07df0f62..74dff710 100644 --- a/src/controllers/playlist_controller.rs +++ b/src/controllers/playlist_controller.rs @@ -1,11 +1,8 @@ use crate::controllers::podcast_episode_controller::PodcastEpisodeWithHistory; use crate::models::playlist::Playlist; use crate::models::user::User; -use crate::utils::error::{map_r2d2_error, CustomError}; -use crate::DbPool; -use actix_web::web::Data; +use crate::utils::error::CustomError; use actix_web::{delete, get, post, put, web, HttpResponse}; -use std::ops::DerefMut; use utoipa::ToSchema; #[derive(Serialize, Deserialize, Clone, ToSchema)] @@ -35,14 +32,12 @@ tag="playlist" #[post("/playlist")] pub async fn add_playlist( requester: Option>, - conn: Data, playlist: web::Json, ) -> Result { let user = requester.unwrap().into_inner(); let playlist = playlist.into_inner(); let res = Playlist::create_new_playlist( - conn.get().map_err(map_r2d2_error)?.deref_mut(), playlist, user, )?; @@ -59,7 +54,6 @@ tag="playlist" #[put("/playlist/{playlist_id}")] pub async fn update_playlist( requester: Option>, - conn: Data, playlist: web::Json, playlist_id: web::Path, ) -> Result { @@ -67,7 +61,6 @@ pub async fn update_playlist( let playlist = playlist.into_inner(); let res = Playlist::update_playlist( - conn.get().map_err(map_r2d2_error)?.deref_mut(), playlist, playlist_id.clone(), user, @@ -85,10 +78,8 @@ tag="playlist" #[get("/playlist")] pub async fn get_all_playlists( requester: Option>, - conn: Data, ) -> Result { Playlist::get_playlists( - conn.get().map_err(map_r2d2_error)?.deref_mut(), requester.unwrap().into_inner().id, ) .map(|playlists| HttpResponse::Ok().json(playlists)) @@ -103,18 +94,15 @@ tag="playlist" #[get("/playlist/{playlist_id}")] pub async fn get_playlist_by_id( requester: Option>, - conn: Data, playlist_id: web::Path, ) -> Result { let user_id = requester.clone().unwrap(); let playlist = Playlist::get_playlist_by_user_and_id( playlist_id.clone(), user_id.clone().into_inner(), - conn.get().map_err(map_r2d2_error)?.deref_mut(), )?; let playlist = Playlist::get_playlist_dto( playlist_id.clone(), - conn.get().map_err(map_r2d2_error)?.deref_mut(), playlist, user_id.clone().into_inner(), )?; @@ -130,13 +118,11 @@ tag="playlist" #[delete("/playlist/{playlist_id}")] pub async fn delete_playlist_by_id( requester: Option>, - conn: Data, playlist_id: web::Path, ) -> Result { let user_id = requester.clone().unwrap().id; Playlist::delete_playlist_by_id( playlist_id.clone(), - conn.get().map_err(map_r2d2_error)?.deref_mut(), user_id, )?; Ok(HttpResponse::Ok().json(())) @@ -151,7 +137,6 @@ tag="playlist" #[delete("/playlist/{playlist_id}/episode/{episode_id}")] pub async fn delete_playlist_item( requester: Option>, - conn: Data, path: web::Path<(String, i32)>, ) -> Result { let user_id = requester.clone().unwrap().id; @@ -159,7 +144,6 @@ pub async fn delete_playlist_item( Playlist::delete_playlist_item( unwrapped_path.0, unwrapped_path.1, - conn.get().map_err(map_r2d2_error)?.deref_mut(), user_id, ) .await?; diff --git a/src/controllers/podcast_controller.rs b/src/controllers/podcast_controller.rs index 2834646c..9098773f 100644 --- a/src/controllers/podcast_controller.rs +++ b/src/controllers/podcast_controller.rs @@ -7,7 +7,7 @@ use crate::service::environment_service::EnvironmentService; use crate::service::mapping_service::MappingService; use crate::service::podcast_episode_service::PodcastEpisodeService; use crate::service::rust_service::PodcastService; -use crate::{get_default_image, unwrap_string, DbPool}; +use crate::{get_default_image, unwrap_string}; use actix_web::dev::PeerAddr; use actix_web::http::Method; use actix_web::web::{Data, Json, Path}; @@ -19,7 +19,6 @@ use rand::rngs::ThreadRng; use rand::Rng; use rss::Channel; use serde_json::{from_str, Value}; -use std::ops::DerefMut; use std::sync::Mutex; use std::thread; use tokio::task::spawn_blocking; @@ -34,7 +33,6 @@ use crate::models::user::User; use crate::mutex::LockResultExt; use crate::service::file_service::{perform_podcast_variable_replacement, FileService}; use crate::utils::append_to_header::add_basic_auth_headers_conditionally; -use crate::DBType as DbConnection; use futures_util::StreamExt; use reqwest::Client; use reqwest::header::HeaderMap; @@ -60,12 +58,10 @@ tag="podcasts" )] #[get("/podcasts/filter")] pub async fn get_filter( - conn: Data, requester: Option>, ) -> Result { let filter = Filter::get_filter_by_username( requester.unwrap().username.clone(), - conn.get().map_err(map_r2d2_error)?.deref_mut(), ) .await?; Ok(HttpResponse::Ok().json(filter)) @@ -81,7 +77,6 @@ tag="podcasts" #[get("/podcasts/search")] pub async fn search_podcasts( query: web::Query, - conn: Data, _podcast_service: Data>, requester: Option>, ) -> Result { @@ -92,7 +87,6 @@ pub async fn search_podcasts( let opt_filter = Filter::get_filter_by_username( requester.clone().unwrap().username.clone(), - conn.get().map_err(map_r2d2_error)?.deref_mut(), ) .await?; @@ -109,7 +103,7 @@ pub async fn search_podcasts( Some(_latest_pub.clone().to_string()), only_favored, ); - Filter::save_filter(filter, conn.get().map_err(map_r2d2_error)?.deref_mut())?; + Filter::save_filter(filter)?; match query.favored_only { true => { @@ -122,7 +116,6 @@ pub async fn search_podcasts( _order.clone(), query.title, _latest_pub.clone(), - conn.get().map_err(map_r2d2_error)?.deref_mut(), username, tag )?; @@ -136,7 +129,6 @@ pub async fn search_podcasts( _order.clone(), query.title, _latest_pub.clone(), - &mut conn.get().unwrap(), username, tag )?; @@ -157,15 +149,14 @@ tag="podcasts" #[get("/podcast/{id}")] pub async fn find_podcast_by_id( id: Path, - conn: Data, user: Option>, ) -> Result { let id_num = from_str::(&id).unwrap(); let username = user.unwrap().username.clone(); let podcast = - PodcastService::get_podcast(conn.get().map_err(map_r2d2_error)?.deref_mut(), id_num)?; - let tags = Tag::get_tags_of_podcast(conn.get().map_err(map_r2d2_error)?.deref_mut(), id_num, &username)?; + PodcastService::get_podcast(id_num)?; + let tags = Tag::get_tags_of_podcast(id_num, &username)?; let mapped_podcast = MappingService::map_podcast_to_podcast_dto(&podcast, tags); Ok(HttpResponse::Ok().json(mapped_podcast)) } @@ -179,13 +170,12 @@ tag="podcasts" )] #[get("/podcasts")] pub async fn find_all_podcasts( - conn: Data, requester: Option>, ) -> Result { let username = requester.unwrap().username.clone(); let podcasts = - PodcastService::get_podcasts(conn.get().map_err(map_r2d2_error)?.deref_mut(), username)?; + PodcastService::get_podcasts(username)?; Ok(HttpResponse::Ok().json(podcasts)) } @@ -246,7 +236,6 @@ tag="podcasts" pub async fn add_podcast( track_id: web::Json, lobby: Data, - conn: Data, requester: Option>, ) -> Result { if !requester.unwrap().is_privileged_user() { @@ -271,7 +260,6 @@ pub async fn add_podcast( let mut podcast_service = PodcastService::new(); podcast_service .handle_insert_of_podcast( - conn.get().map_err(map_r2d2_error)?.deref_mut(), PodcastInsertModel { feed_url: unwrap_string(&res["results"][0]["feedUrl"]), title: unwrap_string(&res["results"][0]["collectionName"]), @@ -298,7 +286,6 @@ pub async fn add_podcast_by_feed( rss_feed: web::Json, lobby: Data, podcast_service: Data>, - conn: Data, requester: Option>, ) -> Result { if !requester.unwrap().is_privileged_user() { @@ -325,7 +312,6 @@ pub async fn add_podcast_by_feed( let mut podcast_service = podcast_service.lock().ignore_poison().clone(); res = podcast_service .handle_insert_of_podcast( - conn.get().map_err(map_r2d2_error)?.deref_mut(), PodcastInsertModel { feed_url: rss_feed.clone().rss_feed_url.clone(), title: channel.title.clone(), @@ -356,7 +342,6 @@ tag="podcasts" pub async fn import_podcasts_from_opml( opml: web::Json, lobby: Data, - conn: Data, requester: Option>, ) -> Result { if !requester.unwrap().is_privileged_user() { @@ -367,7 +352,6 @@ pub async fn import_podcasts_from_opml( spawn_blocking(move || { for outline in document.body.outlines { let moved_lobby = lobby.clone(); - let conn = conn.clone(); thread::spawn(move || { let rt = Runtime::new().unwrap(); let rng = rand::thread_rng(); @@ -379,7 +363,6 @@ pub async fn import_podcasts_from_opml( moved_lobby, rng.clone(), environment.clone(), - conn, )); }); } @@ -399,7 +382,6 @@ tag="podcasts" pub async fn add_podcast_from_podindex( id: web::Json, lobby: Data, - conn: Data, requester: Option>, ) -> Result { if !requester.unwrap().is_privileged_user() { @@ -421,7 +403,6 @@ pub async fn add_podcast_from_podindex( match start_download_podindex( id.track_id, lobby, - conn.get().map_err(map_r2d2_error).unwrap().deref_mut(), ) { Ok(_) => {} Err(e) => { @@ -435,14 +416,13 @@ pub async fn add_podcast_from_podindex( fn start_download_podindex( id: i32, lobby: Data, - conn: &mut DbConnection, ) -> Result { let rt = Runtime::new().unwrap(); rt.block_on(async { let mut podcast_service = PodcastService::new(); podcast_service - .insert_podcast_from_podindex(conn, id, lobby) + .insert_podcast_from_podindex(id, lobby) .await }) } @@ -456,11 +436,9 @@ tag="podcasts",)] #[get("/podcasts/{podcast}/query")] pub async fn query_for_podcast( podcast: Path, - conn: Data, ) -> Result { let res = PodcastEpisodeService::query_for_podcast( &podcast, - conn.get().map_err(map_r2d2_error)?.deref_mut(), )?; Ok(HttpResponse::Ok().json(res)) @@ -476,14 +454,13 @@ tag="podcasts" pub async fn refresh_all_podcasts( lobby: Data, podcast_service: Data>, - conn: Data, requester: Option>, ) -> Result { if !requester.unwrap().is_privileged_user() { return Err(CustomError::Forbidden); } - let podcasts = Podcast::get_all_podcasts(conn.get().map_err(map_r2d2_error)?.deref_mut()); + let podcasts = Podcast::get_all_podcasts(); thread::spawn(move || { for podcast in podcasts.unwrap() { podcast_service @@ -492,7 +469,6 @@ pub async fn refresh_all_podcasts( .refresh_podcast( podcast.clone(), lobby.clone(), - conn.get().map_err(map_r2d2_error).unwrap().deref_mut(), ) .unwrap(); lobby.send_broadcast_sync(MAIN_ROOM.parse().unwrap(), serde_json::to_string(&BroadcastMessage { @@ -518,7 +494,6 @@ pub async fn download_podcast( id: Path, lobby: Data, podcast_service: Data>, - conn: Data, requester: Option>, ) -> Result { if !requester.unwrap().is_privileged_user() { @@ -528,13 +503,12 @@ pub async fn download_podcast( let id_num = from_str::(&id).unwrap(); let mut podcast_service = podcast_service.lock().ignore_poison(); let podcast = - podcast_service.get_podcast_by_id(conn.get().map_err(map_r2d2_error)?.deref_mut(), id_num); + podcast_service.get_podcast_by_id(id_num); thread::spawn(move || { let mut podcast_service = PodcastService::new(); match podcast_service.refresh_podcast( podcast.clone(), lobby.clone(), - conn.get().map_err(map_r2d2_error).unwrap().deref_mut(), ) { Ok(_) => { log::info!("Succesfully refreshed podcast."); @@ -547,7 +521,6 @@ pub async fn download_podcast( let download = podcast_service.schedule_episode_download( podcast.clone(), Some(lobby), - conn.get().map_err(map_r2d2_error).unwrap().deref_mut(), ); if download.is_err() { @@ -569,10 +542,9 @@ tag="podcasts" )] #[put("/podcast/favored")] pub async fn favorite_podcast( - update_model: web::Json, + update_model: Json, podcast_service_mutex: Data>, requester: Option>, - conn: Data, ) -> Result { let mut podcast_service = podcast_service_mutex.lock().ignore_poison(); @@ -580,7 +552,6 @@ pub async fn favorite_podcast( update_model.id, update_model.favored, requester.unwrap().username.clone(), - conn.get().map_err(map_r2d2_error)?.deref_mut(), )?; Ok(HttpResponse::Ok().json("Favorited podcast")) } @@ -595,12 +566,10 @@ tag="podcasts" pub async fn get_favored_podcasts( podcast_service_mutex: Data>, requester: Option>, - conn: Data, ) -> Result { let mut podcast_service = podcast_service_mutex.lock().ignore_poison(); let podcasts = podcast_service.get_favored_podcasts( requester.unwrap().username.clone(), - conn.get().map_err(map_r2d2_error)?.deref_mut(), )?; Ok(HttpResponse::Ok().json(podcasts)) } @@ -615,7 +584,6 @@ tag="podcasts" #[put("/podcast/{id}/active")] pub async fn update_active_podcast( id: Path, - conn: Data, requester: Option>, ) -> Result { if !requester.unwrap().is_privileged_user() { @@ -623,7 +591,7 @@ pub async fn update_active_podcast( } let id_num = from_str::(&id).unwrap(); - PodcastService::update_active_podcast(conn.get().map_err(map_r2d2_error)?.deref_mut(), id_num)?; + PodcastService::update_active_podcast(id_num)?; Ok(HttpResponse::Ok().json("Updated active podcast")) } @@ -634,7 +602,6 @@ async fn insert_outline( lobby: Data, mut rng: ThreadRng, environment: EnvironmentService, - conn: Data, ) { if !podcast.outlines.is_empty() { for outline_nested in podcast.clone().outlines { @@ -643,8 +610,7 @@ async fn insert_outline( client.clone(), lobby.clone(), rng.clone(), - environment.clone(), - conn.clone(), + environment.clone() ) .await; } @@ -687,7 +653,6 @@ async fn insert_outline( let inserted_podcast = podcast_service .handle_insert_of_podcast( - conn.get().map_err(map_r2d2_error).unwrap().deref_mut(), PodcastInsertModel { feed_url: podcast.clone().xml_url.expect("No feed url"), title: channel.clone().title.to_string(), @@ -744,7 +709,7 @@ use crate::models::settings::Setting; use crate::models::tags_podcast::TagsPodcast; use crate::utils::environment_variables::is_env_var_present_and_true; -use crate::utils::error::{map_r2d2_error, map_reqwest_error, CustomError}; +use crate::utils::error::{map_reqwest_error, CustomError}; use crate::utils::reqwest_client::get_async_sync_client; use crate::utils::rss_feed_parser::PodcastParsed; @@ -763,7 +728,6 @@ tag="podcasts" #[delete("/podcast/{id}")] pub async fn delete_podcast( data: web::Json, - db: Data, id: Path, requester: Option>, ) -> Result { @@ -771,18 +735,18 @@ pub async fn delete_podcast( return Err(CustomError::Forbidden); } - let podcast = Podcast::get_podcast(&mut db.get().unwrap(), *id).expect( + let podcast = Podcast::get_podcast(*id).expect( "Error \ finding podcast", ); if data.delete_files { FileService::delete_podcast_files(&podcast.directory_name); } - Episode::delete_watchtime(&mut db.get().unwrap(), *id)?; - PodcastEpisode::delete_episodes_of_podcast(&mut db.get().unwrap(), *id)?; - TagsPodcast::delete_tags_by_podcast_id(&mut db.get().unwrap(), *id)?; + Episode::delete_watchtime(*id)?; + PodcastEpisode::delete_episodes_of_podcast(*id)?; + TagsPodcast::delete_tags_by_podcast_id(*id)?; - Podcast::delete_podcast(&mut db.get().unwrap(), *id)?; + Podcast::delete_podcast(*id)?; Ok(HttpResponse::Ok().into()) } #[derive(Debug, Deserialize)] @@ -806,7 +770,6 @@ pub(crate) async fn proxy_podcast( query: Option>, method: Method, rq: HttpRequest, - pool: Data, ) -> Result { let is_auth_enabled = is_env_var_present_and_true(BASIC_AUTH) || is_env_var_present_and_true(OIDC_AUTH); @@ -818,16 +781,14 @@ pub(crate) async fn proxy_podcast( let api_key = query.unwrap().0; let api_key_exists = - User::check_if_api_key_exists(api_key.api_key.to_string(), &mut pool.get().unwrap()); + User::check_if_api_key_exists(api_key.api_key.to_string()); if !api_key_exists { return Ok(HttpResponse::Unauthorized().body("Unauthorized")); } } - let conn = &mut *pool.get().unwrap(); - - let opt_res = PodcastEpisodeService::get_podcast_episode_by_id(conn, ¶ms.episode_id)?; + let opt_res = PodcastEpisodeService::get_podcast_episode_by_id(¶ms.episode_id)?; if opt_res.clone().is_none() { return Ok(HttpResponse::NotFound().finish()); } @@ -886,7 +847,6 @@ pub(crate) async fn proxy_podcast( pub async fn update_podcast_settings( id: Path, settings: Json, - conn: Data, requester: Option>, ) -> Result { if !requester.unwrap().is_privileged_user() { @@ -894,10 +854,9 @@ pub async fn update_podcast_settings( } let id_num = id.into_inner(); - let mut conn = conn.get().map_err(map_r2d2_error)?; let mut settings = settings.into_inner(); settings.podcast_id = id_num; - let updated_podcast = PodcastSetting::update_settings(&settings, &mut conn)?; + let updated_podcast = PodcastSetting::update_settings(&settings)?; Ok(HttpResponse::Ok().json(updated_podcast)) } @@ -906,7 +865,6 @@ pub async fn update_podcast_settings( #[get("/podcasts/{id}/settings")] pub async fn get_podcast_settings( id: Path, - conn: Data, requester: Option>, ) -> Result { if !requester.unwrap().is_privileged_user() { @@ -914,8 +872,7 @@ pub async fn get_podcast_settings( } let id_num = id.into_inner(); - let mut conn = conn.get().map_err(map_r2d2_error)?; - let settings = PodcastSetting::get_settings(&mut conn, id_num)?; + let settings = PodcastSetting::get_settings(id_num)?; Ok(HttpResponse::Ok().json(settings)) } diff --git a/src/controllers/podcast_episode_controller.rs b/src/controllers/podcast_episode_controller.rs index 608f288f..5b09bb8c 100644 --- a/src/controllers/podcast_episode_controller.rs +++ b/src/controllers/podcast_episode_controller.rs @@ -9,13 +9,11 @@ use crate::models::user::User; use utoipa::ToSchema; use crate::service::mapping_service::MappingService; use crate::service::podcast_episode_service::PodcastEpisodeService; -use crate::utils::error::{map_r2d2_error, CustomError}; -use crate::DbPool; +use crate::utils::error::CustomError; use actix_web::web::{Data, Json, Query}; use actix_web::{delete, get, post, put}; use actix_web::{web, HttpResponse}; use serde_json::from_str; -use std::ops::DerefMut; use crate::models::settings::Setting; use crate::service::file_service::perform_episode_variable_replacement; @@ -48,12 +46,10 @@ pub async fn find_all_podcast_episodes_of_podcast( id: web::Path, requester: Option>, last_podcast_episode: Query, - conn: Data, ) -> Result { let last_podcast_episode = last_podcast_episode.into_inner(); let id_num = from_str(&id).unwrap(); let res = PodcastEpisodeService::get_podcast_episodes_of_podcast( - conn.get().map_err(map_r2d2_error)?.deref_mut(), id_num, last_podcast_episode.last_podcast_episode, requester.unwrap().into_inner(), @@ -82,14 +78,12 @@ pub struct TimeLinePodcastEpisode { #[get("/podcast/available/gpodder")] pub async fn get_available_podcasts_not_in_webview( requester: Option>, - conn: Data, ) -> Result { if !requester.unwrap().is_privileged_user() { return Err(CustomError::Forbidden) } - let mut retrieved_conn = conn.get().map_err(map_r2d2_error)?; let found_episodes = Episode:: - find_episodes_not_in_webview(&mut retrieved_conn)?; + find_episodes_not_in_webview()?; Ok(HttpResponse::Ok().json(found_episodes)) } @@ -117,13 +111,11 @@ tag = "podcasts" )] #[get("/podcasts/timeline")] pub async fn get_timeline( - conn: Data, requester: Option>, favored_only: Query, ) -> Result { let res = TimelineItem::get_timeline( requester.unwrap().username.clone(), - conn.get().map_err(map_r2d2_error)?.deref_mut(), favored_only.into_inner(), )?; @@ -161,7 +153,6 @@ tag = "podcast_episodes" #[put("/podcast/{id}/episodes/download")] pub async fn download_podcast_episodes_of_podcast( id: web::Path, - conn: Data, requester: Option>, ) -> Result { if !requester.unwrap().is_privileged_user() { @@ -170,24 +161,20 @@ pub async fn download_podcast_episodes_of_podcast( thread::spawn(move || { let res = PodcastEpisode::get_podcast_episode_by_id( - conn.get().map_err(map_r2d2_error).unwrap().deref_mut(), &id.into_inner(), ) .unwrap(); if let Some(podcast_episode) = res { let podcast = Podcast::get_podcast( - conn.get().map_err(map_r2d2_error).unwrap().deref_mut(), podcast_episode.podcast_id, ) .unwrap(); PodcastEpisodeService::perform_download( &podcast_episode.clone(), podcast, - conn.get().map_err(map_r2d2_error).unwrap().deref_mut(), ) .unwrap(); PodcastEpisode::update_deleted( - conn.get().map_err(map_r2d2_error).unwrap().deref_mut(), &podcast_episode.clone().episode_id, false, ) @@ -212,7 +199,6 @@ tag = "podcast_episodes" pub async fn delete_podcast_episode_locally( id: web::Path, requester: Option>, - db: Data, lobby: Data, ) -> Result { if !requester.unwrap().is_privileged_user() { @@ -221,7 +207,6 @@ pub async fn delete_podcast_episode_locally( let delted_podcast_episode = PodcastEpisodeService::delete_podcast_episode_locally( &id.into_inner(), - &mut db.get().unwrap(), )?; lobby.send_broadcast(MAIN_ROOM.parse().unwrap(),serde_json::to_string(&BroadcastMessage { podcast_episode: Some(delted_podcast_episode), diff --git a/src/controllers/settings_controller.rs b/src/controllers/settings_controller.rs index a5cb35a6..9a7bc193 100644 --- a/src/controllers/settings_controller.rs +++ b/src/controllers/settings_controller.rs @@ -6,12 +6,10 @@ use crate::mutex::LockResultExt; use crate::service::environment_service::EnvironmentService; use crate::service::podcast_episode_service::PodcastEpisodeService; use crate::service::settings_service::SettingsService; -use crate::DbPool; use actix_web::web::{Data, Path, ReqData}; use actix_web::{get, put}; use actix_web::{web, HttpResponse}; use chrono::Local; -use std::ops::DerefMut; use std::str::FromStr; use std::sync::Mutex; use xml_builder::{XMLBuilder, XMLElement, XMLVersion}; @@ -24,13 +22,12 @@ tag="podcast_episodes" )] #[get("/settings")] pub async fn get_settings( - conn: Data, requester: Option>, ) -> Result { if !requester.unwrap().is_admin() { return Err(CustomError::Forbidden); } - let settings = Setting::get_settings(conn.get().map_err(map_r2d2_error)?.deref_mut())?; + let settings = Setting::get_settings()?; match settings { Some(settings) => Ok(HttpResponse::Ok().json(settings)), None => Err(CustomError::NotFound), @@ -49,7 +46,6 @@ pub async fn update_settings( settings_service: Data>, settings: web::Json, requester: Option>, - conn: Data, ) -> Result { if !requester.unwrap().is_admin() { return Err(CustomError::Forbidden); @@ -58,7 +54,6 @@ pub async fn update_settings( let mut settings_service = settings_service.lock().ignore_poison(); let settings = settings_service.update_settings( settings.into_inner(), - conn.get().map_err(map_r2d2_error)?.deref_mut(), )?; Ok(HttpResponse::Ok().json(settings)) } @@ -72,7 +67,6 @@ tag="settings" #[put("/settings/runcleanup")] pub async fn run_cleanup( settings_service: Data>, - conn: Data, requester: Option>, ) -> Result { if !requester.unwrap().is_admin() { @@ -81,12 +75,11 @@ pub async fn run_cleanup( let settings = settings_service .lock() .ignore_poison() - .get_settings(conn.get().map_err(map_r2d2_error)?.deref_mut())?; + .get_settings()?; match settings { Some(settings) => { PodcastEpisodeService::cleanup_old_episodes( settings.auto_cleanup_days, - conn.get().map_err(map_r2d2_error)?.deref_mut(), ); Ok(HttpResponse::Ok().finish()) } @@ -112,12 +105,11 @@ tag="podcasts" )] #[get("/settings/opml/{type_of}")] pub async fn get_opml( - conn: Data, requester: Option>, type_of: Path, ) -> Result { let podcasts_found = - Podcast::get_all_podcasts(conn.get().map_err(map_r2d2_error)?.deref_mut())?; + Podcast::get_all_podcasts()?; let mut xml = XMLBuilder::new() .version(XMLVersion::XML1_1) @@ -209,7 +201,6 @@ pub async fn update_name( settings_service: Data>, update_information: web::Json, requester: Option>, - conn: Data, ) -> Result { if !requester.unwrap().is_admin() { return Err(CustomError::Forbidden); @@ -219,13 +210,12 @@ pub async fn update_name( let settings = settings_service.update_name( update_information.into_inner(), - conn.get().map_err(map_r2d2_error)?.deref_mut(), )?; Ok(HttpResponse::Ok().json(settings)) } use crate::constants::inner_constants::ENVIRONMENT_SERVICE; -use crate::utils::error::{map_r2d2_error, CustomError}; +use crate::utils::error::CustomError; use utoipa::ToSchema; #[derive(Deserialize, Clone, ToSchema)] diff --git a/src/controllers/sys_info_controller.rs b/src/controllers/sys_info_controller.rs index 4636f4fa..b7f26ac3 100644 --- a/src/controllers/sys_info_controller.rs +++ b/src/controllers/sys_info_controller.rs @@ -1,7 +1,5 @@ use crate::models::user::User; -use crate::DbPool; -use actix_web::web::Data; use actix_web::{get, post}; use actix_web::{web, HttpResponse, Responder}; use fs_extra::dir::get_size; @@ -152,7 +150,6 @@ tag="sys" #[post("/login")] pub async fn login( auth: web::Json, - db: Data, ) -> Result { use crate::ENVIRONMENT_SERVICE; let env_service = ENVIRONMENT_SERVICE.get().unwrap(); @@ -167,7 +164,7 @@ pub async fn login( } } } - let db_user = User::find_by_username(&auth.0.username, &mut db.get().unwrap())?; + let db_user = User::find_by_username(&auth.0.username)?; if db_user.password.is_none() { log::warn!("Login failed for user {}", auth.0.username); diff --git a/src/controllers/tags_controller.rs b/src/controllers/tags_controller.rs index f7caa68f..7b7af98e 100644 --- a/src/controllers/tags_controller.rs +++ b/src/controllers/tags_controller.rs @@ -1,7 +1,6 @@ use actix_web::{delete, get, HttpResponse, post, put, web}; -use actix_web::web::{Data, Json}; +use actix_web::web::Json; use utoipa::ToSchema; -use crate::DbPool; use crate::models::color::Color; use crate::models::podcast_dto::PodcastDto; use crate::models::tag::Tag; @@ -30,11 +29,11 @@ body = TagCreate)), tag="tags" )] #[post("/tags")] -pub async fn insert_tag(tag_create: Json, conn: Data, requester: Option>) -> +pub async fn insert_tag(tag_create: Json, requester: Option>) -> Result { let new_tag = Tag::new(tag_create.name.clone(), tag_create.description.clone(), tag_create.color.to_string(), requester.unwrap().username.clone()); new_tag - .insert_tag(&mut conn.get().unwrap()) + .insert_tag() .map(|tag| HttpResponse::Ok().json(tag)) } @@ -45,9 +44,9 @@ responses( tag="tags" )] #[get("/tags")] -pub async fn get_tags(conn: Data, requester: Option>) -> +pub async fn get_tags(requester: Option>) -> Result { - let tags = Tag::get_tags(&mut conn.get().unwrap(), requester.unwrap().username.clone())?; + let tags = Tag::get_tags(requester.unwrap().username.clone())?; Ok(HttpResponse::Ok().json(tags)) } @@ -59,13 +58,13 @@ responses( tag="tags" )] #[delete("/tags/{tag_id}")] -pub async fn delete_tag(tag_id: web::Path, conn: Data, requester: Option>) -> +pub async fn delete_tag(tag_id: web::Path, requester: Option>) -> Result { - let opt_tag = Tag::get_tag_by_id_and_username(&mut conn.get().unwrap(), &tag_id.into_inner(), &requester.unwrap().username.clone())?; + let opt_tag = Tag::get_tag_by_id_and_username(&tag_id.into_inner(), &requester.unwrap().username.clone())?; match opt_tag{ Some(tag) => { - TagsPodcast::delete_tag_podcasts(&mut conn.get().unwrap(), &tag.id)?; - Tag::delete_tag(&mut conn.get().unwrap(), &tag.id)?; + TagsPodcast::delete_tag_podcasts(&tag.id)?; + Tag::delete_tag(&tag.id)?; Ok(HttpResponse::Ok().finish()) }, None=>Err(CustomError::NotFound) @@ -79,12 +78,12 @@ responses( tag="tags" )] #[put("/tags/{tag_id}")] -pub async fn update_tag(tag_id: web::Path, tag_create: Json, conn: Data, requester: Option>) -> +pub async fn update_tag(tag_id: web::Path, tag_create: Json, requester: Option>) -> Result { - let opt_tag = Tag::get_tag_by_id_and_username(&mut conn.get().unwrap(), &tag_id.into_inner(), &requester.unwrap().username.clone())?; + let opt_tag = Tag::get_tag_by_id_and_username(&tag_id.into_inner(), &requester.unwrap().username.clone())?; match opt_tag { Some(tag) => { - let updated_tag = Tag::update_tag(&mut conn.get().unwrap(), &tag.id, tag_create.name.clone(), + let updated_tag = Tag::update_tag(&tag.id, tag_create.name.clone(), tag_create.description.clone(), tag_create.color.to_string())?; Ok(HttpResponse::Ok().json(updated_tag)) }, @@ -99,16 +98,14 @@ responses( tag="tags" )] #[post("/tags/{tag_id}/{podcast_id}")] -pub async fn add_podcast_to_tag(tag_id: web::Path<(String, i32)>, conn: -Data, requester: Option>) -> +pub async fn add_podcast_to_tag(tag_id: web::Path<(String, i32)>, requester: Option>) -> Result { let (tag_id, podcast_id) = tag_id.into_inner(); - let opt_tag = Tag::get_tag_by_id_and_username( &mut conn.get().unwrap(), &tag_id, + let opt_tag = Tag::get_tag_by_id_and_username(&tag_id, &requester.unwrap().username.clone())?; match opt_tag{ Some(tag) => { - let podcast = TagsPodcast::add_podcast_to_tag(tag.id.clone(), podcast_id, - &mut conn.get().unwrap())?; + let podcast = TagsPodcast::add_podcast_to_tag(tag.id.clone(), podcast_id, )?; Ok(HttpResponse::Ok().json(podcast)) }, None=>Err(CustomError::NotFound) @@ -122,15 +119,14 @@ responses( tag="tags" )] #[delete("/tags/{tag_id}/{podcast_id}")] -pub async fn delete_podcast_from_tag(tag_id: web::Path<(String, i32)>, conn: -Data, requester: Option>) -> Result { +pub async fn delete_podcast_from_tag(tag_id: web::Path<(String, i32)>, requester: Option>) -> Result { let (tag_id, podcast_id) = tag_id.into_inner(); - let opt_tag = Tag::get_tag_by_id_and_username( &mut conn.get().unwrap(), &tag_id, + let opt_tag = Tag::get_tag_by_id_and_username(&tag_id, &requester.unwrap().username.clone())?; match opt_tag{ Some(tag) => { - TagsPodcast::delete_tag_podcasts_by_podcast_id_tag_id(&mut conn.get().unwrap(), podcast_id, + TagsPodcast::delete_tag_podcasts_by_podcast_id_tag_id(podcast_id, &tag.id)?; Ok(HttpResponse::Ok().finish()) }, diff --git a/src/controllers/user_controller.rs b/src/controllers/user_controller.rs index f01ad1ef..e79b28b8 100644 --- a/src/controllers/user_controller.rs +++ b/src/controllers/user_controller.rs @@ -2,11 +2,9 @@ use crate::constants::inner_constants::{Role, ENVIRONMENT_SERVICE}; use crate::models::user::User; use crate::service::user_management_service::UserManagementService; -use crate::utils::error::{map_r2d2_error, CustomError}; -use crate::DbPool; -use actix_web::web::{Data, Json, Path}; +use crate::utils::error::CustomError; +use actix_web::web::{Json, Path}; use actix_web::{delete, get, post, put, web, HttpResponse, Responder}; -use std::ops::DerefMut; use utoipa::ToSchema; @@ -50,7 +48,6 @@ tag="info" #[post("/users/")] pub async fn onboard_user( user_onboarding: web::Json, - conn: Data, ) -> Result { let user_to_onboard = user_onboarding.into_inner(); @@ -58,7 +55,6 @@ pub async fn onboard_user( user_to_onboard.username, user_to_onboard.password, user_to_onboard.invite_id, - conn.get().map_err(map_r2d2_error)?.deref_mut(), )?; Ok(HttpResponse::Ok().json(User::map_to_dto(res))) @@ -72,12 +68,10 @@ tag="info" )] #[get("")] pub async fn get_users( - conn: Data, requester: Option>, ) -> Result { let res = UserManagementService::get_users( requester.unwrap().into_inner(), - conn.get().map_err(map_r2d2_error)?.deref_mut(), )?; Ok(HttpResponse::Ok().json(res)) @@ -91,7 +85,6 @@ tag="info" )] #[get("/{username}")] pub async fn get_user( - conn: Data, username: Path, requester: Option>, ) -> Result { @@ -107,7 +100,6 @@ pub async fn get_user( let user = User::find_by_username( &username.clone(), - conn.get().map_err(map_r2d2_error)?.deref_mut(), )?; Ok(HttpResponse::Ok().json(User::map_to_api_dto(user))) } @@ -122,7 +114,6 @@ tag="info" #[put("/{username}/role")] pub async fn update_role( role: web::Json, - conn: Data, username: web::Path, requester: Option>, ) -> Result { @@ -130,7 +121,7 @@ pub async fn update_role( return Err(CustomError::Forbidden); } let mut user_to_update = - User::find_by_username(&username, conn.get().map_err(map_r2d2_error)?.deref_mut())?; + User::find_by_username(&username)?; // Update to his/her designated role user_to_update.role = role.role.to_string(); @@ -138,7 +129,6 @@ pub async fn update_role( let res = UserManagementService::update_user( user_to_update, - conn.get().map_err(map_r2d2_error)?.deref_mut(), )?; Ok(HttpResponse::Ok().json(res)) @@ -148,7 +138,6 @@ pub async fn update_role( pub async fn update_user( user: Option>, username: Path, - conn: Data, user_update: Json, ) -> Result { let username = username.into_inner(); @@ -160,7 +149,7 @@ pub async fn update_user( return Err(CustomError::Forbidden); } let mut user = - User::find_by_username(&username, conn.get().map_err(map_r2d2_error)?.deref_mut())?; + User::find_by_username(&username)?; if let Some(admin_username) = ENVIRONMENT_SERVICE.get().unwrap().username.clone() { if admin_username == user.username { @@ -175,7 +164,6 @@ pub async fn update_user( // Check if this username is already taken let new_username_res = User::find_by_username( &user_update.username, - conn.get().map_err(map_r2d2_error)?.deref_mut(), ); if new_username_res.is_ok() { return Err(CustomError::Conflict("Username already taken".to_string())); @@ -195,7 +183,7 @@ pub async fn update_user( user.api_key = Some(api_key); } - let user = User::update_user(user, conn.get().map_err(map_r2d2_error)?.deref_mut())?; + let user = User::update_user(user)?; Ok(HttpResponse::Ok().json(User::map_to_api_dto(user))) } @@ -211,7 +199,6 @@ tag="info" #[post("/invites")] pub async fn create_invite( invite: web::Json, - conn: Data, requester: Option>, ) -> impl Responder { let invite = invite.into_inner(); @@ -219,7 +206,6 @@ pub async fn create_invite( let created_invite = UserManagementService::create_invite( invite.role, invite.explicit_consent, - conn.get().map_err(map_r2d2_error).unwrap().deref_mut(), requester.unwrap().into_inner(), ) .expect("Error creating invite"); @@ -234,7 +220,6 @@ tag="info" )] #[get("/invites")] pub async fn get_invites( - conn: Data, requester: Option>, ) -> Result { if !requester.unwrap().is_admin() { @@ -242,7 +227,7 @@ pub async fn get_invites( } let invites = - UserManagementService::get_invites(conn.get().map_err(map_r2d2_error)?.deref_mut())?; + UserManagementService::get_invites()?; Ok(HttpResponse::Ok().json(invites)) } @@ -255,12 +240,10 @@ tag="info" )] #[get("/users/invites/{invite_id}")] pub async fn get_invite( - conn: Data, invite_id: web::Path, ) -> Result { match UserManagementService::get_invite( invite_id.into_inner(), - conn.get().map_err(map_r2d2_error)?.deref_mut(), ) { Ok(invite) => Ok(HttpResponse::Ok().json(invite)), Err(e) => Ok(HttpResponse::BadRequest().body(e.to_string())), @@ -275,7 +258,6 @@ tag="info" )] #[delete("/{username}")] pub async fn delete_user( - conn: Data, username: Path, requester: Option>, ) -> Result { @@ -284,10 +266,9 @@ pub async fn delete_user( } let user_to_delete = - User::find_by_username(&username, conn.get().map_err(map_r2d2_error)?.deref_mut()).unwrap(); + User::find_by_username(&username).unwrap(); match UserManagementService::delete_user( user_to_delete, - conn.get().map_err(map_r2d2_error)?.deref_mut(), ) { Ok(_) => Ok(HttpResponse::Ok().into()), Err(e) => Err(e), @@ -301,7 +282,6 @@ responses( (status = 200, description = "Gets an invite by id", body = Option)))] #[get("/invites/{invite_id}/link")] pub async fn get_invite_link( - conn: Data, invite_id: Path, requester: Option>, ) -> impl Responder { @@ -312,7 +292,6 @@ pub async fn get_invite_link( match UserManagementService::get_invite_link( invite_id.into_inner(), ENVIRONMENT_SERVICE.get().unwrap(), - conn.get().map_err(map_r2d2_error).unwrap().deref_mut(), ) { Ok(invite) => HttpResponse::Ok().json(invite), Err(e) => HttpResponse::BadRequest().body(e.to_string()), @@ -326,7 +305,6 @@ responses( (status = 200, description = "Deletes an invite by id")))] #[delete("/invites/{invite_id}")] pub async fn delete_invite( - conn: Data, invite_id: web::Path, requester: Option>, ) -> impl Responder { @@ -336,7 +314,6 @@ pub async fn delete_invite( match UserManagementService::delete_invite( invite_id.into_inner(), - conn.get().map_err(map_r2d2_error).unwrap().deref_mut(), ) { Ok(_) => HttpResponse::Ok().into(), Err(e) => HttpResponse::BadRequest().body(e.to_string()), diff --git a/src/controllers/watch_time_controller.rs b/src/controllers/watch_time_controller.rs index ae7fca24..9aab18ac 100644 --- a/src/controllers/watch_time_controller.rs +++ b/src/controllers/watch_time_controller.rs @@ -2,12 +2,9 @@ use crate::models::episode::Episode; use crate::models::misc_models::PodcastWatchedPostModel; use crate::models::user::User; -use crate::utils::error::{map_r2d2_error, CustomError}; -use crate::DbPool; -use actix_web::web::Data; +use crate::utils::error::CustomError; use actix_web::{get, post, web, HttpResponse}; -use std::ops::DerefMut; #[utoipa::path( context_path="/api/v1", @@ -18,12 +15,10 @@ tag="watchtime" #[post("/podcast/episode")] pub async fn log_watchtime( podcast_watch: web::Json, - conn: Data, requester: Option>, ) -> Result { let podcast_episode_id = podcast_watch.0.podcast_episode_id.clone(); Episode::log_watchtime( - conn.get().map_err(map_r2d2_error)?.deref_mut(), podcast_watch.0, requester.unwrap().username.clone(), )?; @@ -39,14 +34,12 @@ tag="watchtime" )] #[get("/podcast/episode/lastwatched")] pub async fn get_last_watched( - conn: Data, requester: Option>, ) -> Result { let designated_username = requester.unwrap().username.clone(); let mut episodes = Episode::get_last_watched_episodes( designated_username, - conn.get().map_err(map_r2d2_error)?.deref_mut(), )?; episodes.sort_by(|a, b| a.date.cmp(&b.date).reverse()); Ok(HttpResponse::Ok().json(episodes)) @@ -61,12 +54,10 @@ tag="watchtime" #[get("/podcast/episode/{id}")] pub async fn get_watchtime( id: web::Path, - conn: Data, requester: Option>, ) -> Result { let designated_username = requester.unwrap().username.clone(); let watchtime = Episode::get_watchtime( - conn.get().map_err(map_r2d2_error)?.deref_mut(), id.into_inner(), designated_username, )?; diff --git a/src/controllers/websocket_controller.rs b/src/controllers/websocket_controller.rs index 5c3e199a..9afb080c 100644 --- a/src/controllers/websocket_controller.rs +++ b/src/controllers/websocket_controller.rs @@ -1,15 +1,13 @@ use crate::controllers::web_socket::{chat_ws}; -use std::ops::DerefMut; use crate::models::podcast_episode::PodcastEpisode; use crate::models::podcasts::Podcast; use crate::service::environment_service::EnvironmentService; use crate::service::podcast_episode_service::PodcastEpisodeService; -use crate::utils::error::{map_r2d2_error, CustomError}; -use crate::DbPool; +use crate::utils::error::CustomError; use actix_web::web::Query; -use actix_web::{get, web, web::Data, Error, HttpRequest, HttpResponse}; +use actix_web::{get, web, Error, HttpRequest, HttpResponse}; use rss::extension::itunes::{ ITunesCategory, ITunesCategoryBuilder, ITunesChannelExtension, ITunesChannelExtensionBuilder, ITunesItemExtensionBuilder, ITunesOwner, ITunesOwnerBuilder, @@ -64,7 +62,6 @@ responses( , tag = "info")] #[get("/rss")] pub async fn get_rss_feed( - db: Data, query: Option>, api_key: Option>, ) -> Result { @@ -78,7 +75,7 @@ pub async fn get_rss_feed( } let api_key = api_key.as_ref().unwrap().api_key.to_string(); - let api_key_exists = User::check_if_api_key_exists(api_key, db.get().unwrap().deref_mut()); + let api_key_exists = User::check_if_api_key_exists(api_key); if !&api_key_exists { return Ok(HttpResponse::Unauthorized().body("Unauthorized")); @@ -87,11 +84,9 @@ pub async fn get_rss_feed( let downloaded_episodes = match query { Some(q) => PodcastEpisodeService::find_all_downloaded_podcast_episodes_with_top_k( - &mut db.get().unwrap(), q.top, )?, None => PodcastEpisodeService::find_all_downloaded_podcast_episodes( - &mut db.get().unwrap(), env, )?, }; @@ -168,7 +163,6 @@ responses( #[get("/rss/{id}")] pub async fn get_rss_feed_for_podcast( id: web::Path, - conn: Data, api_key: Option>, ) -> Result { let env = ENVIRONMENT_SERVICE.get().unwrap(); @@ -182,19 +176,18 @@ pub async fn get_rss_feed_for_podcast( let api_key = api_key.as_ref().unwrap().api_key.to_string(); let api_key_exists = - User::check_if_api_key_exists(api_key, conn.get().unwrap().deref_mut()); + User::check_if_api_key_exists(api_key); if !api_key_exists { return Ok(HttpResponse::Unauthorized().body("Unauthorized")); } } - let podcast = Podcast::get_podcast(conn.get().map_err(map_r2d2_error)?.deref_mut(), *id)?; + let podcast = Podcast::get_podcast(*id)?; let downloaded_episodes = PodcastEpisodeService::find_all_downloaded_podcast_episodes_by_podcast_id( *id, - conn.get().map_err(map_r2d2_error)?.deref_mut(), )?; let mut itunes_owner = get_itunes_owner("", ""); diff --git a/src/db.rs b/src/db.rs index faa89ec4..2d4a607d 100644 --- a/src/db.rs +++ b/src/db.rs @@ -1,5 +1,4 @@ use crate::controllers::podcast_episode_controller::TimelineQueryParams; -use crate::dbconfig::DBType; use crate::models::episode::Episode; use crate::models::favorites::Favorite; use crate::models::filter::Filter; @@ -9,6 +8,7 @@ use crate::utils::error::{map_db_error, CustomError}; use diesel::dsl::max; use diesel::prelude::*; use diesel::RunQueryDsl; +use crate::adapters::persistence::dbconfig::db::get_connection; #[derive(Deserialize, Serialize)] #[serde(rename_all = "camelCase")] @@ -20,27 +20,25 @@ pub struct TimelineItem { impl TimelineItem { pub fn get_timeline( username_to_search: String, - conn: &mut DBType, favored_only: TimelineQueryParams, ) -> Result { - use crate::dbconfig::schema::podcast_episodes::dsl::*; - use crate::dbconfig::schema::podcasts::dsl::*; - use crate::dbconfig::schema::podcasts::id as pid; + use crate::adapters::persistence::dbconfig::schema::podcast_episodes::dsl::*; + use crate::adapters::persistence::dbconfig::schema::podcasts::dsl::*; + use crate::adapters::persistence::dbconfig::schema::podcasts::id as pid; - use crate::dbconfig::schema::episodes as phi_struct; - use crate::dbconfig::schema::episodes::episode as ehid; - use crate::dbconfig::schema::episodes::guid as eguid; - use crate::dbconfig::schema::episodes::timestamp as phistory_date; - use crate::dbconfig::schema::episodes::username as phi_username; - use crate::dbconfig::schema::favorites::dsl::*; - use crate::dbconfig::schema::favorites::podcast_id as f_podcast_id; - use crate::dbconfig::schema::favorites::username as f_username; - use crate::dbconfig::schema::podcast_episodes::guid as pguid; - use crate::dbconfig::schema::podcast_episodes::podcast_id as e_podcast_id; + use crate::adapters::persistence::dbconfig::schema::episodes as phi_struct; + use crate::adapters::persistence::dbconfig::schema::episodes::episode as ehid; + use crate::adapters::persistence::dbconfig::schema::episodes::guid as eguid; + use crate::adapters::persistence::dbconfig::schema::episodes::timestamp as phistory_date; + use crate::adapters::persistence::dbconfig::schema::episodes::username as phi_username; + use crate::adapters::persistence::dbconfig::schema::favorites::dsl::*; + use crate::adapters::persistence::dbconfig::schema::favorites::podcast_id as f_podcast_id; + use crate::adapters::persistence::dbconfig::schema::favorites::username as f_username; + use crate::adapters::persistence::dbconfig::schema::podcast_episodes::guid as pguid; + use crate::adapters::persistence::dbconfig::schema::podcast_episodes::podcast_id as e_podcast_id; Filter::save_decision_for_timeline( username_to_search.clone(), - conn, favored_only.favored_only, ); @@ -95,9 +93,9 @@ impl TimelineItem { query = query.filter(ph1.field(phistory_date).nullable().ne_all(subquery.clone())); total_count = total_count.filter(ph1.field(phistory_date).nullable().ne_all(subquery)); } - let results = total_count.get_result::(conn).map_err(map_db_error)?; + let results = total_count.get_result::(&mut get_connection()).map_err(map_db_error)?; let result = query - .load::<(PodcastEpisode, Podcast, Option, Option)>(conn) + .load::<(PodcastEpisode, Podcast, Option, Option)>(&mut get_connection()) .map_err(map_db_error)?; Ok(TimelineItem { diff --git a/src/dbconfig/mod.rs b/src/dbconfig/mod.rs deleted file mode 100644 index 0ed48250..00000000 --- a/src/dbconfig/mod.rs +++ /dev/null @@ -1,39 +0,0 @@ -#[path = "schemas/sqlite/schema.rs"] -pub mod schema; -use diesel::QueryResult; - -#[derive(diesel::MultiConnection)] -pub enum DBType { - Postgresql(diesel::PgConnection), - Sqlite(diesel::SqliteConnection), -} - -#[macro_export] -macro_rules! import_database_config { - () => { - pub const SQLITE_MIGRATIONS: EmbeddedMigrations = embed_migrations!("./migrations/sqlite"); - - pub const POSTGRES_MIGRATIONS: EmbeddedMigrations = - embed_migrations!("./migrations/postgres"); - }; -} - -#[macro_export] -macro_rules! execute_with_conn { - ($conn:expr, $diesel_func:expr) => { - match $conn { - DbConnection::Sqlite(conn) => return $diesel_func(conn), - DbConnection::Postgresql(conn) => return $diesel_func(conn), - } - }; -} - -#[macro_export] -macro_rules! insert_with_conn { - ($conn:expr, $diesel_func:expr) => { - match $conn { - DbConnection::Sqlite(conn) => $diesel_func(conn), - DbConnection::Postgresql(conn) => $diesel_func(conn), - } - }; -} diff --git a/src/gpodder/auth/authentication.rs b/src/gpodder/auth/authentication.rs index 37b905af..e45d59b2 100644 --- a/src/gpodder/auth/authentication.rs +++ b/src/gpodder/auth/authentication.rs @@ -2,15 +2,11 @@ use crate::auth_middleware::AuthFilter; use crate::models::session::Session; use crate::models::user::User; -use crate::utils::error::{map_r2d2_error, CustomError}; -use crate::DbPool; +use crate::utils::error::CustomError; use actix_web::post; -use actix_web::web::Data; use actix_web::{web, HttpRequest, HttpResponse}; use awc::cookie::{Cookie, SameSite}; use sha256::digest; -use std::ops::DerefMut; - use crate::constants::inner_constants::ENVIRONMENT_SERVICE; use crate::service::environment_service::EnvironmentService; @@ -18,7 +14,6 @@ use crate::service::environment_service::EnvironmentService; pub async fn login( username: web::Path, rq: HttpRequest, - conn: Data, ) -> Result { let env = ENVIRONMENT_SERVICE.get().unwrap(); @@ -26,7 +21,7 @@ pub async fn login( if let Some(cookie) = rq.clone().cookie("sessionid") { let session = cookie.value(); let opt_session = - Session::find_by_session_id(session, conn.get().map_err(map_r2d2_error)?.deref_mut()); + Session::find_by_session_id(session); if let Ok(unwrapped_session) = opt_session { let user_cookie = create_session_cookie(unwrapped_session); return Ok(HttpResponse::Ok().cookie(user_cookie).finish()); @@ -34,15 +29,14 @@ pub async fn login( } match env.reverse_proxy { - true => handle_proxy_auth(rq, username.into_inner(), conn, env), - false => handle_gpodder_basic_auth(rq, username, conn, env), + true => handle_proxy_auth(rq, username.into_inner(), env), + false => handle_gpodder_basic_auth(rq, username, env), } } fn handle_proxy_auth( rq: HttpRequest, username: String, - conn: Data, env: &EnvironmentService, ) -> Result { let config = env.reverse_proxy_config.clone().unwrap(); @@ -59,13 +53,11 @@ fn handle_proxy_auth( match User::find_by_username( auth_val, - conn.get().map_err(map_r2d2_error)?.deref_mut(), ) { Ok(user) => { let session = Session::new(user.username); Session::insert_session( &session, - conn.get().map_err(map_r2d2_error)?.deref_mut(), )?; let user_cookie = create_session_cookie(session); Ok(HttpResponse::Ok().cookie(user_cookie).finish()) @@ -82,9 +74,8 @@ fn handle_proxy_auth( created_at: chrono::Utc::now().naive_utc(), api_key: None, }, - &mut conn.get().unwrap(), ).expect("Error inserting user on auto registering"); - handle_proxy_auth(rq, username.clone(), conn, env) + handle_proxy_auth(rq, username.clone(), env) } else { log::error!("Error finding user by username: {}", e); Err(CustomError::Forbidden) @@ -99,7 +90,6 @@ fn handle_proxy_auth( fn handle_gpodder_basic_auth( rq: HttpRequest, username: web::Path, - conn: Data, env: &EnvironmentService, ) -> Result { let opt_authorization = rq.headers().get("Authorization"); @@ -128,13 +118,12 @@ fn handle_gpodder_basic_auth( let user = User::find_by_username( &unwrapped_username, - conn.get().map_err(map_r2d2_error)?.deref_mut(), )?; match user.password { Some(p) => { if p == digest(password) { let session = Session::new(user.username); - Session::insert_session(&session, conn.get().map_err(map_r2d2_error)?.deref_mut()) + Session::insert_session(&session) .expect("Error inserting session"); let user_cookie = create_session_cookie(session); Ok(HttpResponse::Ok().cookie(user_cookie).finish()) diff --git a/src/gpodder/episodes/gpodder_episodes.rs b/src/gpodder/episodes/gpodder_episodes.rs index 94e1f1c8..bfd1256d 100644 --- a/src/gpodder/episodes/gpodder_episodes.rs +++ b/src/gpodder/episodes/gpodder_episodes.rs @@ -1,14 +1,11 @@ use actix_web::{web, HttpResponse}; -use std::ops::DerefMut; -use actix_web::web::Data; use actix_web::{get, post}; use crate::models::episode::{Episode, EpisodeDto}; use crate::models::session::Session; -use crate::utils::error::{map_r2d2_error, CustomError}; +use crate::utils::error::CustomError; use crate::utils::time::get_current_timestamp; -use crate::DbPool; use chrono::{DateTime}; #[derive(Serialize, Deserialize)] @@ -34,7 +31,6 @@ pub struct EpisodeSinceRequest { #[get("/episodes/{username}.json")] pub async fn get_episode_actions( username: web::Path, - pool: Data, opt_flag: Option>, since: web::Query, ) -> Result { @@ -49,7 +45,6 @@ pub async fn get_episode_actions( .map(|v| v.naive_utc()); let mut actions = Episode::get_actions_by_username( username.clone(), - &mut pool.get().unwrap(), since_date, since.device.clone(), since.aggregate.clone(), @@ -79,7 +74,6 @@ pub async fn upload_episode_actions( username: web::Path, podcast_episode: web::Json>, opt_flag: Option>, - conn: Data, ) -> Result { match opt_flag { Some(flag) => { @@ -92,7 +86,6 @@ pub async fn upload_episode_actions( inserted_episodes.push( Episode::insert_episode( &episode.clone(), - conn.get().map_err(map_r2d2_error).unwrap().deref_mut(), ) .unwrap(), ); diff --git a/src/gpodder/session_middleware.rs b/src/gpodder/session_middleware.rs index 31f8244c..9b3003f2 100644 --- a/src/gpodder/session_middleware.rs +++ b/src/gpodder/session_middleware.rs @@ -1,4 +1,3 @@ -use crate::config::dbconfig::establish_connection; use crate::models::session::Session; use actix::fut::ok; use actix_web::body::{EitherBody, MessageBody}; @@ -12,6 +11,7 @@ use diesel::{OptionalExtension, QueryDsl, RunQueryDsl}; use futures_util::future::{LocalBoxFuture, Ready}; use futures_util::FutureExt; use std::rc::Rc; +use crate::adapters::persistence::dbconfig::db::get_connection; pub struct CookieFilter {} @@ -66,10 +66,10 @@ where let binding = cookie.unwrap(); let extracted_cookie = binding.value(); - use crate::dbconfig::schema::sessions::dsl::*; + use crate::adapters::persistence::dbconfig::schema::sessions::dsl::*; let session = sessions .filter(session_id.eq(extracted_cookie)) - .first::(&mut establish_connection()) + .first::(&mut get_connection()) .optional() .expect("Error connecting to database"); if session.is_none() { diff --git a/src/gpodder/subscription/subscriptions.rs b/src/gpodder/subscription/subscriptions.rs index 54473228..fcd5d738 100644 --- a/src/gpodder/subscription/subscriptions.rs +++ b/src/gpodder/subscription/subscriptions.rs @@ -1,12 +1,9 @@ use crate::models::session::Session; use crate::models::subscription::SubscriptionChangesToClient; -use crate::utils::error::{map_r2d2_error, CustomError}; +use crate::utils::error::CustomError; use crate::utils::time::get_current_timestamp; -use crate::DbPool; -use actix_web::web::Data; use actix_web::{get, post}; use actix_web::{web, HttpResponse}; -use std::ops::DerefMut; #[derive(Deserialize, Serialize)] pub struct SubscriptionRetrieveRequest { @@ -30,7 +27,6 @@ pub async fn get_subscriptions( paths: web::Path<(String, String)>, opt_flag: Option>, query: web::Query, - conn: Data, ) -> Result { match opt_flag { Some(flag) => { @@ -44,7 +40,6 @@ pub async fn get_subscriptions( &deviceid, &username, query.since, - conn.get().map_err(map_r2d2_error)?.deref_mut(), ) .await; @@ -66,7 +61,6 @@ pub async fn upload_subscription_changes( upload_request: web::Json, opt_flag: Option>, paths: web::Path<(String, String)>, - conn: Data, ) -> Result { match opt_flag { Some(flag) => { @@ -79,7 +73,6 @@ pub async fn upload_subscription_changes( &deviceid, &username, upload_request, - conn.get().map_err(map_r2d2_error)?.deref_mut(), ) .await .unwrap(); diff --git a/src/main.rs b/src/main.rs index 37bf9d86..390dcfc9 100644 --- a/src/main.rs +++ b/src/main.rs @@ -17,7 +17,7 @@ use std::io::Read; use std::sync::Mutex; use std::time::Duration; use std::{env, thread}; - +use std::ops::DerefMut; use actix_web::body::{BoxBody, EitherBody}; use diesel::r2d2::ConnectionManager; use jsonwebtoken::jwk::{ @@ -32,8 +32,6 @@ use tokio::{spawn, try_join}; mod controllers; use crate::auth_middleware::AuthFilter; use crate::command_line_runner::start_command_line; -use crate::config::dbconfig::establish_connection; -use crate::config::dbconfig::ConnectionOptions; use crate::constants::inner_constants::{CSS, ENVIRONMENT_SERVICE, JS}; use crate::controllers::notification_controller::{ dismiss_notifications, get_unread_notifications, @@ -57,9 +55,10 @@ use crate::controllers::user_controller::{ get_users, onboard_user, update_role, update_user, }; use crate::controllers::watch_time_controller::{get_last_watched, get_watchtime, log_watchtime}; -use crate::dbconfig::DBType; pub use controllers::controller_utils::*; use crate::adapters::api::controllers::routes::{get_gpodder_api, global_routes}; +use crate::adapters::persistence::dbconfig::db::get_connection; +use crate::adapters::persistence::dbconfig::DBType; use crate::controllers::server::ChatServer; use crate::controllers::tags_controller::{add_podcast_to_tag, delete_podcast_from_tag, delete_tag, get_tags, insert_tag, update_tag}; @@ -88,7 +87,6 @@ mod config; mod auth_middleware; mod command_line_runner; -mod dbconfig; mod exception; mod gpodder; pub mod mutex; @@ -103,16 +101,14 @@ import_database_config!(); pub fn run_poll(mut podcast_service: PodcastService) -> Result<(), CustomError> { //check for new episodes - let conn = &mut establish_connection(); - let podcats_result = Podcast::get_all_podcasts(conn)?; + let podcats_result = Podcast::get_all_podcasts()?; for podcast in podcats_result { if podcast.active { let podcast_clone = podcast.clone(); - PodcastEpisodeService::insert_podcast_episodes(conn, podcast)?; + PodcastEpisodeService::insert_podcast_episodes(podcast)?; podcast_service.schedule_episode_download( podcast_clone, None, - &mut establish_connection(), )?; } } @@ -133,6 +129,7 @@ async fn index() -> impl Responder { .body(fix_links(index_html)) } + #[actix_web::main] async fn main() -> std::io::Result<()> { let env_service = EnvironmentService::new(); @@ -149,17 +146,18 @@ async fn main() -> std::io::Result<()> { exit(0) } - let conn = establish_connection(); + let mut conn = get_connection(); + let conn = conn.deref_mut(); match conn { - DBType::Postgresql(mut conn) => { + DBType::Postgresql(ref mut conn) => { let res_migration = conn.run_pending_migrations(POSTGRES_MIGRATIONS); if res_migration.is_err() { panic!("Could not run migrations: {}", res_migration.err().unwrap()); } } - DBType::Sqlite(mut conn) => { + DBType::Sqlite(ref mut conn) => { let res_migration = conn.run_pending_migrations(SQLITE_MIGRATIONS); if res_migration.is_err() { @@ -169,23 +167,6 @@ async fn main() -> std::io::Result<()> { } check_server_config(); - let pool; - { - let conn = establish_connection(); - match conn { - DBType::Postgresql(_) => { - pool = init_postgres_db_pool(&ENVIRONMENT_SERVICE.get().unwrap().database_url) - .await - .expect("Failed to connect to database"); - } - DBType::Sqlite(_) => { - pool = init_sqlite_db_pool(&ENVIRONMENT_SERVICE.get().unwrap().database_url) - .await - .expect("Failed to connect to database"); - } - } - } - let data_pool = Data::new(pool); //services let podcast_service = PodcastService::new(); @@ -214,8 +195,7 @@ async fn main() -> std::io::Result<()> { ENVIRONMENT_SERVICE.get().unwrap().get_environment(); let polling_interval = ENVIRONMENT_SERVICE.get().unwrap().get_polling_interval(); scheduler.every(polling_interval.minutes()).run(|| { - let conn = &mut establish_connection(); - let settings = Setting::get_settings(conn).unwrap(); + let settings = Setting::get_settings().unwrap(); match settings { Some(settings) => { if settings.auto_update { @@ -239,18 +219,17 @@ async fn main() -> std::io::Result<()> { scheduler.every(1.day()).run(move || { // Clears the session ids once per day - let conn = &mut establish_connection(); + let conn = &mut get_connection(); Session::cleanup_sessions(conn).expect( "Error clearing old \ sessions", ); - let settings = Setting::get_settings(conn).unwrap(); + let settings = Setting::get_settings().unwrap(); match settings { Some(settings) => { if settings.auto_cleanup { PodcastEpisodeService::cleanup_old_episodes( settings.auto_cleanup_days, - &mut establish_connection(), ) } } @@ -349,7 +328,6 @@ async fn main() -> std::io::Result<()> { .app_data(Data::new(Mutex::new(file_service.clone()))) .app_data(Data::new(Mutex::new(notification_service.clone()))) .app_data(Data::new(Mutex::new(settings_service.clone()))) - .app_data(data_pool.clone()) .wrap(Condition::new(cfg!(debug_assertions), Logger::default())) }) .workers(4) @@ -500,8 +478,7 @@ pub fn get_secure_user_management() -> Scope { } pub fn insert_default_settings_if_not_present() -> Result<(), CustomError> { - let conn = &mut establish_connection(); - let settings = Setting::get_settings(conn)?; + let settings = Setting::get_settings()?; match settings { Some(_) => { info!("Settings already present"); @@ -509,7 +486,7 @@ pub fn insert_default_settings_if_not_present() -> Result<(), CustomError> { } None => { info!("No settings found, inserting default settings"); - Setting::insert_default_settings(conn)?; + Setting::insert_default_settings()?; Ok(()) } } @@ -550,31 +527,4 @@ fn check_if_multiple_auth_is_configured(env: &EnvironmentService) -> bool { num_of_auth_count > 1 } -async fn init_postgres_db_pool( - database_url: &str, -) -> Result>, String> { - let env_service = ENVIRONMENT_SERVICE.get().unwrap(); - let db_connections = env_service.conn_number; - let manager = ConnectionManager::::new(database_url); - let pool = Pool::builder() - .max_size(db_connections as u32) - .build(manager) - .expect("Failed to create pool."); - Ok(pool) -} -async fn init_sqlite_db_pool( - database_url: &str, -) -> Result>, String> { - let manager = ConnectionManager::::new(database_url); - let pool = Pool::builder() - .max_size(16) - .connection_customizer(Box::new(ConnectionOptions { - enable_wal: true, - enable_foreign_keys: true, - busy_timeout: Some(Duration::from_secs(120)), - })) - .build(manager) - .unwrap(); - Ok(pool) -} diff --git a/src/models/episode.rs b/src/models/episode.rs index df7130a1..d34e9c8f 100644 --- a/src/models/episode.rs +++ b/src/models/episode.rs @@ -1,6 +1,6 @@ use crate::constants::inner_constants::DEFAULT_DEVICE; -use crate::dbconfig::schema::episodes; -use crate::dbconfig::schema::episodes::dsl::episodes as episodes_dsl; +use crate::adapters::persistence::dbconfig::schema::episodes; +use crate::adapters::persistence::dbconfig::schema::episodes::dsl::episodes as episodes_dsl; use crate::DBType as DbConnection; use chrono::{NaiveDateTime, Utc}; use diesel::sql_types::{Integer, Nullable, Text, Timestamp}; @@ -15,6 +15,7 @@ use std::fmt; use std::io::Error; use diesel::query_dsl::methods::DistinctDsl; use utoipa::ToSchema; +use crate::adapters::persistence::dbconfig::db::get_connection; use crate::models::gpodder_available_podcasts::GPodderAvailablePodcasts; use crate::models::misc_models::{ PodcastWatchedEpisodeModelWithPodcastEpisode, PodcastWatchedPostModel, @@ -63,9 +64,8 @@ pub struct Episode { impl Episode { pub fn insert_episode( &self, - conn: &mut DbConnection, ) -> Result { - use crate::dbconfig::schema::episodes::dsl::*; + use crate::adapters::persistence::dbconfig::schema::episodes::dsl::*; let res = episodes .filter( @@ -76,7 +76,7 @@ impl Episode { .and(episode.eq(&self.clone().episode)) .and(timestamp.eq(self.clone().timestamp)), ) - .first::(conn) + .first::(&mut get_connection()) .optional() .expect(""); @@ -99,7 +99,7 @@ impl Episode { position.eq(&self.position), total.eq(&self.total), )) - .get_result(conn) + .get_result(&mut get_connection()) } pub fn convert_to_episode_dto(&self) -> EpisodeDto { @@ -137,16 +137,15 @@ impl Episode { } pub async fn get_actions_by_username( username1: String, - conn: &mut DbConnection, since_date: Option, opt_device: Option, _opt_aggregate: Option, opt_podcast: Option, ) -> Vec { - use crate::dbconfig::schema::episodes::dsl as ep_dsl; - use crate::dbconfig::schema::episodes::dsl::timestamp; - use crate::dbconfig::schema::episodes::table as ep_table; - use crate::dbconfig::schema::episodes::username; + use crate::adapters::persistence::dbconfig::schema::episodes::dsl as ep_dsl; + use crate::adapters::persistence::dbconfig::schema::episodes::dsl::timestamp; + use crate::adapters::persistence::dbconfig::schema::episodes::table as ep_table; + use crate::adapters::persistence::dbconfig::schema::episodes::username; let mut query = ep_table.filter(username.eq(username1)).into_boxed(); @@ -172,7 +171,7 @@ impl Episode { query - .load::(conn) + .load::(&mut get_connection()) .expect("Error querying episodes") } @@ -181,9 +180,9 @@ impl Episode { conn: &mut DbConnection, episode_1: String, ) -> Result, CustomError> { - use crate::dbconfig::schema::episodes::dsl::*; - use crate::dbconfig::schema::podcasts::dsl::*; - use crate::dbconfig::schema::podcasts::table as podcast_episode_table; + use crate::adapters::persistence::dbconfig::schema::episodes::dsl::*; + use crate::adapters::persistence::dbconfig::schema::podcasts::dsl::*; + use crate::adapters::persistence::dbconfig::schema::podcasts::table as podcast_episode_table; use diesel::JoinOnDsl; use diesel::Table; @@ -200,14 +199,13 @@ impl Episode { pub fn get_last_watched_episodes( username_to_find: String, - conn: &mut DbConnection, ) -> Result, CustomError> { - use crate::dbconfig::schema::episodes::dsl as ep_dsl; - use crate::dbconfig::schema::episodes::dsl::guid as eguid; - use crate::dbconfig::schema::episodes::username as e_username; - use crate::dbconfig::schema::podcast_episodes::dsl::guid as pguid; - use crate::dbconfig::schema::podcast_episodes::dsl::*; - use crate::dbconfig::schema::podcasts as podcast_table; + use crate::adapters::persistence::dbconfig::schema::episodes::dsl as ep_dsl; + use crate::adapters::persistence::dbconfig::schema::episodes::dsl::guid as eguid; + use crate::adapters::persistence::dbconfig::schema::episodes::username as e_username; + use crate::adapters::persistence::dbconfig::schema::podcast_episodes::dsl::guid as pguid; + use crate::adapters::persistence::dbconfig::schema::podcast_episodes::dsl::*; + use crate::adapters::persistence::dbconfig::schema::podcasts as podcast_table; use diesel::JoinOnDsl; let (episodes1, episodes2) = diesel::alias!(episodes as p1, episodes as p2); @@ -238,7 +236,7 @@ impl Episode { .eq_any(subquery), ) .filter(episodes1.field(ep_dsl::action).eq("play")) - .load::<(PodcastEpisode, Episode, Podcast)>(conn) + .load::<(PodcastEpisode, Episode, Podcast)>(&mut get_connection()) .map_err(map_db_error)?; let mapped_watched_episodes = query @@ -264,8 +262,8 @@ impl Episode { username1: &str, conn: &mut DbConnection, ) -> Result<(), Error> { - use crate::dbconfig::schema::episodes::dsl::episodes; - use crate::dbconfig::schema::episodes::username; + use crate::adapters::persistence::dbconfig::schema::episodes::dsl::episodes; + use crate::adapters::persistence::dbconfig::schema::episodes::username; diesel::delete(episodes.filter(username.eq(username1))) .execute(conn) .expect(""); @@ -273,63 +271,62 @@ impl Episode { } - pub fn find_episodes_not_in_webview(conn: &mut DbConnection) -> Result, CustomError> { - use crate::dbconfig::schema::episodes::dsl::episodes; - use crate::dbconfig::schema::episodes::device; - use crate::dbconfig::schema::episodes::podcast; - use crate::dbconfig::schema::podcasts::dsl::podcasts; - use crate::dbconfig::schema::podcasts::dsl::rssfeed; + pub fn find_episodes_not_in_webview() -> Result, CustomError> { + use crate::adapters::persistence::dbconfig::schema::episodes::dsl::episodes; + use crate::adapters::persistence::dbconfig::schema::episodes::device; + use crate::adapters::persistence::dbconfig::schema::episodes::podcast; + use crate::adapters::persistence::dbconfig::schema::podcasts::dsl::podcasts; + use crate::adapters::persistence::dbconfig::schema::podcasts::dsl::rssfeed; let result = DistinctDsl::distinct(episodes .left_join(podcasts.on(podcast.eq(rssfeed))) .select((device, podcast)) .filter(rssfeed.is_null())) .filter(device.ne("webview")) - .load::(conn) + .load::(&mut get_connection()) .map_err(map_db_error)?; Ok(result) } - pub fn delete_watchtime(conn: &mut DbConnection, podcast_id: i32) -> Result<(), CustomError> { - use crate::dbconfig::schema::episodes::dsl as ep_dsl; - use crate::dbconfig::schema::episodes::table as ep_table; - use crate::dbconfig::schema::podcasts::dsl as podcast_dsl; - use crate::dbconfig::schema::podcasts::table as podcast_table; + pub fn delete_watchtime(podcast_id: i32) -> Result<(), CustomError> { + use crate::adapters::persistence::dbconfig::schema::episodes::dsl as ep_dsl; + use crate::adapters::persistence::dbconfig::schema::episodes::table as ep_table; + use crate::adapters::persistence::dbconfig::schema::podcasts::dsl as podcast_dsl; + use crate::adapters::persistence::dbconfig::schema::podcasts::table as podcast_table; let found_podcast: Option = podcast_table .filter(podcast_dsl::id.eq(podcast_id)) - .first(conn) + .first(&mut get_connection()) .optional() .map_err(map_db_error)?; diesel::delete(ep_table.filter(ep_dsl::podcast.eq(found_podcast.unwrap().rssfeed))) - .execute(conn) + .execute(&mut get_connection()) .map_err(map_db_error)?; Ok(()) } pub fn get_watchtime( - conn: &mut DbConnection, episode_id: String, username: String, ) -> Result, CustomError> { - use crate::dbconfig::schema::episodes::dsl as ep_dsl; - use crate::dbconfig::schema::episodes::table as ep_table; - use crate::dbconfig::schema::podcast_episodes::dsl as pe_dsl; - use crate::dbconfig::schema::podcast_episodes::table as pe_table; + use crate::adapters::persistence::dbconfig::schema::episodes::dsl as ep_dsl; + use crate::adapters::persistence::dbconfig::schema::episodes::table as ep_table; + use crate::adapters::persistence::dbconfig::schema::podcast_episodes::dsl as pe_dsl; + use crate::adapters::persistence::dbconfig::schema::podcast_episodes::table as pe_table; let podcast_episode = pe_table .filter(pe_dsl::episode_id.eq(episode_id)) - .first::(conn) + .first::(&mut get_connection()) .optional() .map_err(map_db_error)?; let episode = ep_table .filter(ep_dsl::username.eq(username)) .filter(ep_dsl::guid.eq(podcast_episode.unwrap().guid)) - .first::(conn) + .first::(&mut get_connection()) .optional() .map_err(map_db_error)?; @@ -337,18 +334,17 @@ impl Episode { } pub fn log_watchtime( - conn: &mut DbConnection, pod_watch_model: PodcastWatchedPostModel, username: String, ) -> Result<(), CustomError> { - use crate::dbconfig::schema::podcast_episodes::dsl as pe_dsl; - use crate::dbconfig::schema::podcast_episodes::table as pe_table; - use crate::dbconfig::schema::podcasts::dsl as p_dsl; - use crate::dbconfig::schema::podcasts::table as p_table; + use crate::adapters::persistence::dbconfig::schema::podcast_episodes::dsl as pe_dsl; + use crate::adapters::persistence::dbconfig::schema::podcast_episodes::table as pe_table; + use crate::adapters::persistence::dbconfig::schema::podcasts::dsl as p_dsl; + use crate::adapters::persistence::dbconfig::schema::podcasts::table as p_table; let found_episode = pe_table .filter(pe_dsl::episode_id.eq(pod_watch_model.podcast_episode_id.clone())) - .first::(conn) + .first::(&mut get_connection()) .optional() .map_err(map_db_error)?; @@ -359,7 +355,7 @@ impl Episode { let podcast = p_table .filter(p_dsl::id.eq(found_episode.podcast_id)) - .first::(conn) + .first::(&mut get_connection()) .optional() .map_err(map_db_error)?; @@ -375,7 +371,6 @@ impl Episode { match Self::get_watchlog_by_device_and_episode( found_episode.guid.clone(), DEFAULT_DEVICE.to_string(), - conn, ) { Ok(Some(mut episode)) => { episode.position = Some(pod_watch_model.time); @@ -384,7 +379,7 @@ impl Episode { episodes::position.eq(pod_watch_model.time), episodes::timestamp.eq(Utc::now().naive_utc()), )) - .execute(conn) + .execute(&mut get_connection()) .map_err(map_db_error)?; return Ok(()); } @@ -403,7 +398,7 @@ impl Episode { position: Some(pod_watch_model.time), total: Some(found_episode.total_time), }; - episode.insert_episode(conn).map_err(map_db_error)?; + episode.insert_episode().map_err(map_db_error)?; } Err(e) => { return Err(e); @@ -416,25 +411,24 @@ impl Episode { pub fn get_watchlog_by_device_and_episode( episode_guid: String, device_id: String, - conn: &mut DbConnection, ) -> Result, CustomError> { - use crate::dbconfig::schema::episodes::dsl as ep_dsl; - use crate::dbconfig::schema::episodes::table as ep_table; + use crate::adapters::persistence::dbconfig::schema::episodes::dsl as ep_dsl; + use crate::adapters::persistence::dbconfig::schema::episodes::table as ep_table; ep_table .filter(ep_dsl::device.eq(device_id)) .filter(ep_dsl::guid.eq(episode_guid)) - .first::(conn) + .first::(&mut get_connection()) .optional() .map_err(map_db_error) } - pub fn delete_by_username(conn: &mut DbConnection, username: &str) -> Result<(), CustomError> { - use crate::dbconfig::schema::episodes::dsl as ep_dsl; - use crate::dbconfig::schema::episodes::table as ep_table; + pub fn delete_by_username(username: &str) -> Result<(), CustomError> { + use crate::adapters::persistence::dbconfig::schema::episodes::dsl as ep_dsl; + use crate::adapters::persistence::dbconfig::schema::episodes::table as ep_table; diesel::delete(ep_table.filter(ep_dsl::username.eq(username))) - .execute(conn) + .execute(&mut get_connection()) .map_err(map_db_error)?; Ok(()) } diff --git a/src/models/favorites.rs b/src/models/favorites.rs index 0dbb9391..0ec029f3 100644 --- a/src/models/favorites.rs +++ b/src/models/favorites.rs @@ -1,4 +1,4 @@ -use crate::dbconfig::schema::favorites; +use crate::adapters::persistence::dbconfig::schema::favorites; use crate::models::order_criteria::{OrderCriteria, OrderOption}; use crate::models::podcast_dto::PodcastDto; use crate::models::podcast_episode::PodcastEpisode; @@ -11,6 +11,7 @@ use diesel::insert_into; use diesel::prelude::*; use diesel::sql_types::{Bool, Integer, Text}; use serde::{Deserialize, Serialize}; +use crate::adapters::persistence::dbconfig::db::get_connection; use crate::models::tag::Tag; #[derive( @@ -41,7 +42,7 @@ impl Favorite { username1: String, conn: &mut DbConnection, ) -> Result<(), diesel::result::Error> { - use crate::dbconfig::schema::favorites::dsl::*; + use crate::adapters::persistence::dbconfig::schema::favorites::dsl::*; diesel::delete(favorites.filter(username.eq(username1))).execute(conn)?; Ok(()) } @@ -49,13 +50,12 @@ impl Favorite { pub fn update_podcast_favor( podcast_id_1: &i32, favor: bool, - conn: &mut DbConnection, username_1: String, ) -> Result<(), CustomError> { - use crate::dbconfig::schema::favorites::dsl::favored as favor_column; - use crate::dbconfig::schema::favorites::dsl::favorites as f_db; - use crate::dbconfig::schema::favorites::dsl::podcast_id; - use crate::dbconfig::schema::favorites::dsl::username; + use crate::adapters::persistence::dbconfig::schema::favorites::dsl::favored as favor_column; + use crate::adapters::persistence::dbconfig::schema::favorites::dsl::favorites as f_db; + use crate::adapters::persistence::dbconfig::schema::favorites::dsl::podcast_id; + use crate::adapters::persistence::dbconfig::schema::favorites::dsl::username; let res = f_db .filter( @@ -63,7 +63,7 @@ impl Favorite { .eq(podcast_id_1) .and(username.eq(username_1.clone())), ) - .first::(conn) + .first::(&mut get_connection()) .optional() .map_err(map_db_error)?; @@ -73,7 +73,7 @@ impl Favorite { f_db.filter(podcast_id.eq(podcast_id_1).and(username.eq(username_1))), ) .set(favor_column.eq(favor)) - .execute(conn) + .execute(&mut get_connection()) .map_err(map_db_error)?; Ok(()) } @@ -84,7 +84,7 @@ impl Favorite { username.eq(username_1), favor_column.eq(favor), )) - .execute(conn) + .execute(&mut get_connection()) .map_err(map_db_error)?; Ok(()) } @@ -93,23 +93,22 @@ impl Favorite { pub fn get_favored_podcasts( found_username: String, - conn: &mut DbConnection, ) -> Result, CustomError> { - use crate::dbconfig::schema::favorites::dsl::favored as favor_column; - use crate::dbconfig::schema::favorites::dsl::favorites as f_db; - use crate::dbconfig::schema::favorites::dsl::username as user_favor; - use crate::dbconfig::schema::podcasts::dsl::podcasts as dsl_podcast; + use crate::adapters::persistence::dbconfig::schema::favorites::dsl::favored as favor_column; + use crate::adapters::persistence::dbconfig::schema::favorites::dsl::favorites as f_db; + use crate::adapters::persistence::dbconfig::schema::favorites::dsl::username as user_favor; + use crate::adapters::persistence::dbconfig::schema::podcasts::dsl::podcasts as dsl_podcast; let result: Vec<(Podcast, Favorite)> = dsl_podcast .inner_join(f_db) .filter(favor_column.eq(true).and(user_favor.eq(&found_username))) - .load::<(Podcast, Favorite)>(conn) + .load::<(Podcast, Favorite)>(&mut get_connection()) .map_err(map_db_error)?; let mapped_result = result .iter() .map(|podcast| { - let tags = Tag::get_tags_of_podcast(conn, podcast.0.id, &found_username).unwrap(); + let tags = Tag::get_tags_of_podcast(podcast.0.id, &found_username).unwrap(); MappingService::map_podcast_to_podcast_dto_with_favorites_option(podcast, tags) }) .collect::>(); @@ -117,15 +116,14 @@ impl Favorite { } pub fn search_podcasts_favored( - conn: &mut DbConnection, order: OrderCriteria, title: Option, latest_pub: OrderOption, designated_username: &str ) -> Result, CustomError> { - use crate::dbconfig::schema::podcast_episodes::dsl::*; - use crate::dbconfig::schema::podcasts::dsl::id as podcastsid; - use crate::dbconfig::schema::podcasts::dsl::*; + use crate::adapters::persistence::dbconfig::schema::podcast_episodes::dsl::*; + use crate::adapters::persistence::dbconfig::schema::podcasts::dsl::id as podcastsid; + use crate::adapters::persistence::dbconfig::schema::podcasts::dsl::*; let mut query = podcasts .inner_join(podcast_episodes.on(podcastsid.eq(podcast_id))) @@ -138,7 +136,7 @@ impl Favorite { match latest_pub { OrderOption::Title => { - use crate::dbconfig::schema::podcasts::dsl::name as podcasttitle; + use crate::adapters::persistence::dbconfig::schema::podcasts::dsl::name as podcasttitle; match order { OrderCriteria::Asc => { query = query.order_by(podcasttitle.asc()); @@ -159,13 +157,13 @@ impl Favorite { } if title.is_some() { - use crate::dbconfig::schema::podcasts::dsl::name as podcasttitle; + use crate::adapters::persistence::dbconfig::schema::podcasts::dsl::name as podcasttitle; query = query.filter(podcasttitle.like(format!("%{}%", title.unwrap()))); } let mut matching_podcast_ids = vec![]; let pr = query - .load::<(Podcast, PodcastEpisode, Favorite)>(conn) + .load::<(Podcast, PodcastEpisode, Favorite)>(&mut get_connection()) .map_err(map_db_error)?; let distinct_podcasts: Vec<(Podcast, Favorite)> = pr .iter() @@ -182,18 +180,17 @@ impl Favorite { } pub fn search_podcasts( - conn: &mut DbConnection, order: OrderCriteria, title: Option, latest_pub: OrderOption, designated_username: &str, ) -> Result)>, CustomError> { - use crate::dbconfig::schema::favorites::dsl::favorites as f_db; - use crate::dbconfig::schema::favorites::dsl::podcast_id as f_id; - use crate::dbconfig::schema::favorites::dsl::username as f_username; - use crate::dbconfig::schema::podcast_episodes::dsl::*; - use crate::dbconfig::schema::podcasts::dsl::id as podcastsid; - use crate::dbconfig::schema::podcasts::dsl::*; + use crate::adapters::persistence::dbconfig::schema::favorites::dsl::favorites as f_db; + use crate::adapters::persistence::dbconfig::schema::favorites::dsl::podcast_id as f_id; + use crate::adapters::persistence::dbconfig::schema::favorites::dsl::username as f_username; + use crate::adapters::persistence::dbconfig::schema::podcast_episodes::dsl::*; + use crate::adapters::persistence::dbconfig::schema::podcasts::dsl::id as podcastsid; + use crate::adapters::persistence::dbconfig::schema::podcasts::dsl::*; let mut query = podcasts .inner_join(podcast_episodes.on(podcastsid.eq(podcast_id))) @@ -202,7 +199,7 @@ impl Favorite { match latest_pub { OrderOption::Title => { - use crate::dbconfig::schema::podcasts::dsl::name as podcasttitle; + use crate::adapters::persistence::dbconfig::schema::podcasts::dsl::name as podcasttitle; match order { OrderCriteria::Asc => { query = query.order_by(podcasttitle.asc()); @@ -225,13 +222,13 @@ impl Favorite { define_sql_function!(fn lower(x: Text) -> Text); if let Some(title) = title { - use crate::dbconfig::schema::podcasts::dsl::name as podcasttitle; + use crate::adapters::persistence::dbconfig::schema::podcasts::dsl::name as podcasttitle; query = query.filter(lower(podcasttitle).like(format!("%{}%", title.to_lowercase()))); } let mut matching_podcast_ids = vec![]; let pr = query - .load::<(Podcast, PodcastEpisode, Option)>(conn) + .load::<(Podcast, PodcastEpisode, Option)>(&mut get_connection()) .map_err(map_db_error)?; let distinct_podcasts = pr .iter() diff --git a/src/models/file_path.rs b/src/models/file_path.rs index 195ffbc0..19e20357 100644 --- a/src/models/file_path.rs +++ b/src/models/file_path.rs @@ -54,9 +54,8 @@ impl FilenameBuilder { pub fn with_episode( mut self, podcast_episode: PodcastEpisode, - conn: &mut DbConnection, ) -> Result { - self.episode = prepare_podcast_episode_title_to_directory(podcast_episode.clone(), conn)?; + self.episode = prepare_podcast_episode_title_to_directory(podcast_episode.clone())?; self.raw_episode = podcast_episode; Ok(self) } @@ -88,14 +87,12 @@ impl FilenameBuilder { pub fn with_raw_directory( mut self, - conn: &mut DbConnection, ) -> Result { self.directory = PathService::get_image_path( &self.podcast.clone().directory_name, Some(self.raw_episode.clone()), &self.suffix, &self.raw_episode.name, - conn, )?; self.raw_filename = true; Ok(self) diff --git a/src/models/filter.rs b/src/models/filter.rs index 3b6a5eda..62c6300c 100644 --- a/src/models/filter.rs +++ b/src/models/filter.rs @@ -1,12 +1,13 @@ -use crate::dbconfig::schema::filters; use crate::utils::error::{map_db_error, CustomError}; -use crate::{execute_with_conn, DBType as DbConnection}; +use crate::execute_with_conn; use diesel::AsChangeset; use diesel::ExpressionMethods; use diesel::QueryDsl; use diesel::Queryable; use diesel::{Insertable, OptionalExtension, RunQueryDsl}; use utoipa::ToSchema; +use crate::adapters::persistence::dbconfig::db::get_connection; +use crate::adapters::persistence::dbconfig::schema::filters; #[derive(Debug, Clone, Serialize, Deserialize, Insertable, AsChangeset, Queryable, ToSchema)] #[serde(rename_all = "camelCase")] @@ -36,23 +37,23 @@ impl Filter { } #[allow(clippy::redundant_closure_call)] - pub fn save_filter(self, conn: &mut DbConnection) -> Result<(), CustomError> { - use crate::dbconfig::schema::filters::dsl::*; + pub fn save_filter(self) -> Result<(), CustomError> { + use crate::adapters::persistence::dbconfig::schema::filters::dsl::*; let opt_filter = filters .filter(username.eq(&self.username)) - .first::(conn) + .first::(&mut get_connection()) .optional() .expect("Error connecting to database"); // delete all filters match opt_filter { Some(_) => { diesel::update(filters.filter(username.eq(&self.clone().username))) .set(self) - .execute(conn) + .execute(&mut get_connection()) .map_err(map_db_error)?; } None => { - execute_with_conn!(conn, |conn| { + execute_with_conn!(|conn| { diesel::insert_into(filters) .values(self) .execute(conn) @@ -66,12 +67,11 @@ impl Filter { pub async fn get_filter_by_username( username1: String, - conn: &mut DbConnection, ) -> Result, CustomError> { - use crate::dbconfig::schema::filters::dsl::*; + use crate::adapters::persistence::dbconfig::schema::filters::dsl::*; let res = filters .filter(username.eq(username1)) - .first::(conn) + .first::(&mut get_connection()) .optional() .map_err(map_db_error)?; Ok(res) @@ -79,13 +79,12 @@ impl Filter { pub fn save_decision_for_timeline( username_to_search: String, - conn: &mut DbConnection, only_favored_to_insert: bool, ) { - use crate::dbconfig::schema::filters::dsl::*; + use crate::adapters::persistence::dbconfig::schema::filters::dsl::*; diesel::update(filters.filter(username.eq(username_to_search))) .set(only_favored.eq(only_favored_to_insert)) - .execute(conn) + .execute(&mut get_connection()) .expect("Error connecting to database"); } } diff --git a/src/models/invite.rs b/src/models/invite.rs index a190a3b7..11650511 100644 --- a/src/models/invite.rs +++ b/src/models/invite.rs @@ -1,7 +1,6 @@ use crate::constants::inner_constants::Role; -use crate::dbconfig::schema::invites; +use crate::adapters::persistence::dbconfig::schema::invites; use crate::utils::error::{map_db_error, CustomError}; -use crate::DBType as DbConnection; use chrono::NaiveDateTime; use diesel::associations::HasTable; use diesel::ExpressionMethods; @@ -9,6 +8,7 @@ use diesel::{Identifiable, Insertable, OptionalExtension, QueryDsl, Queryable, R use std::io::Error; use utoipa::ToSchema; use uuid::Uuid; +use crate::adapters::persistence::dbconfig::db::get_connection; #[derive(Queryable, Insertable, Identifiable, Serialize, Deserialize, Clone, ToSchema)] #[serde(rename_all = "camelCase")] @@ -43,9 +43,8 @@ impl Invite { pub fn insert_invite( role_to_insert: &Role, explicit_consent_to_insert: bool, - conn: &mut DbConnection, ) -> Result { - use crate::dbconfig::schema::invites::dsl::*; + use crate::adapters::persistence::dbconfig::schema::invites::dsl::*; let now = chrono::Utc::now().naive_utc(); @@ -57,42 +56,41 @@ impl Invite { created_at.eq(now), expires_at.eq(now + chrono::Duration::days(7)), )) - .get_result::(conn) + .get_result::(&mut get_connection()) .unwrap(); Ok(created_invite) } - pub fn find_invite(id: String, conn: &mut DbConnection) -> Result, CustomError> { + pub fn find_invite(id: String) -> Result, CustomError> { invites::table .filter(invites::id.eq(id)) - .first::(conn) + .first::(&mut get_connection()) .optional() .map_err(map_db_error) } - pub fn find_all_invites(conn: &mut DbConnection) -> Result, diesel::result::Error> { - invites::table.load::(conn) + pub fn find_all_invites() -> Result, diesel::result::Error> { + invites::table.load::(&mut get_connection()) } pub fn invalidate_invite( invite_id: String, - conn: &mut DbConnection, ) -> Result<(), diesel::result::Error> { - use crate::dbconfig::schema::invites::dsl::*; + use crate::adapters::persistence::dbconfig::schema::invites::dsl::*; diesel::update(invites.filter(id.eq(invite_id))) .set(accepted_at.eq(chrono::Utc::now().naive_utc())) - .execute(conn)?; + .execute(&mut get_connection())?; Ok(()) } - pub fn delete_invite(invite_id: String, conn: &mut DbConnection) -> Result<(), CustomError> { - use crate::dbconfig::schema::invites::dsl::*; + pub fn delete_invite(invite_id: String) -> Result<(), CustomError> { + use crate::adapters::persistence::dbconfig::schema::invites::dsl::*; diesel::delete(invites.filter(id.eq(invite_id))) - .execute(conn) + .execute(&mut get_connection()) .map_err(map_db_error)?; Ok(()) diff --git a/src/models/notification.rs b/src/models/notification.rs index 1c0970c1..4f0c134f 100644 --- a/src/models/notification.rs +++ b/src/models/notification.rs @@ -1,9 +1,9 @@ use crate::utils::do_retry::do_retry; use crate::utils::error::{map_db_error, CustomError}; -use crate::DBType as DbConnection; use diesel::insert_into; use diesel::Queryable; use utoipa::ToSchema; +use crate::adapters::persistence::dbconfig::db::get_connection; #[derive(Serialize, Deserialize, Queryable, Clone, ToSchema)] #[serde(rename_all = "camelCase")] @@ -16,10 +16,8 @@ pub struct Notification { } impl Notification { - pub fn get_unread_notifications( - conn: &mut DbConnection, - ) -> Result, CustomError> { - use crate::dbconfig::schema::notifications::dsl::*; + pub fn get_unread_notifications() -> Result, CustomError> { + use crate::adapters::persistence::dbconfig::schema::notifications::dsl::*; use diesel::ExpressionMethods; use diesel::QueryDsl; use diesel::RunQueryDsl; @@ -27,17 +25,16 @@ impl Notification { let result = notifications .filter(status.eq("unread")) .order(created_at.desc()) - .load::(conn) + .load::(&mut get_connection()) .map_err(map_db_error)?; Ok(result) } pub fn insert_notification( notification: Notification, - conn: &mut DbConnection, ) -> Result<(), CustomError> { - use crate::dbconfig::schema::notifications::dsl::notifications; - use crate::dbconfig::schema::notifications::*; + use crate::adapters::persistence::dbconfig::schema::notifications::dsl::notifications; + use crate::adapters::persistence::dbconfig::schema::notifications::*; use diesel::ExpressionMethods; use diesel::RunQueryDsl; @@ -48,7 +45,7 @@ impl Notification { status.eq(notification.clone().status), created_at.eq(notification.clone().created_at), )) - .execute(conn) + .execute(&mut get_connection()) .map_err(map_db_error)?; Ok(()) } @@ -56,16 +53,15 @@ impl Notification { pub fn update_status_of_notification( id_to_search: i32, status_update: &str, - conn: &mut DbConnection, ) -> Result<(), CustomError> { - use crate::dbconfig::schema::notifications::dsl::*; + use crate::adapters::persistence::dbconfig::schema::notifications::dsl::*; use diesel::ExpressionMethods; use diesel::QueryDsl; use diesel::RunQueryDsl; do_retry(|| { diesel::update(notifications.filter(id.eq(id_to_search))) .set(status.eq(status_update)) - .execute(conn) + .execute(&mut get_connection()) }) .map_err(map_db_error)?; Ok(()) diff --git a/src/models/playlist.rs b/src/models/playlist.rs index 517998a1..c1122c58 100644 --- a/src/models/playlist.rs +++ b/src/models/playlist.rs @@ -1,6 +1,6 @@ use crate::controllers::playlist_controller::{PlaylistDto, PlaylistDtoPost}; use crate::controllers::podcast_episode_controller::PodcastEpisodeWithHistory; -use crate::dbconfig::schema::playlists; +use crate::adapters::persistence::dbconfig::schema::playlists; use crate::models::episode::Episode; use crate::models::playlist_item::PlaylistItem; use crate::models::podcast_episode::PodcastEpisode; @@ -14,6 +14,7 @@ use diesel::RunQueryDsl; use diesel::{Queryable, QueryableByName}; use utoipa::ToSchema; use uuid::Uuid; +use crate::adapters::persistence::dbconfig::db::get_connection; #[derive(Serialize, Deserialize, Queryable, Insertable, QueryableByName, Clone, ToSchema)] pub struct Playlist { @@ -28,7 +29,7 @@ pub struct Playlist { impl Playlist { #[allow(clippy::redundant_closure_call)] pub fn insert_playlist(&self, conn: &mut DbConnection) -> Result { - use crate::dbconfig::schema::playlists::dsl::*; + use crate::adapters::persistence::dbconfig::schema::playlists::dsl::*; let res = playlists .filter(name.eq(self.name.clone())) @@ -39,18 +40,19 @@ impl Playlist { if let Some(unwrapped_res) = res { return Ok(unwrapped_res); } - - execute_with_conn!(conn, |conn| diesel::insert_into(playlists) + + + execute_with_conn!(|conn| diesel::insert_into(playlists) .values(self) .get_result::(conn) - .map_err(map_db_error)); + .map_err(map_db_error)) } pub fn delete_playlist( playlist_id_1: String, conn: &mut DbConnection, ) -> Result<(), CustomError> { - use crate::dbconfig::schema::playlists::dsl::*; + use crate::adapters::persistence::dbconfig::schema::playlists::dsl::*; diesel::delete(playlists.filter(id.eq(playlist_id_1))) .execute(conn) @@ -60,13 +62,12 @@ impl Playlist { pub fn get_playlist_by_id( playlist_id_1: String, - conn: &mut DbConnection, ) -> Result { - use crate::dbconfig::schema::playlists::dsl::*; + use crate::adapters::persistence::dbconfig::schema::playlists::dsl::*; let res = playlists .filter(id.eq(playlist_id_1)) - .first::(conn) + .first::(&mut get_connection()) .optional() .map_err(map_db_error)?; @@ -80,14 +81,13 @@ impl Playlist { pub fn get_playlist_by_user_and_id( playlist_id_1: String, user: User, - conn: &mut DbConnection, ) -> Result { - use crate::dbconfig::schema::playlists::dsl::*; + use crate::adapters::persistence::dbconfig::schema::playlists::dsl::*; let res = playlists .filter(id.eq(playlist_id_1)) .filter(user_id.eq(user.id)) - .first::(conn) + .first::(&mut get_connection()) .optional() .map_err(map_db_error)?; @@ -99,19 +99,17 @@ impl Playlist { } pub fn get_playlists( - conn: &mut DbConnection, user_id1: i32, ) -> Result, CustomError> { - use crate::dbconfig::schema::playlists::dsl::*; + use crate::adapters::persistence::dbconfig::schema::playlists::dsl::*; playlists .filter(user_id.eq(user_id1)) - .load::(conn) + .load::(&mut get_connection()) .map_err(map_db_error) } pub fn create_new_playlist( - conn: &mut DbConnection, playlist_dto: PlaylistDtoPost, user: User, ) -> Result { @@ -120,7 +118,7 @@ impl Playlist { name: playlist_dto.name.clone(), user_id: user.id, }; - let inserted_playlist = playlist_to_insert.insert_playlist(conn)?; + let inserted_playlist = playlist_to_insert.insert_playlist(&mut get_connection())?; playlist_dto.items.iter().enumerate().for_each(|(i, x)| { let playlist_item_to_insert = PlaylistItem { @@ -129,13 +127,12 @@ impl Playlist { position: i as i32, }; playlist_item_to_insert - .insert_playlist_item(conn) + .insert_playlist_item(&mut get_connection()) .expect("Error inserting playlist item"); }); let items = PlaylistItem::get_playlist_items_by_playlist_id( inserted_playlist.id.clone(), - conn, user, )?; let playlist_dto_returned = inserted_playlist.to_playlist_dto(items); @@ -164,27 +161,25 @@ impl Playlist { pub fn update_playlist_fields( playlist_id_1: String, playlist_dto: PlaylistDtoPost, - conn: &mut DbConnection, user_id_1: User, ) -> Result { - use crate::dbconfig::schema::playlists::dsl::*; + use crate::adapters::persistence::dbconfig::schema::playlists::dsl::*; diesel::update( playlists .filter(id.eq(playlist_id_1)) .filter(user_id.eq(user_id_1.id)), ) .set(name.eq(playlist_dto.name)) - .execute(conn) + .execute(&mut get_connection()) .map_err(map_db_error) } pub fn update_playlist( - conn: &mut DbConnection, playlist_dto: PlaylistDtoPost, playlist_id: String, user: User, ) -> Result { - let playlist_to_be_updated = Self::get_playlist_by_id(playlist_id.clone(), conn)?; + let playlist_to_be_updated = Self::get_playlist_by_id(playlist_id.clone())?; if playlist_to_be_updated.user_id != user.id { return Err(CustomError::Forbidden); @@ -193,12 +188,11 @@ impl Playlist { Self::update_playlist_fields( playlist_id.clone(), playlist_dto.clone(), - conn, user.clone(), )?; // deletes all old playlist entries - PlaylistItem::delete_playlist_item_by_playlist_id(playlist_id.clone(), conn)?; + PlaylistItem::delete_playlist_item_by_playlist_id(playlist_id.clone())?; // inserts new playlist entries playlist_dto.items.iter().enumerate().for_each(|(i, x)| { @@ -208,17 +202,16 @@ impl Playlist { position: i as i32, }; playlist_item_to_insert - .insert_playlist_item(conn) + .insert_playlist_item(&mut get_connection()) .expect("Error inserting playlist item"); }); - let updated_playlist = Self::get_playlist_by_id(playlist_id.clone(), conn)?; - Self::get_playlist_dto(playlist_id, conn, updated_playlist, user) + let updated_playlist = Self::get_playlist_by_id(playlist_id.clone())?; + Self::get_playlist_dto(playlist_id, updated_playlist, user) } pub(crate) fn get_playlist_dto( playlist_id: String, - conn: &mut DbConnection, playlist: Playlist, user: User, ) -> Result { @@ -226,31 +219,30 @@ impl Playlist { return Err(CustomError::Forbidden); } let items_in_playlist = - PlaylistItem::get_playlist_items_by_playlist_id(playlist_id, conn, user)?; + PlaylistItem::get_playlist_items_by_playlist_id(playlist_id, user)?; Ok(playlist.to_playlist_dto(items_in_playlist)) } pub fn delete_playlist_by_id( playlist_id: String, - conn: &mut DbConnection, user_id1: i32, ) -> Result<(), CustomError> { - use crate::dbconfig::schema::playlists::dsl::*; + use crate::adapters::persistence::dbconfig::schema::playlists::dsl::*; - let playlist_to_delete = Playlist::get_playlist_by_id(playlist_id.clone(), conn)?; + let playlist_to_delete = Playlist::get_playlist_by_id(playlist_id.clone())?; if playlist_to_delete.user_id != user_id1 { return Err(CustomError::Forbidden); } - PlaylistItem::delete_playlist_item_by_playlist_id(playlist_id.clone(), conn)?; + PlaylistItem::delete_playlist_item_by_playlist_id(playlist_id.clone())?; diesel::delete( playlists .filter(id.eq(playlist_id)) .filter(user_id.eq(user_id1)), ) - .execute(conn) + .execute(&mut get_connection()) .map_err(map_db_error)?; Ok(()) } @@ -258,23 +250,22 @@ impl Playlist { pub async fn delete_playlist_item( playlist_id_1: String, episode_id: i32, - conn: &mut DbConnection, user_id: i32, ) -> Result<(), CustomError> { - let found_podcast = Self::get_playlist_by_id(playlist_id_1.clone(), conn)?; + let found_podcast = Self::get_playlist_by_id(playlist_id_1.clone())?; if found_podcast.user_id != user_id { return Err(CustomError::Forbidden); } - use crate::dbconfig::schema::playlist_items::dsl::*; + use crate::adapters::persistence::dbconfig::schema::playlist_items::dsl::*; diesel::delete( playlist_items .filter(playlist_id.eq(playlist_id)) .filter(episode.eq(episode_id)), ) - .execute(conn) + .execute(&mut get_connection()) .map_err(map_db_error)?; Ok(()) } diff --git a/src/models/playlist_item.rs b/src/models/playlist_item.rs index 3f1976ef..fecb04b2 100644 --- a/src/models/playlist_item.rs +++ b/src/models/playlist_item.rs @@ -1,4 +1,4 @@ -use crate::dbconfig::schema::playlist_items; +use crate::adapters::persistence::dbconfig::schema::playlist_items; use crate::models::episode::Episode; use crate::models::podcast_episode::PodcastEpisode; use crate::models::user::User; @@ -10,6 +10,7 @@ use diesel::sql_types::{Integer, Text}; use diesel::ExpressionMethods; use diesel::{Queryable, QueryableByName}; use utoipa::ToSchema; +use crate::adapters::persistence::dbconfig::db::get_connection; #[derive( Serialize, Deserialize, Debug, Queryable, QueryableByName, Insertable, Clone, ToSchema, @@ -28,7 +29,7 @@ impl PlaylistItem { &self, conn: &mut DbConnection, ) -> Result { - use crate::dbconfig::schema::playlist_items::dsl::*; + use crate::adapters::persistence::dbconfig::schema::playlist_items::dsl::*; let res = playlist_items .filter( @@ -59,7 +60,7 @@ impl PlaylistItem { episode_1: i32, conn: &mut DbConnection, ) -> Result<(), diesel::result::Error> { - use crate::dbconfig::schema::playlist_items::dsl::*; + use crate::adapters::persistence::dbconfig::schema::playlist_items::dsl::*; diesel::delete( playlist_items.filter(playlist_id.eq(playlist_id_1).and(episode.eq(episode_1))), @@ -70,29 +71,27 @@ impl PlaylistItem { pub fn delete_playlist_item_by_playlist_id( playlist_id_1: String, - conn: &mut DbConnection, ) -> Result<(), CustomError> { - use crate::dbconfig::schema::playlist_items::dsl::*; + use crate::adapters::persistence::dbconfig::schema::playlist_items::dsl::*; diesel::delete(playlist_items.filter(playlist_id.eq(playlist_id_1))) - .execute(conn) + .execute(&mut get_connection()) .map_err(map_db_error)?; Ok(()) } pub fn get_playlist_items_by_playlist_id( playlist_id_1: String, - conn: &mut DbConnection, user: User, ) -> Result)>, CustomError> { - use crate::dbconfig::schema::episodes as episode_item; - use crate::dbconfig::schema::episodes::episode as phistory_episode_id; - use crate::dbconfig::schema::episodes::timestamp as phistory_date; - use crate::dbconfig::schema::episodes::username as phistory_username; - use crate::dbconfig::schema::playlist_items::dsl::*; - use crate::dbconfig::schema::podcast_episodes::dsl::episode_id as epid; - use crate::dbconfig::schema::podcast_episodes::dsl::id as eid; - use crate::dbconfig::schema::podcast_episodes::dsl::podcast_episodes; + use crate::adapters::persistence::dbconfig::schema::episodes as episode_item; + use crate::adapters::persistence::dbconfig::schema::episodes::episode as phistory_episode_id; + use crate::adapters::persistence::dbconfig::schema::episodes::timestamp as phistory_date; + use crate::adapters::persistence::dbconfig::schema::episodes::username as phistory_username; + use crate::adapters::persistence::dbconfig::schema::playlist_items::dsl::*; + use crate::adapters::persistence::dbconfig::schema::podcast_episodes::dsl::episode_id as epid; + use crate::adapters::persistence::dbconfig::schema::podcast_episodes::dsl::id as eid; + use crate::adapters::persistence::dbconfig::schema::podcast_episodes::dsl::podcast_episodes; let (ph1, ph2) = diesel::alias!(episode_item as ph1, episode_item as ph2); let subquery = ph2 @@ -107,7 +106,7 @@ impl PlaylistItem { .left_join(ph1.on(ph1.field(phistory_episode_id).eq(epid))) .filter(ph1.field(phistory_date).nullable().eq_any(subquery)) .order(position.asc()) - .load::<(PlaylistItem, PodcastEpisode, Option)>(conn) + .load::<(PlaylistItem, PodcastEpisode, Option)>(&mut get_connection()) .map_err(map_db_error) } @@ -115,7 +114,7 @@ impl PlaylistItem { episode_id_1: i32, conn: &mut DbConnection, ) -> Result<(), CustomError> { - use crate::dbconfig::schema::playlist_items::dsl::*; + use crate::adapters::persistence::dbconfig::schema::playlist_items::dsl::*; diesel::delete(playlist_items.filter(episode.eq(episode_id_1))) .execute(conn) diff --git a/src/models/podcast_episode.rs b/src/models/podcast_episode.rs index 46e3f266..d6a209eb 100644 --- a/src/models/podcast_episode.rs +++ b/src/models/podcast_episode.rs @@ -1,6 +1,6 @@ use crate::constants::inner_constants::DEFAULT_IMAGE_URL; -use crate::dbconfig::schema::*; -use crate::dbconfig::DBType; +use crate::adapters::persistence::dbconfig::schema::*; +use crate::adapters::persistence::dbconfig::DBType; use crate::models::episode::Episode; use crate::models::playlist_item::PlaylistItem; use crate::models::podcasts::Podcast; @@ -23,6 +23,7 @@ use diesel::{ }; use rss::{Guid, Item}; use utoipa::ToSchema; +use crate::adapters::persistence::dbconfig::db::get_connection; #[derive( Queryable, @@ -86,7 +87,7 @@ impl PodcastEpisode { conn: &mut DbConnection, podcast_episode_id_to_be_found: i32, ) -> Result, CustomError> { - use crate::dbconfig::schema::podcast_episodes::dsl::*; + use crate::adapters::persistence::dbconfig::schema::podcast_episodes::dsl::*; let found_podcast_episode = podcast_episodes .filter(id.eq(podcast_episode_id_to_be_found)) @@ -102,7 +103,7 @@ impl PodcastEpisode { pid: i32, conn: &mut DBType, ) -> Result { - use crate::dbconfig::schema::podcast_episodes::dsl::*; + use crate::adapters::persistence::dbconfig::schema::podcast_episodes::dsl::*; let result = diesel::QueryDsl::order( podcast_episodes @@ -116,14 +117,13 @@ impl PodcastEpisode { } pub fn get_podcast_episode_by_id( - conn: &mut DbConnection, podcas_episode_id_to_be_found: &str, ) -> Result, CustomError> { - use crate::dbconfig::schema::podcast_episodes::dsl::*; + use crate::adapters::persistence::dbconfig::schema::podcast_episodes::dsl::*; let found_podcast_episode = podcast_episodes .filter(episode_id.eq(podcas_episode_id_to_be_found)) - .first::(conn) + .first::(&mut get_connection()) .optional() .map_err(map_db_error)?; @@ -131,24 +131,23 @@ impl PodcastEpisode { } pub fn get_podcast_episode_by_url( - conn: &mut DbConnection, podcas_episode_url_to_be_found: &str, i: Option, ) -> Result, CustomError> { - use crate::dbconfig::schema::podcast_episodes::dsl::*; + use crate::adapters::persistence::dbconfig::schema::podcast_episodes::dsl::*; let found_podcast_epsiode = if let Some(i_unwrapped) = i { podcast_episodes .filter( url.eq(podcas_episode_url_to_be_found) .and(podcast_id.eq(i_unwrapped)), ) - .first::(conn) + .first::(&mut get_connection()) .optional() .map_err(map_db_error)? } else { podcast_episodes .filter(url.eq(podcas_episode_url_to_be_found)) - .first::(conn) + .first::(&mut get_connection()) .optional() .map_err(map_db_error)? }; @@ -157,14 +156,13 @@ impl PodcastEpisode { } pub fn query_podcast_episode_by_url( - conn: &mut DbConnection, podcas_episode_url_to_be_found: &str, ) -> Result, String> { - use crate::dbconfig::schema::podcast_episodes::dsl::*; + use crate::adapters::persistence::dbconfig::schema::podcast_episodes::dsl::*; let found_podcast_episode = podcast_episodes .filter(url.like("%".to_owned() + podcas_episode_url_to_be_found + "%")) - .first::(conn) + .first::(&mut get_connection()) .optional() .expect("Error loading podcast by id"); @@ -172,13 +170,12 @@ impl PodcastEpisode { } pub fn insert_podcast_episodes( - conn: &mut DbConnection, podcast: Podcast, item: Item, optional_image: Option, duration: i32, ) -> PodcastEpisode { - use crate::dbconfig::schema::podcast_episodes::dsl::*; + use crate::adapters::persistence::dbconfig::schema::podcast_episodes::dsl::*; let uuid_podcast = uuid::Uuid::new_v4(); let mut inserted_date = "".to_string(); @@ -233,24 +230,23 @@ impl PodcastEpisode { image_url.eq(inserted_image_url), description.eq(opt_or_empty_string(item.description)), )) - .get_result::(conn) + .get_result::(&mut get_connection()) .expect("Error inserting podcast episode"); inserted_podcast } pub fn get_podcast_episodes_of_podcast( - conn: &mut DbConnection, podcast_id_to_be_searched: i32, last_id: Option, user: User, ) -> Result)>, CustomError> { - use crate::dbconfig::schema::episodes as phistory; - use crate::dbconfig::schema::episodes::guid as eguid; - use crate::dbconfig::schema::episodes::timestamp as phistory_date; - use crate::dbconfig::schema::episodes::username as phistory_username; - use crate::dbconfig::schema::podcast_episodes::dsl::podcast_episodes; - use crate::dbconfig::schema::podcast_episodes::*; + use crate::adapters::persistence::dbconfig::schema::episodes as phistory; + use crate::adapters::persistence::dbconfig::schema::episodes::guid as eguid; + use crate::adapters::persistence::dbconfig::schema::episodes::timestamp as phistory_date; + use crate::adapters::persistence::dbconfig::schema::episodes::username as phistory_username; + use crate::adapters::persistence::dbconfig::schema::podcast_episodes::dsl::podcast_episodes; + use crate::adapters::persistence::dbconfig::schema::podcast_episodes::*; let (ph1, ph2) = diesel::alias!(phistory as ph1, phistory as ph2); let subquery = ph2 @@ -273,7 +269,7 @@ impl PodcastEpisode { .filter(date_of_recording.lt(last_id)) .order(date_of_recording.desc()) .limit(75) - .load::<(PodcastEpisode, Option)>(conn) + .load::<(PodcastEpisode, Option)>(&mut get_connection()) .map_err(map_db_error)?; Ok(podcasts_found) } @@ -289,7 +285,7 @@ impl PodcastEpisode { .filter(podcast_id.eq(podcast_id_to_be_searched)) .order(date_of_recording.desc()) .limit(75) - .load::<(PodcastEpisode, Option)>(conn) + .load::<(PodcastEpisode, Option)>(&mut get_connection()) .expect("Error loading podcasts"); Ok(podcasts_found) @@ -298,16 +294,15 @@ impl PodcastEpisode { } pub fn get_last_n_podcast_episodes( - conn: &mut DbConnection, podcast_episode_id: i32, number_to_download: i32, ) -> Result, CustomError> { - use crate::dbconfig::schema::podcast_episodes::dsl::*; + use crate::adapters::persistence::dbconfig::schema::podcast_episodes::dsl::*; podcast_episodes .filter(podcast_id.eq(podcast_episode_id)) .limit(number_to_download as i64) .order(date_of_recording.desc()) - .load::(conn) + .load::(&mut get_connection()) .map_err(map_db_error) } @@ -319,12 +314,12 @@ impl PodcastEpisode { file_episode_path: &str, conn: &mut DbConnection, ) -> Result<(), CustomError> { - use crate::dbconfig::schema::podcast_episodes::dsl::episode_id as episode_id_column; - use crate::dbconfig::schema::podcast_episodes::dsl::file_episode_path as file_episode_path_column; - use crate::dbconfig::schema::podcast_episodes::dsl::file_image_path as file_image_path_column; - use crate::dbconfig::schema::podcast_episodes::dsl::local_image_url as local_image_url_column; - use crate::dbconfig::schema::podcast_episodes::dsl::local_url as local_url_column; - use crate::dbconfig::schema::podcast_episodes::dsl::podcast_episodes; + use crate::adapters::persistence::dbconfig::schema::podcast_episodes::dsl::episode_id as episode_id_column; + use crate::adapters::persistence::dbconfig::schema::podcast_episodes::dsl::file_episode_path as file_episode_path_column; + use crate::adapters::persistence::dbconfig::schema::podcast_episodes::dsl::file_image_path as file_image_path_column; + use crate::adapters::persistence::dbconfig::schema::podcast_episodes::dsl::local_image_url as local_image_url_column; + use crate::adapters::persistence::dbconfig::schema::podcast_episodes::dsl::local_url as local_url_column; + use crate::adapters::persistence::dbconfig::schema::podcast_episodes::dsl::podcast_episodes; let result = podcast_episodes .filter(episode_id_column.eq(episode_id)) @@ -348,22 +343,21 @@ impl PodcastEpisode { } pub fn delete_episodes_of_podcast( - conn: &mut DbConnection, podcast_id: i32, ) -> Result<(), CustomError> { - use crate::dbconfig::schema::podcast_episodes::dsl::podcast_episodes; - use crate::dbconfig::schema::podcast_episodes::dsl::podcast_id as podcast_id_column; + use crate::adapters::persistence::dbconfig::schema::podcast_episodes::dsl::podcast_episodes; + use crate::adapters::persistence::dbconfig::schema::podcast_episodes::dsl::podcast_id as podcast_id_column; - Self::get_episodes_by_podcast_id(podcast_id, conn) + Self::get_episodes_by_podcast_id(podcast_id) .iter() .for_each(|episode| { - PlaylistItem::delete_playlist_item_by_episode_id(episode.id, conn) + PlaylistItem::delete_playlist_item_by_episode_id(episode.id, &mut get_connection()) .expect("Error deleting episode"); }); delete(podcast_episodes) .filter(podcast_id_column.eq(podcast_id)) - .execute(conn) + .execute(&mut get_connection()) .map_err(map_db_error)?; Ok(()) } @@ -371,22 +365,21 @@ impl PodcastEpisode { pub fn update_podcast_image( id: &str, image_url: &str, - conn: &mut DbConnection, ) -> Result<(), CustomError> { - use crate::dbconfig::schema::podcasts::dsl::directory_id; - use crate::dbconfig::schema::podcasts::dsl::image_url as image_url_column; - use crate::dbconfig::schema::podcasts::dsl::podcasts as dsl_podcast; + use crate::adapters::persistence::dbconfig::schema::podcasts::dsl::directory_id; + use crate::adapters::persistence::dbconfig::schema::podcasts::dsl::image_url as image_url_column; + use crate::adapters::persistence::dbconfig::schema::podcasts::dsl::podcasts as dsl_podcast; let result = dsl_podcast .filter(directory_id.eq(id)) - .first::(conn) + .first::(&mut get_connection()) .optional() .expect("Error loading podcast episode by id"); match result { Some(..) => { diesel::update(dsl_podcast.filter(directory_id.eq(id))) .set(image_url_column.eq(image_url)) - .execute(conn) + .execute(&mut get_connection()) .map_err(map_db_error)?; Ok(()) } @@ -398,15 +391,14 @@ impl PodcastEpisode { pub fn check_if_downloaded( download_episode_url: &str, - conn: &mut DbConnection, ) -> Result { - use crate::dbconfig::schema::podcast_episodes::dsl::local_url as local_url_column; - use crate::dbconfig::schema::podcast_episodes::dsl::podcast_episodes as dsl_podcast_episodes; - use crate::dbconfig::schema::podcast_episodes::url as podcast_episode_url; + use crate::adapters::persistence::dbconfig::schema::podcast_episodes::dsl::local_url as local_url_column; + use crate::adapters::persistence::dbconfig::schema::podcast_episodes::dsl::podcast_episodes as dsl_podcast_episodes; + use crate::adapters::persistence::dbconfig::schema::podcast_episodes::url as podcast_episode_url; let result = dsl_podcast_episodes .filter(local_url_column.is_not_null()) .filter(podcast_episode_url.eq(download_episode_url)) - .first::(conn) + .first::(&mut get_connection()) .optional() .expect("Error loading podcast episode by id"); match result { @@ -427,9 +419,8 @@ impl PodcastEpisode { pub fn update_podcast_episode_status( download_url_of_episode: &str, status_to_insert: &str, - conn: &mut DbConnection, ) -> Result { - use crate::dbconfig::schema::podcast_episodes::dsl::*; + use crate::adapters::persistence::dbconfig::schema::podcast_episodes::dsl::*; let updated_podcast = diesel::update(podcast_episodes.filter(url.eq(download_url_of_episode))) @@ -437,35 +428,34 @@ impl PodcastEpisode { status.eq(status_to_insert), download_time.eq(Utc::now().naive_utc()), )) - .get_result::(conn) + .get_result::(&mut get_connection()) .expect("Error updating podcast episode"); Ok(updated_podcast) } - pub fn get_episodes(conn: &mut DbConnection) -> Vec { - use crate::dbconfig::schema::podcast_episodes::dsl::podcast_episodes as dsl_podcast_episodes; + pub fn get_episodes() -> Vec { + use crate::adapters::persistence::dbconfig::schema::podcast_episodes::dsl::podcast_episodes as dsl_podcast_episodes; dsl_podcast_episodes - .load::(conn) + .load::(&mut get_connection()) .expect("Error loading podcast episode by id") } pub fn get_podcast_episodes_older_than_days( days: i32, - conn: &mut DbConnection, podcast_id_to_search: i32, ) -> Vec { - use crate::dbconfig::schema::podcast_episodes::dsl::*; + use crate::adapters::persistence::dbconfig::schema::podcast_episodes::dsl::*; podcast_episodes .filter(download_time.lt(Utc::now().naive_utc() - Duration::days(days as i64))) .filter(podcast_id.eq(podcast_id_to_search)) - .load::(conn) + .load::(&mut get_connection()) .expect("Error loading podcast episode by id") } - pub fn update_download_status_of_episode(id_to_find: i32, conn: &mut DbConnection) { - use crate::dbconfig::schema::podcast_episodes::dsl::*; + pub fn update_download_status_of_episode(id_to_find: i32) { + use crate::adapters::persistence::dbconfig::schema::podcast_episodes::dsl::*; do_retry(|| { diesel::update(podcast_episodes.filter(id.eq(id_to_find))) .set(( @@ -476,47 +466,44 @@ impl PodcastEpisode { file_episode_path.eq(sql("NULL")), file_image_path.eq(sql("NULL")), )) - .get_result::(conn) + .get_result::(&mut get_connection()) }) .expect("Error updating podcast episode"); } pub fn get_episodes_by_podcast_id( id_to_search: i32, - conn: &mut DbConnection, ) -> Vec { - use crate::dbconfig::schema::podcast_episodes::dsl::*; + use crate::adapters::persistence::dbconfig::schema::podcast_episodes::dsl::*; podcast_episodes .filter(podcast_id.eq(id_to_search)) - .load::(conn) + .load::(&mut get_connection()) .expect("Error loading podcast episode by id") } pub fn update_guid( - conn: &mut DbConnection, guid_to_update: Guid, podcast_episode_id_to_update: &str, ) { - use crate::dbconfig::schema::podcast_episodes::dsl::episode_id as podcast_episode_id; - use crate::dbconfig::schema::podcast_episodes::dsl::*; + use crate::adapters::persistence::dbconfig::schema::podcast_episodes::dsl::episode_id as podcast_episode_id; + use crate::adapters::persistence::dbconfig::schema::podcast_episodes::dsl::*; diesel::update( podcast_episodes.filter(podcast_episode_id.eq(podcast_episode_id_to_update)), ) .set(guid.eq(guid_to_update.value)) - .execute(conn) + .execute(&mut get_connection()) .expect("Error updating guide"); } pub fn update_podcast_episode( - conn: &mut DbConnection, episode_to_update: PodcastEpisode, ) -> PodcastEpisode { - use crate::dbconfig::schema::podcast_episodes::dsl::*; + use crate::adapters::persistence::dbconfig::schema::podcast_episodes::dsl::*; diesel::update(podcast_episodes.find(episode_to_update.id)) .set(episode_to_update) - .get_result::(conn) + .get_result::(&mut get_connection()) .expect("Error updating podcast episode") } @@ -525,27 +512,25 @@ impl PodcastEpisode { local episode. Thus it should not be redownloaded with the scheduled download */ pub fn update_deleted( - conn: &mut DbConnection, episode_to_update: &str, deleted_status: bool, ) -> Result { - use crate::dbconfig::schema::podcast_episodes::dsl::*; + use crate::adapters::persistence::dbconfig::schema::podcast_episodes::dsl::*; diesel::update(podcast_episodes.filter(episode_id.eq(episode_to_update))) .set(deleted.eq(deleted_status)) - .execute(conn) + .execute(&mut get_connection()) .map_err(map_db_error) } pub fn get_podcast_episodes_by_podcast_to_k( - conn: &mut DbConnection, top_k: i32, ) -> Result, CustomError> { - use crate::dbconfig::schema::podcast_episodes as p_episode; - use crate::dbconfig::schema::podcast_episodes::dsl::podcast_id as podcast_id_column; - use crate::dbconfig::schema::podcast_episodes::dsl::*; - use crate::dbconfig::schema::podcasts::dsl::podcasts; - use crate::dbconfig::schema::podcasts::id as pod_id; + use crate::adapters::persistence::dbconfig::schema::podcast_episodes as p_episode; + use crate::adapters::persistence::dbconfig::schema::podcast_episodes::dsl::podcast_id as podcast_id_column; + use crate::adapters::persistence::dbconfig::schema::podcast_episodes::dsl::*; + use crate::adapters::persistence::dbconfig::schema::podcasts::dsl::podcasts; + use crate::adapters::persistence::dbconfig::schema::podcasts::id as pod_id; let (podcast_episode1, podcast_episode2) = diesel::alias!(p_episode as p1, p_episode as p2); podcast_episode1 @@ -560,15 +545,15 @@ impl PodcastEpisode { .limit(top_k.into()), ), ) - .load::(conn) + .load::(&mut get_connection()) .map_err(map_db_error) } pub fn update_episode_numbering_processed(conn: &mut DBType, processed: bool, episode_id_to_update: &str) { - use crate::dbconfig::schema::podcast_episodes::dsl::*; - use crate::dbconfig::schema::podcast_episodes::dsl::episode_numbering_processed as episode_numbering_processed_column; - use crate::dbconfig::schema::podcast_episodes::dsl::podcast_episodes as dsl_podcast_episodes; + use crate::adapters::persistence::dbconfig::schema::podcast_episodes::dsl::*; + use crate::adapters::persistence::dbconfig::schema::podcast_episodes::dsl::episode_numbering_processed as episode_numbering_processed_column; + use crate::adapters::persistence::dbconfig::schema::podcast_episodes::dsl::podcast_episodes as dsl_podcast_episodes; diesel::update(dsl_podcast_episodes) .set(episode_numbering_processed_column.eq(processed)) .filter(episode_id.eq(episode_id_to_update)) diff --git a/src/models/podcast_settings.rs b/src/models/podcast_settings.rs index 1b937897..fda7b09f 100644 --- a/src/models/podcast_settings.rs +++ b/src/models/podcast_settings.rs @@ -1,8 +1,8 @@ use diesel::{AsChangeset, Identifiable, Insertable, OptionalExtension, QueryDsl, Queryable, RunQueryDsl}; use utoipa::ToSchema; -use crate::DBType; +use crate::adapters::persistence::dbconfig::db::get_connection; use crate::utils::error::{map_db_error, CustomError}; -use crate::dbconfig::schema::podcast_settings; +use crate::adapters::persistence::dbconfig::schema::podcast_settings; use crate::models::file_path::FilenameBuilderReturn; use crate::models::podcast_episode::PodcastEpisode; use crate::models::podcasts::Podcast; @@ -55,14 +55,14 @@ pub struct PodcastSetting { impl PodcastSetting { - pub fn get_settings(conn: &mut DBType, id: i32) -> Result, + pub fn get_settings(id: i32) -> Result, CustomError> { - use crate::dbconfig::schema::podcast_settings::dsl::*; + use crate::adapters::persistence::dbconfig::schema::podcast_settings::dsl::*; use diesel::ExpressionMethods; podcast_settings .filter(podcast_id.eq(id)) - .first::(conn) + .first::(&mut get_connection()) .optional() .map_err(map_db_error) } @@ -74,28 +74,26 @@ impl PodcastSetting { pub fn update_settings( setting_to_insert: &PodcastSetting, - conn: &mut DBType, ) -> Result { - use crate::dbconfig::schema::podcast_settings::dsl::*; - let opt_setting = Self::get_settings(conn, setting_to_insert.podcast_id)?; + use crate::adapters::persistence::dbconfig::schema::podcast_settings::dsl::*; + let opt_setting = Self::get_settings(setting_to_insert.podcast_id)?; match opt_setting { Some(_) => { diesel::update(podcast_settings.find(setting_to_insert.podcast_id)) .set(setting_to_insert.clone()) - .execute(conn) + .execute(&mut get_connection()) .map_err(map_db_error)?; } None => { diesel::insert_into(podcast_settings) .values(setting_to_insert.clone()) - .execute(conn) + .execute(&mut get_connection()) .map_err(map_db_error)?; } } - let available_episodes = PodcastEpisode::get_episodes_by_podcast_id(setting_to_insert.podcast_id, - conn); - let podcast = Podcast::get_podcast(conn, setting_to_insert.podcast_id); + let available_episodes = PodcastEpisode::get_episodes_by_podcast_id(setting_to_insert.podcast_id); + let podcast = Podcast::get_podcast(setting_to_insert.podcast_id); if podcast.is_err() { return Err(CustomError::Conflict("Podcast not found".to_string())); } @@ -109,8 +107,7 @@ impl PodcastSetting { .local_image_url); let result = DownloadService::handle_metadata_insertion(&file_name_builder, &e .clone(), - &podcast, - conn); + &podcast); if result.is_err() { log::error!("Error while updating metadata for episode: {}", e.id); } diff --git a/src/models/podcasts.rs b/src/models/podcasts.rs index 71a2cae2..46f22e7b 100644 --- a/src/models/podcasts.rs +++ b/src/models/podcasts.rs @@ -1,4 +1,4 @@ -use crate::dbconfig::schema::*; +use crate::adapters::persistence::dbconfig::schema::*; use crate::models::favorites::Favorite; use crate::models::podcast_dto::PodcastDto; @@ -15,6 +15,7 @@ use diesel::{ delete, insert_into, BoolExpressionMethods, JoinOnDsl, OptionalExtension, RunQueryDsl, }; use utoipa::ToSchema; +use crate::adapters::persistence::dbconfig::db::get_connection; use crate::models::tag::Tag; use crate::utils::error::{map_db_error, CustomError}; @@ -63,54 +64,52 @@ pub struct Podcast { } impl Podcast { - pub fn find_by_rss_feed_url(conn: &mut DbConnection, feed_url: &str) -> Option { - use crate::dbconfig::schema::podcasts::dsl::*; + pub fn find_by_rss_feed_url(feed_url: &str) -> Option { + use crate::adapters::persistence::dbconfig::schema::podcasts::dsl::*; podcasts .filter(rssfeed.eq(feed_url)) - .first::(conn) + .first::(&mut get_connection()) .optional() .expect("Error loading podcast by rss feed url") } pub fn get_podcasts( - conn: &mut DbConnection, u: String, ) -> Result, CustomError> { - use crate::dbconfig::schema::favorites::dsl::favorites as f_db; - use crate::dbconfig::schema::favorites::dsl::podcast_id as f_id; - use crate::dbconfig::schema::favorites::dsl::username; - use crate::dbconfig::schema::podcasts::dsl::podcasts; - use crate::dbconfig::schema::podcasts::id as p_id; + use crate::adapters::persistence::dbconfig::schema::favorites::dsl::favorites as f_db; + use crate::adapters::persistence::dbconfig::schema::favorites::dsl::podcast_id as f_id; + use crate::adapters::persistence::dbconfig::schema::favorites::dsl::username; + use crate::adapters::persistence::dbconfig::schema::podcasts::dsl::podcasts; + use crate::adapters::persistence::dbconfig::schema::podcasts::id as p_id; let result = podcasts .left_join(f_db.on(username.eq(&u).and(f_id.eq(p_id)))) - .load::<(Podcast, Option)>(conn) + .load::<(Podcast, Option)>(&mut get_connection()) .map_err(map_db_error)?; let mapped_result = result .iter() .map(|podcast| { - let tags = Tag::get_tags_of_podcast(conn, podcast.0.id, &u).unwrap(); + let tags = Tag::get_tags_of_podcast(podcast.0.id, &u).unwrap(); MappingService::map_podcast_to_podcast_dto_with_favorites(podcast, tags) }) .collect::>(); Ok(mapped_result) } - pub fn get_all_podcasts(conn: &mut DbConnection) -> Result, CustomError> { - use crate::dbconfig::schema::podcasts::dsl::podcasts; - let result = podcasts.load::(conn).map_err(map_db_error)?; + pub fn get_all_podcasts() -> Result, CustomError> { + use crate::adapters::persistence::dbconfig::schema::podcasts::dsl::podcasts; + let result = podcasts.load::(&mut get_connection()).map_err(map_db_error)?; Ok(result) } pub fn get_podcast( - conn: &mut DbConnection, podcast_id_to_be_found: i32, ) -> Result { - use crate::dbconfig::schema::podcasts::dsl::podcasts; - use crate::dbconfig::schema::podcasts::id as podcast_id; + use crate::adapters::persistence::dbconfig::schema::podcasts::dsl::podcasts; + use crate::adapters::persistence::dbconfig::schema::podcasts::id as podcast_id; let found_podcast = podcasts .filter(podcast_id.eq(podcast_id_to_be_found)) - .first::(conn) + .first::(&mut get_connection()) .optional() .map_err(map_db_error)?; @@ -121,25 +120,23 @@ impl Podcast { } pub fn delete_podcast( - conn: &mut DbConnection, podcast_id_to_find: i32, ) -> Result<(), CustomError> { - use crate::dbconfig::schema::podcasts::dsl::*; + use crate::adapters::persistence::dbconfig::schema::podcasts::dsl::*; let _ = delete(podcasts.filter(id.eq(podcast_id_to_find))) - .execute(conn) + .execute(&mut get_connection()) .map_err(map_db_error)?; Ok(()) } pub fn get_podcast_by_track_id( - conn: &mut DbConnection, podcast_id: i32, ) -> Result, CustomError> { - use crate::dbconfig::schema::podcasts::directory_id; - use crate::dbconfig::schema::podcasts::dsl::podcasts; + use crate::adapters::persistence::dbconfig::schema::podcasts::directory_id; + use crate::adapters::persistence::dbconfig::schema::podcasts::dsl::podcasts; let optional_podcast = podcasts .filter(directory_id.eq(podcast_id.to_string())) - .first::(conn) + .first::(&mut get_connection()) .optional() .map_err(map_db_error)?; @@ -147,17 +144,16 @@ impl Podcast { } pub fn add_podcast_to_database( - conn: &mut DbConnection, collection_name: String, collection_id: String, feed_url: String, image_url_1: String, directory_name_to_insert: String, ) -> Result { - use crate::dbconfig::schema::podcasts::{ + use crate::adapters::persistence::dbconfig::schema::podcasts::{ directory_id, image_url, name as podcast_name, rssfeed, }; - use crate::dbconfig::schema::podcasts::{directory_name, original_image_url}; + use crate::adapters::persistence::dbconfig::schema::podcasts::{directory_name, original_image_url}; let inserted_podcast = insert_into(podcasts::table) .values(( @@ -168,7 +164,7 @@ impl Podcast { original_image_url.eq(image_url_1.to_string()), directory_name.eq(directory_name_to_insert.to_string()), )) - .get_result::(conn) + .get_result::(&mut get_connection()) .map_err(map_db_error)?; Ok(inserted_podcast) } @@ -177,7 +173,7 @@ impl Podcast { rss_feed_1: String, conn: &mut DbConnection, ) -> Result { - use crate::dbconfig::schema::podcasts::dsl::*; + use crate::adapters::persistence::dbconfig::schema::podcasts::dsl::*; podcasts .filter(rssfeed.eq(rss_feed_1)) @@ -189,8 +185,8 @@ impl Podcast { podcast_id: &str, conn: &mut DbConnection, ) -> Result, CustomError> { - use crate::dbconfig::schema::podcasts::dsl::directory_id; - use crate::dbconfig::schema::podcasts::dsl::podcasts as dsl_podcast; + use crate::adapters::persistence::dbconfig::schema::podcasts::dsl::directory_id; + use crate::adapters::persistence::dbconfig::schema::podcasts::dsl::podcasts as dsl_podcast; let result = dsl_podcast .filter(directory_id.eq(podcast_id)) .first::(conn) @@ -201,25 +197,23 @@ impl Podcast { pub fn query_for_podcast( query: &str, - conn: &mut DbConnection, ) -> Result, CustomError> { - use crate::dbconfig::schema::podcast_episodes::dsl::*; + use crate::adapters::persistence::dbconfig::schema::podcast_episodes::dsl::*; use diesel::TextExpressionMethods; let result = podcast_episodes .filter( name.like(format!("%{}%", query)) .or(description.like(format!("%{}%", query))), ) - .load::(conn) + .load::(&mut get_connection()) .map_err(map_db_error)?; Ok(result) } pub fn update_podcast_fields( podcast_extra: PodcastExtra, - conn: &mut DbConnection, ) -> Result { - use crate::dbconfig::schema::podcasts::dsl::*; + use crate::adapters::persistence::dbconfig::schema::podcasts::dsl::*; do_retry(|| { diesel::update(podcasts) @@ -232,22 +226,21 @@ impl Podcast { summary.eq(podcast_extra.clone().description), last_build_date.eq(podcast_extra.clone().last_build_date), )) - .execute(conn) + .execute(&mut get_connection()) }) .map_err(map_db_error) } pub fn update_podcast_active( - conn: &mut DbConnection, podcast_id: i32, ) -> Result<(), CustomError> { - use crate::dbconfig::schema::podcasts::dsl::*; + use crate::adapters::persistence::dbconfig::schema::podcasts::dsl::*; - let found_podcast = Podcast::get_podcast(conn, podcast_id)?; + let found_podcast = Podcast::get_podcast(podcast_id)?; diesel::update(podcasts.filter(id.eq(podcast_id))) .set(active.eq(!found_podcast.active)) - .execute(conn) + .execute(&mut get_connection()) .map_err(map_db_error)?; Ok(()) } @@ -255,13 +248,12 @@ impl Podcast { pub fn update_original_image_url( original_image_url_to_set: &str, podcast_id_to_find: i32, - conn: &mut DbConnection, ) -> Result<(), CustomError> { - use crate::dbconfig::schema::podcasts::dsl::*; + use crate::adapters::persistence::dbconfig::schema::podcasts::dsl::*; do_retry(|| { diesel::update(podcasts.filter(id.eq(podcast_id_to_find))) .set(original_image_url.eq(original_image_url_to_set)) - .execute(conn) + .execute(&mut get_connection()) }) .map_err(map_db_error)?; Ok(()) @@ -270,14 +262,13 @@ impl Podcast { pub fn update_podcast_urls_on_redirect( podcast_id_to_update: i32, new_url: String, - conn: &mut DbConnection, ) { - use crate::dbconfig::schema::podcasts::dsl::id as pid; - use crate::dbconfig::schema::podcasts::dsl::*; + use crate::adapters::persistence::dbconfig::schema::podcasts::dsl::id as pid; + use crate::adapters::persistence::dbconfig::schema::podcasts::dsl::*; diesel::update(podcasts.filter(pid.eq(podcast_id_to_update))) .set(rssfeed.eq(new_url)) - .execute(conn) + .execute(&mut get_connection()) .expect("Error updating podcast episode"); } } diff --git a/src/models/session.rs b/src/models/session.rs index af13ff54..6591d35b 100644 --- a/src/models/session.rs +++ b/src/models/session.rs @@ -1,4 +1,4 @@ -use crate::dbconfig::schema::sessions; +use crate::adapters::persistence::dbconfig::schema::sessions; use crate::utils::error::{map_db_error, CustomError}; use crate::{execute_with_conn, DBType as DbConnection}; use chrono::{DateTime, NaiveDateTime, Utc}; @@ -7,6 +7,7 @@ use diesel::QueryDsl; use diesel::{Insertable, Queryable, RunQueryDsl}; use utoipa::ToSchema; use uuid::Uuid; +use crate::adapters::persistence::dbconfig::db::get_connection; #[derive(Queryable, Insertable, Clone, ToSchema, PartialEq, Debug)] pub struct Session { @@ -26,8 +27,8 @@ impl Session { } #[allow(clippy::redundant_closure_call)] - pub fn insert_session(&self, conn: &mut DbConnection) -> Result { - execute_with_conn!(conn, |conn| diesel::insert_into(sessions::table) + pub fn insert_session(&self) -> Result { + execute_with_conn!(|conn| diesel::insert_into(sessions::table) .values(self) .get_result(conn) .map_err(map_db_error)) @@ -39,18 +40,16 @@ impl Session { } pub fn find_by_session_id( - session_id: &str, - conn: &mut DbConnection, + session_id: &str ) -> Result { sessions::table .filter(sessions::session_id.eq(session_id)) - .get_result(conn) + .get_result(&mut get_connection()) } pub fn delete_by_username( - username1: &str, - conn: &mut DbConnection, + username1: &str ) -> Result { - diesel::delete(sessions::table.filter(sessions::username.eq(username1))).execute(conn) + diesel::delete(sessions::table.filter(sessions::username.eq(username1))).execute(&mut get_connection()) } } diff --git a/src/models/settings.rs b/src/models/settings.rs index 7cbad1c5..4c79c595 100644 --- a/src/models/settings.rs +++ b/src/models/settings.rs @@ -1,13 +1,13 @@ use crate::constants::inner_constants::DEFAULT_SETTINGS; -use crate::dbconfig::schema::*; +use crate::adapters::persistence::dbconfig::schema::*; use crate::service::environment_service::OidcConfig; use crate::utils::do_retry::do_retry; use crate::utils::error::{map_db_error, CustomError}; -use crate::DBType as DbConnection; use diesel::insert_into; use diesel::prelude::{AsChangeset, Identifiable, Insertable, Queryable}; use diesel::{OptionalExtension, RunQueryDsl}; use utoipa::ToSchema; +use crate::adapters::persistence::dbconfig::db::get_connection; #[derive( Serialize, @@ -51,33 +51,32 @@ pub struct ConfigModel { } impl Setting { - pub fn get_settings(conn: &mut DbConnection) -> Result, CustomError> { - use crate::dbconfig::schema::settings::dsl::*; + pub fn get_settings() -> Result, CustomError> { + use crate::adapters::persistence::dbconfig::schema::settings::dsl::*; settings - .first::(conn) + .first::(&mut get_connection()) .optional() .map_err(map_db_error) } pub fn update_settings( setting: Setting, - conn: &mut DbConnection, ) -> Result { - use crate::dbconfig::schema::settings::dsl::*; + use crate::adapters::persistence::dbconfig::schema::settings::dsl::*; let setting_to_update = settings - .first::(conn) + .first::(&mut get_connection()) .expect("Error loading settings"); do_retry(|| { diesel::update(&setting_to_update) .set(setting.clone()) - .get_result::(conn) + .get_result::(&mut get_connection()) }) .map_err(map_db_error) } - pub fn insert_default_settings(conn: &mut DbConnection) -> Result<(), CustomError> { - use crate::dbconfig::schema::settings::dsl::*; + pub fn insert_default_settings() -> Result<(), CustomError> { + use crate::adapters::persistence::dbconfig::schema::settings::dsl::*; use diesel::ExpressionMethods; do_retry(|| { insert_into(settings) @@ -89,7 +88,7 @@ impl Setting { auto_cleanup_days.eq(DEFAULT_SETTINGS.auto_cleanup_days), podcast_prefill.eq(DEFAULT_SETTINGS.podcast_prefill), )) - .execute(conn) + .execute(&mut get_connection()) }) .map_err(map_db_error)?; Ok(()) diff --git a/src/models/subscription.rs b/src/models/subscription.rs index f6e65acb..73817a78 100644 --- a/src/models/subscription.rs +++ b/src/models/subscription.rs @@ -5,7 +5,7 @@ use diesel::ExpressionMethods; use diesel::{BoolExpressionMethods, QueryDsl, RunQueryDsl}; use std::io::Error; -use crate::dbconfig::schema::subscriptions; +use crate::adapters::persistence::dbconfig::schema::subscriptions; use crate::utils::time::get_current_timestamp; use crate::DBType as DbConnection; use diesel::sql_types::{Integer, Nullable, Text, Timestamp}; @@ -13,6 +13,7 @@ use diesel::OptionalExtension; use diesel::{AsChangeset, Insertable, Queryable, QueryableByName}; use serde::{Deserialize, Serialize}; use utoipa::ToSchema; +use crate::adapters::persistence::dbconfig::db::get_connection; #[derive( Debug, @@ -53,7 +54,7 @@ impl Subscription { } } pub fn delete_by_username(username1: &str, conn: &mut DbConnection) -> Result<(), Error> { - use crate::dbconfig::schema::subscriptions::dsl::*; + use crate::adapters::persistence::dbconfig::schema::subscriptions::dsl::*; diesel::delete(subscriptions.filter(username.eq(username1))) .execute(conn) .expect("Error deleting subscriptions of user"); @@ -73,7 +74,6 @@ impl SubscriptionChangesToClient { device_id: &str, username: &str, since: i32, - conn: &mut DbConnection, ) -> Result { let since = DateTime::from_timestamp(since as i64, 0).map(|v|v.naive_utc()).unwrap(); let res: Vec = subscriptions::table @@ -83,7 +83,7 @@ impl SubscriptionChangesToClient { .eq(device_id) .and(subscriptions::created.gt(since)), ) - .load::(conn) + .load::(&mut get_connection()) .expect("Error retrieving changed subscriptions"); let (deleted_subscriptions, created_subscriptions): (Vec, Vec) = @@ -106,10 +106,9 @@ impl SubscriptionChangesToClient { device_id: &str, username: &str, upload_request: web::Json, - conn: &mut DbConnection, ) -> Result>, Error> { - use crate::dbconfig::schema::subscriptions::dsl as dsl_types; - use crate::dbconfig::schema::subscriptions::dsl::subscriptions; + use crate::adapters::persistence::dbconfig::schema::subscriptions::dsl as dsl_types; + use crate::adapters::persistence::dbconfig::schema::subscriptions::dsl::subscriptions; let mut rewritten_urls: Vec> = vec![vec![]]; // Add subscriptions upload_request.clone().add.iter().for_each(|c| { @@ -122,7 +121,6 @@ impl SubscriptionChangesToClient { username.to_string(), device_id.to_string(), c.to_string(), - conn, ) .expect( "Error retrieving \ @@ -132,7 +130,7 @@ impl SubscriptionChangesToClient { Some(s) => { diesel::update(subscriptions.filter(dsl_types::id.eq(s.id))) .set(dsl_types::deleted.eq(None::)) - .execute(conn) + .execute(&mut get_connection()) .unwrap(); } None => { @@ -148,7 +146,7 @@ impl SubscriptionChangesToClient { dsl_types::podcast.eq(subscription.podcast), dsl_types::created.eq(subscription.created), )) - .execute(conn) + .execute(&mut get_connection()) .unwrap(); } } @@ -162,7 +160,6 @@ impl SubscriptionChangesToClient { username.to_string(), device_id.to_string(), c.to_string(), - conn, ) .expect( "Error retrieving \ @@ -171,7 +168,7 @@ impl SubscriptionChangesToClient { if let Some(s) = opt_sub { diesel::update(subscriptions.filter(dsl_types::id.eq(s.id))) .set(dsl_types::deleted.eq(Some(Utc::now().naive_utc()))) - .execute(conn) + .execute(&mut get_connection()) .unwrap(); } }); @@ -183,9 +180,8 @@ impl SubscriptionChangesToClient { username_1: String, deviceid_1: String, podcast_1: String, - conn: &mut DbConnection, ) -> Result, Error> { - use crate::dbconfig::schema::subscriptions::dsl::*; + use crate::adapters::persistence::dbconfig::schema::subscriptions::dsl::*; let res = subscriptions .filter( @@ -194,7 +190,7 @@ impl SubscriptionChangesToClient { .and(device.eq(deviceid_1)) .and(podcast.eq(podcast_1)), ) - .first::(conn) + .first::(&mut get_connection()) .optional() .expect("Error retrieving subscription"); diff --git a/src/models/tag.rs b/src/models/tag.rs index ffba8c9f..283cf3ef 100644 --- a/src/models/tag.rs +++ b/src/models/tag.rs @@ -1,11 +1,10 @@ use chrono::{NaiveDateTime, Utc}; use diesel::{AsChangeset, Insertable, JoinOnDsl, OptionalExtension, Queryable, QueryableByName, RunQueryDsl, Table}; use utoipa::ToSchema; -use crate::dbconfig::DBType as DbConnection; use crate::utils::error::{CustomError, map_db_error}; use diesel::sql_types::{Text,Nullable, Timestamp }; - -use crate::dbconfig::schema::tags; +use crate::adapters::persistence::dbconfig::db::get_connection; +use crate::adapters::persistence::dbconfig::schema::tags; use crate::execute_with_conn; #[derive( @@ -47,9 +46,11 @@ impl Tag { } } - pub fn insert_tag(&self, conn: &mut DbConnection) -> Result { - use crate::dbconfig::schema::tags::dsl::*; - execute_with_conn!(conn, + pub fn insert_tag(&self) -> Result { + use crate::adapters::persistence::dbconfig::schema::tags::dsl::*; + + + execute_with_conn!( |conn|diesel::insert_into(tags) .values(self) .get_result(conn) @@ -57,58 +58,58 @@ impl Tag { ) } - pub fn delete_tag(conn: &mut DbConnection, tag_id: &str) -> Result<(), CustomError> { - use crate::dbconfig::schema::tags::dsl::*; + pub fn delete_tag(tag_id: &str) -> Result<(), CustomError> { + use crate::adapters::persistence::dbconfig::schema::tags::dsl::*; use diesel::QueryDsl; use diesel::ExpressionMethods; diesel::delete(tags.filter(id.eq(tag_id))) - .execute(conn) + .execute(&mut get_connection()) .map_err(map_db_error)?; Ok(()) } - pub fn get_tag_by_id_and_username(conn: &mut DbConnection, tag_id: &str, username_to_search: + pub fn get_tag_by_id_and_username(tag_id: &str, username_to_search: &str) -> Result, CustomError> { - use crate::dbconfig::schema::tags::dsl::*; + use crate::adapters::persistence::dbconfig::schema::tags::dsl::*; use diesel::QueryDsl; use diesel::ExpressionMethods; tags.filter(id.eq(tag_id)) .filter(username.eq(username_to_search)) - .first::(conn) + .first::(&mut get_connection()) .optional() .map_err(map_db_error) } - pub fn update_tag(conn: &mut DbConnection, tag_id: &str, name_new: String, description_new: Option, color_new: String) -> Result { - use crate::dbconfig::schema::tags::dsl::*; + pub fn update_tag(tag_id: &str, name_new: String, description_new: Option, color_new: String) -> Result { + use crate::adapters::persistence::dbconfig::schema::tags::dsl::*; use diesel::QueryDsl; use diesel::ExpressionMethods; diesel::update(tags.filter(id.eq(tag_id))) .set((name.eq(name_new), description.eq(description_new), color.eq(color_new))) - .get_result::(conn) + .get_result::(&mut get_connection()) .map_err(map_db_error) } - pub fn get_tags(conn: &mut DbConnection, username_to_search: String) -> Result, CustomError> { - use crate::dbconfig::schema::tags::dsl::*; + pub fn get_tags(username_to_search: String) -> Result, CustomError> { + use crate::adapters::persistence::dbconfig::schema::tags::dsl::*; use diesel::QueryDsl; use diesel::ExpressionMethods; tags .filter(username.eq(username_to_search)) - .load::(conn) + .load::(&mut get_connection()) .map_err(map_db_error) } - pub fn get_tags_of_podcast(conn: &mut DbConnection, podcast_id_to_search: i32, + pub fn get_tags_of_podcast(podcast_id_to_search: i32, username_to_search: &str) -> Result, CustomError> { - use crate::dbconfig::schema::tags::dsl::*; - use crate::dbconfig::schema::tags_podcasts::dsl::*; - use crate::dbconfig::schema::tags_podcasts::table as t_podcasts; - use crate::dbconfig::schema::tags_podcasts::dsl as t_podcasts_dsl; + use crate::adapters::persistence::dbconfig::schema::tags::dsl::*; + use crate::adapters::persistence::dbconfig::schema::tags_podcasts::dsl::*; + use crate::adapters::persistence::dbconfig::schema::tags_podcasts::table as t_podcasts; + use crate::adapters::persistence::dbconfig::schema::tags_podcasts::dsl as t_podcasts_dsl; use diesel::QueryDsl; use diesel::ExpressionMethods; @@ -117,7 +118,7 @@ impl Tag { .select(tags::all_columns()) .filter(podcast_id.eq(podcast_id_to_search)) .filter(username.eq(username_to_search)) - .load::(conn) + .load::(&mut get_connection()) .map_err(map_db_error) } } diff --git a/src/models/tags_podcast.rs b/src/models/tags_podcast.rs index 125e1dcb..0f809be9 100644 --- a/src/models/tags_podcast.rs +++ b/src/models/tags_podcast.rs @@ -1,7 +1,6 @@ use diesel::{AsChangeset, Insertable, Queryable, QueryableByName}; use utoipa::ToSchema; -use crate::dbconfig::DBType as DbConnection; -use crate::dbconfig::schema::tags_podcasts; +use crate::adapters::persistence::dbconfig::schema::tags_podcasts; use crate::{execute_with_conn, insert_with_conn}; use crate::utils::error::{CustomError, map_db_error}; @@ -22,60 +21,59 @@ pub struct TagsPodcast { podcast_id: i32 } - impl TagsPodcast { - pub fn add_podcast_to_tag(tag_id_to_insert: String, podcast_id_to_insert: i32, conn: &mut DbConnection) -> + pub fn add_podcast_to_tag(tag_id_to_insert: String, podcast_id_to_insert: i32) -> Result { -use crate::dbconfig::schema::tags_podcasts::dsl::*; +use crate::adapters::persistence::dbconfig::schema::tags_podcasts::dsl::*; use diesel::RunQueryDsl; let new_tag_podcast = TagsPodcast { tag_id: tag_id_to_insert, podcast_id: podcast_id_to_insert }; - execute_with_conn!(conn, |conn| diesel::insert_into(tags_podcasts) + + execute_with_conn!(|conn| diesel::insert_into(tags_podcasts) .values(&new_tag_podcast) .get_result(conn) .map_err(map_db_error)) } - pub fn delete_tags_by_podcast_id(conn: &mut DbConnection, podcast_id_to_delete: i32) -> Result<(), + pub fn delete_tags_by_podcast_id(podcast_id_to_delete: i32) -> Result<(), CustomError> { - use crate::dbconfig::schema::tags_podcasts::dsl::*; - use crate::dbconfig::schema::tags_podcasts::table as t_podcasts; + use crate::adapters::persistence::dbconfig::schema::tags_podcasts::dsl::*; + use crate::adapters::persistence::dbconfig::schema::tags_podcasts::table as t_podcasts; use diesel::RunQueryDsl; use diesel::ExpressionMethods; use diesel::QueryDsl; - let _ = insert_with_conn!(conn, |conn| diesel::delete(t_podcasts.filter(podcast_id.eq(podcast_id_to_delete))) + insert_with_conn!(|conn| diesel::delete(t_podcasts.filter(podcast_id.eq(podcast_id_to_delete))) .execute(conn) .map_err(map_db_error)); Ok(()) } - pub fn delete_tag_podcasts(conn: &mut DbConnection, tag_id_to_delete: &str) -> Result<(), + pub fn delete_tag_podcasts(tag_id_to_delete: &str) -> Result<(), CustomError> { - use crate::dbconfig::schema::tags_podcasts::dsl::*; - use crate::dbconfig::schema::tags_podcasts::table as t_podcasts; + use crate::adapters::persistence::dbconfig::schema::tags_podcasts::dsl::*; + use crate::adapters::persistence::dbconfig::schema::tags_podcasts::table as t_podcasts; use diesel::RunQueryDsl; use diesel::ExpressionMethods; use diesel::QueryDsl; - let _ = insert_with_conn!(conn, |conn| diesel::delete(t_podcasts.filter(tag_id.eq(tag_id_to_delete))) + insert_with_conn!(|conn| diesel::delete(t_podcasts.filter(tag_id.eq(tag_id_to_delete))) .execute(conn) .map_err(map_db_error)); Ok(()) } - pub fn delete_tag_podcasts_by_podcast_id_tag_id(conn: &mut DbConnection, - podcast_id_to_delete: i32, tag_id_key: &str) -> + pub fn delete_tag_podcasts_by_podcast_id_tag_id(podcast_id_to_delete: i32, tag_id_key: &str) -> Result<(), CustomError> { - use crate::dbconfig::schema::tags_podcasts::dsl::*; - use crate::dbconfig::schema::tags_podcasts::table as t_podcasts; + use crate::adapters::persistence::dbconfig::schema::tags_podcasts::dsl::*; + use crate::adapters::persistence::dbconfig::schema::tags_podcasts::table as t_podcasts; use diesel::RunQueryDsl; use diesel::ExpressionMethods; use diesel::QueryDsl; use diesel::BoolExpressionMethods; - let _ = insert_with_conn!(conn, |conn| diesel::delete(t_podcasts.filter(podcast_id.eq + insert_with_conn!(|conn| diesel::delete(t_podcasts.filter(podcast_id.eq (podcast_id_to_delete).and(tag_id.eq(tag_id_key)))) .execute(conn) .map_err(map_db_error)); diff --git a/src/models/user.rs b/src/models/user.rs index c44bebf1..76f5bc73 100644 --- a/src/models/user.rs +++ b/src/models/user.rs @@ -1,6 +1,5 @@ use crate::constants::inner_constants::{Role, BASIC_AUTH, ENVIRONMENT_SERVICE, OIDC_AUTH, STANDARD_USER, USERNAME}; -use crate::dbconfig::schema::users; -use crate::dbconfig::DBType; +use crate::adapters::persistence::dbconfig::schema::users; use crate::utils::environment_variables::is_env_var_present_and_true; use crate::utils::error::{map_db_error, CustomError}; use crate::DBType as DbConnection; @@ -13,6 +12,7 @@ use diesel::QueryDsl; use diesel::{AsChangeset, OptionalExtension, RunQueryDsl}; use std::io::Error; use utoipa::ToSchema; +use crate::adapters::persistence::dbconfig::db::get_connection; #[derive( Serialize, Deserialize, Queryable, Insertable, Clone, ToSchema, PartialEq, Debug, AsChangeset, @@ -71,9 +71,8 @@ impl User { pub fn find_by_username( username_to_find: &str, - conn: &mut DbConnection, ) -> Result { - use crate::dbconfig::schema::users::dsl::*; + use crate::adapters::persistence::dbconfig::schema::users::dsl::*; let env_service = ENVIRONMENT_SERVICE.get().unwrap(); if let Some(res) = env_service.username.clone() { if res == username_to_find { @@ -83,7 +82,7 @@ impl User { let opt_user = users .filter(username.eq(username_to_find)) - .first::(conn) + .first::(&mut get_connection()) .optional() .map_err(map_db_error)?; if let Some(user) = opt_user { @@ -93,8 +92,8 @@ impl User { } } - pub fn insert_user(&mut self, conn: &mut DbConnection) -> Result { - use crate::dbconfig::schema::users::dsl::*; + pub fn insert_user(&mut self) -> Result { + use crate::adapters::persistence::dbconfig::schema::users::dsl::*; let env_service = ENVIRONMENT_SERVICE.get().unwrap(); if let Some(res) = env_service.username.clone() { if res == self.username { @@ -112,35 +111,33 @@ impl User { password.eq(self.password.clone()), created_at.eq(chrono::Utc::now().naive_utc()), )) - .get_result::(conn) + .get_result::(&mut get_connection()) .unwrap(); Ok(res) } - pub fn delete_user(&self, conn: &mut DbConnection) -> Result { + pub fn delete_user(&self) -> Result { diesel::delete(users::table.filter(users::id.eq(self.id))) - .execute(conn) + .execute(&mut get_connection()) .map_err(map_db_error) } pub fn update_role( &self, - conn: &mut DbConnection, ) -> Result { let user = diesel::update(users::table.filter(users::id.eq(self.id))) .set(users::role.eq(self.role.clone())) - .get_result::(conn); + .get_result::(&mut get_connection()); Ok(User::map_to_dto(user.unwrap())) } pub fn update_explicit_consent( &self, - conn: &mut DbConnection, ) -> Result { let user = diesel::update(users::table.filter(users::id.eq(self.id))) .set(users::explicit_consent.eq(self.explicit_consent)) - .get_result::(conn); + .get_result::(&mut get_connection()); Ok(User::map_to_dto(user?)) } @@ -196,7 +193,7 @@ impl User { } pub fn find_all_users(conn: &mut DbConnection) -> Vec { - use crate::dbconfig::schema::users::dsl::*; + use crate::adapters::persistence::dbconfig::schema::users::dsl::*; let loaded_users = users.load::(conn).unwrap(); loaded_users.into_iter().map(User::map_to_dto).collect() @@ -231,10 +228,9 @@ impl User { pub fn check_if_admin_or_uploader( username: &Option, - conn: &mut DbConnection, ) -> Result, CustomError> { if let Some(username) = username { - let found_user = User::find_by_username(username, conn)?; + let found_user = User::find_by_username(username)?; if found_user.role.ne(&Role::Admin.to_string()) && found_user.role.ne(&Role::Uploader.to_string()) { @@ -246,10 +242,9 @@ impl User { pub fn check_if_admin( username: &Option, - conn: &mut DbConnection, ) -> Result<(), CustomError> { if let Some(username_unwrapped) = username { - let found_user = User::find_by_username(username_unwrapped, conn)?; + let found_user = User::find_by_username(username_unwrapped)?; if found_user.role != Role::Admin.to_string() { return Err(CustomError::Forbidden); @@ -263,18 +258,18 @@ impl User { username_to_search: String, conn: &mut DbConnection, ) -> Result<(), CustomError> { - use crate::dbconfig::schema::users::dsl::*; + use crate::adapters::persistence::dbconfig::schema::users::dsl::*; diesel::delete(users.filter(username.eq(username_to_search))) .execute(conn) .map_err(map_db_error)?; Ok(()) } - pub fn update_user(user: User, conn: &mut DbConnection) -> Result { - use crate::dbconfig::schema::users::dsl::*; + pub fn update_user(user: User) -> Result { + use crate::adapters::persistence::dbconfig::schema::users::dsl::*; diesel::update(users.filter(id.eq(user.clone().id))) .set(user) - .get_result(conn) + .get_result(&mut get_connection()) .map_err(map_db_error) } @@ -282,11 +277,11 @@ impl User { self.role.eq(&Role::Admin.to_string()) || self.role.eq(&Role::Uploader.to_string()) } - pub fn get_user_by_userid(user_id: i32, conn: &mut DbConnection) -> Result { - use crate::dbconfig::schema::users::dsl::*; + pub fn get_user_by_userid(user_id: i32) -> Result { + use crate::adapters::persistence::dbconfig::schema::users::dsl::*; let user = users .filter(id.eq(user_id)) - .first::(conn) + .first::(&mut get_connection()) .optional() .map_err(map_db_error)?; if user.is_none() { @@ -301,13 +296,12 @@ impl User { pub fn find_by_api_key( api_key_to_find: String, - conn: &mut DBType, ) -> Result, CustomError> { - use crate::dbconfig::schema::users::dsl::*; + use crate::adapters::persistence::dbconfig::schema::users::dsl::*; users .filter(api_key.eq(api_key_to_find)) - .first::(conn) + .first::(&mut get_connection()) .optional() .map_err(map_db_error) } @@ -315,19 +309,18 @@ impl User { pub fn update_api_key_of_user( username_to_update: &str, api_key_to_update: String, - conn: &mut DBType, ) -> Result<(), CustomError> { - use crate::dbconfig::schema::users::dsl::*; + use crate::adapters::persistence::dbconfig::schema::users::dsl::*; diesel::update(users.filter(username.eq(username_to_update))) .set(api_key.eq(api_key_to_update)) - .execute(conn) + .execute(&mut get_connection()) .map_err(map_db_error)?; Ok(()) } - pub fn check_if_api_key_exists(api_key_to_find: String, conn: &mut DBType) -> bool { + pub fn check_if_api_key_exists(api_key_to_find: String) -> bool { if api_key_to_find.is_empty() { return false; } @@ -341,7 +334,7 @@ impl User { } } - let result = Self::find_by_api_key(api_key_to_find, conn); + let result = Self::find_by_api_key(api_key_to_find); match result { Ok(user) => { diff --git a/src/service/download_service.rs b/src/service/download_service.rs index a123744d..53f5c7e8 100644 --- a/src/service/download_service.rs +++ b/src/service/download_service.rs @@ -10,10 +10,8 @@ use reqwest::header::{HeaderMap, HeaderValue}; use std::io; use std::io::Read; use file_format::FileFormat; - -use crate::config::dbconfig::establish_connection; +use crate::adapters::persistence::dbconfig::db::get_connection; use crate::constants::inner_constants::{COMMON_USER_AGENT, DEFAULT_IMAGE_URL, PODCAST_FILENAME, PODCAST_IMAGENAME}; -use crate::dbconfig::DBType; use crate::get_default_image; use crate::models::file_path::{FilenameBuilder, FilenameBuilderReturn}; use crate::models::podcast_settings::PodcastSetting; @@ -40,9 +38,9 @@ impl DownloadService { podcast: Podcast ) -> Result<(), CustomError> { let client = ClientBuilder::new().build().unwrap(); - let conn = &mut establish_connection(); + let conn = &mut get_connection(); let suffix = determine_file_extension(&podcast_episode.url, &client, FileType::Audio); - let settings_in_db = Setting::get_settings(conn)?.unwrap(); + let settings_in_db = Setting::get_settings()?.unwrap(); let image_suffix = determine_file_extension(&podcast_episode.image_url, &client, FileType::Image); @@ -90,17 +88,17 @@ impl DownloadService { .with_podcast(podcast.clone()) .with_suffix(&suffix) .with_settings(settings_in_db) - .with_episode(podcast_episode.clone(), conn)? + .with_episode(podcast_episode.clone())? .with_filename(PODCAST_FILENAME) .with_image_filename(PODCAST_IMAGENAME) .with_image_suffix(&image_suffix) - .with_raw_directory(conn)? + .with_raw_directory()? .build(conn)?, false => FilenameBuilder::default() .with_suffix(&suffix) .with_settings(settings_in_db) .with_image_suffix(&image_suffix) - .with_episode(podcast_episode.clone(), conn)? + .with_episode(podcast_episode.clone())? .with_podcast_directory(&podcast.directory_name) .with_podcast(podcast.clone()) .with_image_filename(PODCAST_IMAGENAME) @@ -130,25 +128,26 @@ impl DownloadService { conn, )?; io::copy(&mut image_response, &mut image_out).expect("failed to copy content"); - Self::handle_metadata_insertion(&paths, &podcast_episode, &podcast, conn)?; + let result = Self::handle_metadata_insertion(&paths, &podcast_episode, &podcast); + if let Err(err) = result { + log::error!("Error handling metadata insertion: {:?}", err); + } Ok(()) } - pub fn handle_metadata_insertion(paths: &FilenameBuilderReturn, podcast_episode: - &PodcastEpisode, podcast: &Podcast, conn: &mut DBType) -> Result<(), CustomError> { + pub fn handle_metadata_insertion(paths: &FilenameBuilderReturn, podcast_episode: &PodcastEpisode, podcast: &Podcast) -> Result<(), CustomError> { let detected_file = FileFormat::from_file(&paths.filename).unwrap(); match detected_file { FileFormat::Mpeg12AudioLayer3 => { - let result_of_update = Self::update_meta_data_mp3(paths, podcast_episode, podcast, - conn); + let result_of_update = Self::update_meta_data_mp3(paths, podcast_episode, podcast); if let Some(err) = result_of_update.err() { log::error!("Error updating metadata: {:?}", err); } }, FileFormat::AppleItunesAudio =>{ - let result_of_itunes = Self::update_meta_data_mp4(paths, podcast_episode, podcast, - conn); + let result_of_itunes = Self::update_meta_data_mp4(paths, podcast_episode, + podcast); if let Some(err) = result_of_itunes.err() { log::error!("Error updating metadata: {:?}", err); } @@ -165,8 +164,7 @@ impl DownloadService { fn update_meta_data_mp3( paths: &FilenameBuilderReturn, podcast_episode: &PodcastEpisode, - podcast: &Podcast, - conn: &mut DBType, + podcast: &Podcast ) -> Result<(), CustomError> { let mut tag = match Tag::read_from_path(&paths.filename) { Ok(tag) => tag, @@ -193,27 +191,28 @@ impl DownloadService { }); } + let mut conn = get_connection(); let index = PodcastEpisode::get_position_of_episode(&podcast_episode.date_of_recording, podcast_episode.podcast_id, - conn)?; + &mut conn)?; - let settings_for_podcast = PodcastSetting::get_settings(conn, podcast.id)?; + let settings_for_podcast = PodcastSetting::get_settings(podcast.id)?; if let Some(settings_for_podcast) = settings_for_podcast { if settings_for_podcast.episode_numbering { if !podcast_episode.episode_numbering_processed { tag.set_title(format!("{} - {}", index, &podcast_episode.name)); - PodcastEpisode::update_episode_numbering_processed(conn, true, + PodcastEpisode::update_episode_numbering_processed(&mut conn, true, &podcast_episode.episode_id); } } else { tag.set_title(&podcast_episode.name); - PodcastEpisode::update_episode_numbering_processed(conn, false, &podcast_episode + PodcastEpisode::update_episode_numbering_processed(&mut conn, false, &podcast_episode .episode_id) } } else { tag.set_title(&podcast_episode.name); - PodcastEpisode::update_episode_numbering_processed(conn, false, &podcast_episode + PodcastEpisode::update_episode_numbering_processed(&mut conn, false, &podcast_episode .episode_id) } @@ -246,7 +245,6 @@ impl DownloadService { } let track_number = PodcastEpisodeService::get_track_number_for_episode( - conn, podcast.id, &podcast_episode.date_of_recording, ); @@ -273,7 +271,6 @@ impl DownloadService { paths: &FilenameBuilderReturn, podcast_episode: &PodcastEpisode, podcast: &Podcast, - conn: &mut DBType, ) -> Result<(), CustomError> { let tag = mp4ameta::Tag::read_from_path(&paths.filename); match tag { @@ -287,7 +284,6 @@ impl DownloadService { tag.set_comment(&podcast_episode.description); let track_number = PodcastEpisodeService::get_track_number_for_episode( - conn, podcast.id, &podcast_episode.date_of_recording, ); diff --git a/src/service/file_service.rs b/src/service/file_service.rs index 4b3917e9..f80a5806 100644 --- a/src/service/file_service.rs +++ b/src/service/file_service.rs @@ -7,13 +7,12 @@ use std::io::{Error, Write}; use std::path::Path; use std::str::FromStr; -use crate::config::dbconfig::establish_connection; use crate::constants::inner_constants::MAX_FILE_TREE_DEPTH; use crate::models::podcast_episode::PodcastEpisode; use regex::Regex; use rss::Channel; use tokio::task::spawn_blocking; - +use crate::adapters::persistence::dbconfig::db::get_connection; use crate::controllers::settings_controller::ReplacementStrategy; use crate::models::misc_models::PodcastInsertModel; use crate::models::settings::Setting; @@ -72,11 +71,10 @@ impl FileService { pub async fn create_podcast_directory_exists( podcast_insert_model: &PodcastInsertModel, - conn: &mut DbConnection, channel: Option, ) -> Result { let escaped_title = - prepare_podcast_title_to_directory(podcast_insert_model, conn, channel).await?; + prepare_podcast_title_to_directory(podcast_insert_model, channel).await?; let escaped_path = format!("podcasts/{}", escaped_title); if !Path::new(&escaped_path).exists() { std::fs::create_dir(escaped_path.clone()) @@ -85,7 +83,7 @@ impl FileService { } else { // Check if this is a new podcast with the same name as an old one - let conn = &mut establish_connection(); + let conn = &mut get_connection(); let podcast = Podcast::get_podcast_by_directory_id(&podcast_insert_model.id.to_string(), conn)?; match podcast { @@ -114,7 +112,6 @@ impl FileService { podcast_path: &str, image_url: String, podcast_id: &str, - conn: &mut DbConnection, ) { let cloned_image_url = image_url.clone(); let image_suffix = spawn_blocking(move || { @@ -130,7 +127,7 @@ impl FileService { let mut image_out = std::fs::File::create(file_path.0.clone()).unwrap(); let bytes = image_response.bytes().await.unwrap(); image_out.write_all(&bytes).unwrap(); - PodcastEpisode::update_podcast_image(podcast_id, &file_path.1, conn).unwrap(); + PodcastEpisode::update_podcast_image(podcast_id, &file_path.1).unwrap(); } pub fn cleanup_old_episode(episode: PodcastEpisode) -> Result<(), CustomError> { @@ -170,12 +167,11 @@ fn move_one_path_up(path: &str) -> String { pub async fn prepare_podcast_title_to_directory( podcast: &PodcastInsertModel, - conn: &mut DbConnection, channel: Option, ) -> Result { let mut settings_service = SettingsService::new(); - let retrieved_settings = settings_service.get_settings(conn)?.unwrap(); - let opt_podcast_settings = PodcastSetting::get_settings(conn, podcast.id)?; + let retrieved_settings = settings_service.get_settings()?.unwrap(); + let opt_podcast_settings = PodcastSetting::get_settings(podcast.id)?; let podcast = match channel { Some(channel) => RSSFeedParser::parse_rss_feed(channel), @@ -270,17 +266,16 @@ pub fn perform_podcast_variable_replacement( pub fn prepare_podcast_episode_title_to_directory( podcast_episode: PodcastEpisode, - conn: &mut DbConnection, ) -> Result { let mut settings_service = SettingsService::new(); - let retrieved_settings = settings_service.get_settings(conn)?.unwrap(); + let retrieved_settings = settings_service.get_settings()?.unwrap(); if retrieved_settings.use_existing_filename { let res_of_filename = get_filename_of_url(&podcast_episode.url); if let Ok(res_unwrapped) = res_of_filename { return Ok(res_unwrapped); } } - let podcast_settings = PodcastSetting::get_settings(conn, podcast_episode.podcast_id)?; + let podcast_settings = PodcastSetting::get_settings(podcast_episode.podcast_id)?; perform_episode_variable_replacement(retrieved_settings, podcast_episode, podcast_settings) } diff --git a/src/service/notification_service.rs b/src/service/notification_service.rs index 7167977e..2b80124c 100644 --- a/src/service/notification_service.rs +++ b/src/service/notification_service.rs @@ -1,6 +1,5 @@ use crate::models::notification::Notification; use crate::utils::error::CustomError; -use crate::DBType as DbConnection; #[derive(Clone)] pub struct NotificationService {} @@ -12,17 +11,15 @@ impl NotificationService { pub fn get_unread_notifications( &mut self, - conn: &mut DbConnection, ) -> Result, CustomError> { - Notification::get_unread_notifications(conn) + Notification::get_unread_notifications() } pub fn update_status_of_notification( &mut self, id: i32, status: &str, - conn: &mut DbConnection, ) -> Result<(), CustomError> { - Notification::update_status_of_notification(id, status, conn) + Notification::update_status_of_notification(id, status) } } diff --git a/src/service/path_service.rs b/src/service/path_service.rs index a2e8b69f..9e55f002 100644 --- a/src/service/path_service.rs +++ b/src/service/path_service.rs @@ -14,14 +14,13 @@ impl PathService { directory: &str, episode: Option, _suffix: &str, - filename: &str, - conn: &mut DbConnection, + filename: &str ) -> Result { match episode { Some(episode) => Ok(format!( "{}/{}", directory, - prepare_podcast_episode_title_to_directory(episode, conn)? + prepare_podcast_episode_title_to_directory(episode)? )), None => Ok(format!("{}/{}", directory, filename)), } diff --git a/src/service/podcast_episode_service.rs b/src/service/podcast_episode_service.rs index c6800147..230abb15 100644 --- a/src/service/podcast_episode_service.rs +++ b/src/service/podcast_episode_service.rs @@ -16,11 +16,11 @@ use regex::Regex; use reqwest::header::{HeaderMap, ACCEPT}; use reqwest::redirect::Policy; use rss::{Channel, Item}; +use crate::adapters::persistence::dbconfig::db::get_connection; use crate::controllers::server::ChatServerHandle; use crate::models::episode::Episode; use crate::models::notification::Notification; use crate::models::user::User; -use crate::DBType as DbConnection; use crate::models::podcast_settings::PodcastSetting; use crate::mutex::LockResultExt; use crate::service::environment_service::EnvironmentService; @@ -37,16 +37,15 @@ impl PodcastEpisodeService { podcast_episode: PodcastEpisode, podcast: Podcast, lobby: Option>, - conn: &mut DbConnection, ) -> Result<(), CustomError> { let podcast_episode_cloned = podcast_episode.clone(); let podcast_cloned = podcast.clone(); - match PodcastEpisode::check_if_downloaded(&podcast_episode.url, conn) { + match PodcastEpisode::check_if_downloaded(&podcast_episode.url) { Ok(true) => {} Ok(false) => { let podcast_inserted = - Self::perform_download(&podcast_episode_cloned, podcast_cloned, conn)?; + Self::perform_download(&podcast_episode_cloned, podcast_cloned)?; let mapped_dto = MappingService::map_podcastepisode_to_dto(&podcast_inserted); if let Some(lobby) = lobby { lobby.send_broadcast_sync(MAIN_ROOM.parse().unwrap(), serde_json::to_string(&BroadcastMessage { @@ -78,13 +77,12 @@ impl PodcastEpisodeService { pub fn perform_download( podcast_episode: &PodcastEpisode, podcast_cloned: Podcast, - conn: &mut DbConnection, ) -> Result { log::info!("Downloading podcast episode: {}", podcast_episode.name); let mut download_service = DownloadService::new(); download_service.download_podcast_episode(podcast_episode.clone(), podcast_cloned)?; let podcast = - PodcastEpisode::update_podcast_episode_status(&podcast_episode.url, "D", conn)?; + PodcastEpisode::update_podcast_episode_status(&podcast_episode.url, "D")?; let notification = Notification { id: 0, message: podcast_episode.name.to_string(), @@ -92,17 +90,16 @@ impl PodcastEpisodeService { type_of_message: "Download".to_string(), status: "unread".to_string(), }; - Notification::insert_notification(notification, conn)?; + Notification::insert_notification(notification)?; Ok(podcast) } pub fn get_last_n_podcast_episodes( - conn: &mut DbConnection, podcast: Podcast, ) -> Result, CustomError> { let mut settings_service = SettingsService::new(); - let podcast_settings = PodcastSetting::get_settings(conn, podcast.id)?; - let settings = settings_service.get_settings(conn)?.unwrap(); + let podcast_settings = PodcastSetting::get_settings(podcast.id)?; + let settings = settings_service.get_settings()?.unwrap(); let n_episodes; if let Some(podcast_settings) = podcast_settings { @@ -115,12 +112,11 @@ impl PodcastEpisodeService { n_episodes = settings.podcast_prefill; } - PodcastEpisode::get_last_n_podcast_episodes(conn, podcast.id, n_episodes) + PodcastEpisode::get_last_n_podcast_episodes(podcast.id, n_episodes) } // Used for creating/updating podcasts pub fn insert_podcast_episodes( - conn: &mut DbConnection, podcast: Podcast, ) -> Result, CustomError> { let is_redirected = Arc::new(Mutex::new(false)); // Variable to store the redirection status @@ -140,18 +136,17 @@ impl PodcastEpisodeService { Podcast::update_podcast_urls_on_redirect( podcast.id, returned_data_from_podcast_insert.url, - conn, ); - Self::update_episodes_on_redirect(conn, channel.items())?; + Self::update_episodes_on_redirect(channel.items())?; } - Self::handle_itunes_extension(conn, &podcast, &channel)?; + Self::handle_itunes_extension(&podcast, &channel)?; - Self::update_podcast_fields(channel.clone(), podcast.id, conn)?; + Self::update_podcast_fields(channel.clone(), podcast.id)?; let mut podcast_inserted = Vec::new(); - Self::handle_podcast_image_insert(conn, &podcast, &channel)?; + Self::handle_podcast_image_insert(&podcast, &channel)?; for item in channel.items.iter() { let itunes_ext = item.clone().itunes_ext; @@ -162,7 +157,6 @@ impl PodcastEpisodeService { match enclosure { Some(enclosure) => { let result = PodcastEpisode::get_podcast_episode_by_url( - conn, &enclosure.url.to_string(), Some(podcast.id), ); @@ -187,7 +181,6 @@ impl PodcastEpisodeService { { let inserted_episode = PodcastEpisode::insert_podcast_episodes( - conn, podcast.clone(), item.clone(), Some(result_unwrapped_non_opt.image_url), @@ -205,7 +198,6 @@ impl PodcastEpisodeService { let inserted_episode = PodcastEpisode::insert_podcast_episodes( - conn, podcast.clone(), item.clone(), itunes_ext.image, @@ -242,7 +234,6 @@ impl PodcastEpisodeService { continue; } let result = PodcastEpisode::get_podcast_episode_by_url( - conn, &opt_enclosure.clone().unwrap().url, None, ); @@ -251,7 +242,6 @@ impl PodcastEpisodeService { if result?.is_none() { let duration_episode = 0; let inserted_episode = PodcastEpisode::insert_podcast_episodes( - conn, podcast.clone(), item.clone(), Some(image_url), @@ -293,25 +283,23 @@ impl PodcastEpisodeService { } fn handle_podcast_image_insert( - conn: &mut DbConnection, podcast: &Podcast, channel: &Channel, ) -> Result<(), CustomError> { match channel.image() { Some(image) => { - Podcast::update_original_image_url(&image.url.to_string(), podcast.id, conn)?; + Podcast::update_original_image_url(&image.url.to_string(), podcast.id)?; } None => { let env = ENVIRONMENT_SERVICE.get().unwrap(); let url = env.server_url.clone().to_owned() + DEFAULT_IMAGE_URL; - Podcast::update_original_image_url(&url, podcast.id, conn)?; + Podcast::update_original_image_url(&url, podcast.id)?; } } Ok(()) } fn handle_itunes_extension( - conn: &mut DbConnection, podcast: &Podcast, channel: &Channel, ) -> Result<(), CustomError> { @@ -320,32 +308,31 @@ impl PodcastEpisodeService { if extension.new_feed_url.is_some() { let new_url = extension.new_feed_url.unwrap(); - Podcast::update_podcast_urls_on_redirect(podcast.id, new_url, conn); + Podcast::update_podcast_urls_on_redirect(podcast.id, new_url); let returned_data_from_server = Self::do_request_to_podcast_server(podcast.clone()); let channel = Channel::read_from(returned_data_from_server.content.as_bytes()).unwrap(); let items = channel.items(); - Self::update_episodes_on_redirect(conn, items)?; + Self::update_episodes_on_redirect(items)?; } } Ok(()) } fn update_episodes_on_redirect( - conn: &mut DbConnection, items: &[Item], ) -> Result<(), CustomError> { for item in items.iter() { match &item.guid { Some(guid) => { let opt_found_podcast_episode = - Self::get_podcast_episode_by_guid(conn, &guid.value)?; + Self::get_podcast_episode_by_guid(&guid.value)?; if let Some(found_podcast_episode) = opt_found_podcast_episode { let mut podcast_episode = found_podcast_episode.clone(); podcast_episode.url = item.enclosure.as_ref().unwrap().url.to_string(); - PodcastEpisode::update_podcast_episode(conn, podcast_episode); + PodcastEpisode::update_podcast_episode(podcast_episode); } } None => { @@ -356,14 +343,11 @@ impl PodcastEpisodeService { Ok(()) } - fn get_podcast_episode_by_guid( - conn: &mut DbConnection, - guid_to_search: &str, - ) -> Result, CustomError> { - use crate::dbconfig::schema::podcast_episodes::dsl::*; + fn get_podcast_episode_by_guid(guid_to_search: &str) -> Result, CustomError> { + use crate::adapters::persistence::dbconfig::schema::podcast_episodes::dsl::*; podcast_episodes .filter(guid.eq(guid_to_search)) - .first::(conn) + .first::(&mut get_connection()) .optional() .map_err(map_db_error) } @@ -405,9 +389,8 @@ impl PodcastEpisodeService { pub fn query_for_podcast( query: &str, - conn: &mut DbConnection, ) -> Result, CustomError> { - let podcasts = Podcast::query_for_podcast(query, conn)?; + let podcasts = Podcast::query_for_podcast(query)?; let podcast_dto = podcasts .iter() .map(MappingService::map_podcastepisode_to_dto) @@ -416,18 +399,16 @@ impl PodcastEpisodeService { } pub fn find_all_downloaded_podcast_episodes( - conn: &mut DbConnection, env: &EnvironmentService, ) -> Result, CustomError> { - let result = PodcastEpisode::get_episodes(conn); + let result = PodcastEpisode::get_episodes(); Self::map_rss_podcast_episodes(env, result) } pub fn find_all_downloaded_podcast_episodes_with_top_k( - conn: &mut DbConnection, top_k: i32, ) -> Result, CustomError> { - PodcastEpisode::get_podcast_episodes_by_podcast_to_k(conn, top_k) + PodcastEpisode::get_podcast_episodes_by_podcast_to_k(top_k) } fn map_rss_podcast_episodes( @@ -467,16 +448,14 @@ impl PodcastEpisodeService { pub fn find_all_downloaded_podcast_episodes_by_podcast_id( podcast_id: i32, - conn: &mut DbConnection, ) -> Result, CustomError> { - let result = PodcastEpisode::get_episodes_by_podcast_id(podcast_id, conn); + let result = PodcastEpisode::get_episodes_by_podcast_id(podcast_id); Self::map_rss_podcast_episodes(ENVIRONMENT_SERVICE.get().unwrap(), result) } fn update_podcast_fields( feed: Channel, podcast_id: i32, - conn: &mut DbConnection, ) -> Result<(), CustomError> { let itunes = feed.clone().itunes_ext; @@ -489,21 +468,21 @@ impl PodcastEpisodeService { .keywords(itunes.categories) .build(); - Podcast::update_podcast_fields(constructed_extra_fields, conn)?; + Podcast::update_podcast_fields(constructed_extra_fields)?; } Ok(()) } - pub fn cleanup_old_episodes(days_from_settings: i32, conn: &mut DbConnection) { - let podcasts = Podcast::get_all_podcasts(conn); + pub fn cleanup_old_episodes(days_from_settings: i32) { + let podcasts = Podcast::get_all_podcasts(); if podcasts.is_err() { return; } for p in podcasts.unwrap() { - let podcast_settings = PodcastSetting::get_settings(conn, p.id); + let podcast_settings = PodcastSetting::get_settings(p.id); if podcast_settings.is_err() { continue; } @@ -520,7 +499,6 @@ impl PodcastEpisodeService { } let old_podcast_episodes = PodcastEpisode::get_podcast_episodes_older_than_days(days, - conn, p.id); log::info!("Cleaning up {} old episodes", old_podcast_episodes.len()); @@ -531,7 +509,6 @@ impl PodcastEpisodeService { Ok(_) => { PodcastEpisode::update_download_status_of_episode( old_podcast_episode.clone().id, - conn, ); } Err(e) => { @@ -543,19 +520,17 @@ impl PodcastEpisodeService { } pub fn get_podcast_episodes_of_podcast( - conn: &mut DbConnection, id_num: i32, last_id: Option, user: User, ) -> Result)>, CustomError> { - PodcastEpisode::get_podcast_episodes_of_podcast(conn, id_num, last_id, user) + PodcastEpisode::get_podcast_episodes_of_podcast(id_num, last_id, user) } pub fn get_podcast_episode_by_id( - conn: &mut DbConnection, id_num: &str, ) -> Result, CustomError> { - PodcastEpisode::get_podcast_episode_by_id(conn, id_num) + PodcastEpisode::get_podcast_episode_by_id(id_num) } fn do_request_to_podcast_server(podcast: Podcast) -> RequestReturnType { @@ -592,33 +567,32 @@ impl PodcastEpisodeService { pub(crate) fn delete_podcast_episode_locally( episode_id: &str, - conn: &mut DbConnection, ) -> Result { - let episode = PodcastEpisode::get_podcast_episode_by_id(conn, episode_id)?; + let episode = PodcastEpisode::get_podcast_episode_by_id(episode_id)?; if episode.is_none() { return Err(CustomError::NotFound); } FileService::cleanup_old_episode(episode.clone().unwrap())?; - PodcastEpisode::update_download_status_of_episode(episode.clone().unwrap().id, conn); - PodcastEpisode::update_deleted(conn, episode_id, true)?; + PodcastEpisode::update_download_status_of_episode(episode.clone().unwrap().id); + PodcastEpisode::update_deleted(episode_id, true)?; Ok(episode.unwrap()) } pub fn get_track_number_for_episode( - conn: &mut DbConnection, podcast_id: i32, date_of_recording_to_search: &str, ) -> Result { - use crate::dbconfig::schema::podcast_episodes::dsl::podcast_episodes; + use crate::adapters::persistence::dbconfig::schema::podcast_episodes::dsl::podcast_episodes; podcast_episodes - .filter(crate::dbconfig::schema::podcast_episodes::podcast_id.eq(podcast_id)) + .filter(crate::adapters::persistence::dbconfig::schema::podcast_episodes::podcast_id.eq + (podcast_id)) .filter( - crate::dbconfig::schema::podcast_episodes::date_of_recording + crate::adapters::persistence::dbconfig::schema::podcast_episodes::date_of_recording .le(date_of_recording_to_search), ) .count() - .get_result::(conn) + .get_result::(&mut get_connection()) .map_err(map_db_error) } } diff --git a/src/service/rust_service.rs b/src/service/rust_service.rs index 57953c2e..1e2e20a0 100644 --- a/src/service/rust_service.rs +++ b/src/service/rust_service.rs @@ -16,7 +16,6 @@ use serde_json::Value; use sha1::{Digest, Sha1}; use std::time::SystemTime; use reqwest::Client; -use crate::config::dbconfig::establish_connection; use serde::Serialize; use tokio::task::spawn_blocking; use crate::controllers::server::ChatServerHandle; @@ -24,7 +23,6 @@ use crate::models::favorites::Favorite; use crate::models::order_criteria::{OrderCriteria, OrderOption}; use crate::models::settings::Setting; use crate::utils::error::{map_reqwest_error, CustomError}; -use crate::DBType as DbConnection; use crate::models::podcast_settings::PodcastSetting; use crate::utils::reqwest_client::get_async_sync_client; use crate::models::tag::Tag; @@ -110,7 +108,6 @@ impl PodcastService { pub async fn insert_podcast_from_podindex( &mut self, - conn: &mut DbConnection, id: i32, lobby: Data, ) -> Result { @@ -130,7 +127,6 @@ impl PodcastService { let podcast = resp.json::().await.unwrap(); self.handle_insert_of_podcast( - conn, PodcastInsertModel { title: unwrap_string(&podcast["feed"]["title"]), id, @@ -145,12 +141,11 @@ impl PodcastService { pub async fn handle_insert_of_podcast( &mut self, - conn: &mut DbConnection, podcast_insert: PodcastInsertModel, lobby: Data, channel: Option, ) -> Result { - let opt_podcast = Podcast::find_by_rss_feed_url(conn, &podcast_insert.feed_url.clone()); + let opt_podcast = Podcast::find_by_rss_feed_url(&podcast_insert.feed_url.clone()); if opt_podcast.is_some() { return Err(CustomError::Conflict(format!( "Podcast with feed url {} already exists", @@ -161,10 +156,9 @@ impl PodcastService { let fileservice = FileService::new(); let podcast_directory_created = - FileService::create_podcast_directory_exists(&podcast_insert, conn, channel).await?; + FileService::create_podcast_directory_exists(&podcast_insert, channel).await?; let inserted_podcast = Podcast::add_podcast_to_database( - conn, podcast_insert.title, podcast_insert.id.to_string(), podcast_insert.feed_url, @@ -177,10 +171,9 @@ impl PodcastService { &inserted_podcast.directory_name.clone().to_string(), podcast_insert.image_url.clone().to_string(), &podcast_insert.id.clone().to_string(), - conn, ) .await; - let podcast = Podcast::get_podcast_by_track_id(conn, podcast_insert.id).unwrap(); + let podcast = Podcast::get_podcast_by_track_id(podcast_insert.id).unwrap(); lobby .send_broadcast(MAIN_ROOM.parse().unwrap(), serde_json::to_string(&BroadcastMessage { podcast_episode: None, @@ -195,12 +188,11 @@ impl PodcastService { match podcast { Some(podcast) => { spawn_blocking(move || { - let mut conn = establish_connection(); let mut podcast_service = PodcastService::new(); log::debug!("Inserting podcast episodes of {}", podcast.name); let inserted_podcasts = - PodcastEpisodeService::insert_podcast_episodes(&mut conn, podcast.clone()) + PodcastEpisodeService::insert_podcast_episodes(podcast.clone()) .unwrap(); lobby.send_broadcast_sync(MAIN_ROOM.parse().unwrap(), serde_json::to_string @@ -212,7 +204,7 @@ impl PodcastService { podcast_episodes: Option::from(inserted_podcasts), }).unwrap()); if let Err(e) = - podcast_service.schedule_episode_download(podcast, Some(lobby), &mut conn) + podcast_service.schedule_episode_download(podcast, Some(lobby)) { log::error!("Error scheduling episode download: {}", e); } @@ -231,15 +223,14 @@ impl PodcastService { &mut self, podcast: Podcast, lobby: Option>, - conn: &mut DbConnection, ) -> Result<(), CustomError> { - let settings = Setting::get_settings(conn)?; - let podcast_settings = PodcastSetting::get_settings(conn, podcast.id)?; + let settings = Setting::get_settings()?; + let podcast_settings = PodcastSetting::get_settings(podcast.id)?; match settings { Some(settings) => { if (podcast_settings.is_some() && podcast_settings.unwrap().auto_download) || settings.auto_download { let result = - PodcastEpisodeService::get_last_n_podcast_episodes(conn, podcast.clone())?; + PodcastEpisodeService::get_last_n_podcast_episodes(podcast.clone())?; for podcast_episode in result { if !podcast_episode.deleted { if let Err(e) = @@ -247,7 +238,6 @@ impl PodcastService { podcast_episode, podcast.clone(), lobby.clone(), - conn, ){ log::error!("Error downloading podcast episode: {}", e); } @@ -267,11 +257,10 @@ impl PodcastService { &mut self, podcast: Podcast, lobby: Data, - conn: &mut DbConnection, ) -> Result<(), CustomError> { log::info!("Refreshing podcast: {}", podcast.name); - PodcastEpisodeService::insert_podcast_episodes(conn, podcast.clone())?; - self.schedule_episode_download(podcast.clone(), Some(lobby.clone()), conn) + PodcastEpisodeService::insert_podcast_episodes(podcast.clone())?; + self.schedule_episode_download(podcast.clone(), Some(lobby.clone())) } pub fn update_favor_podcast( @@ -279,25 +268,23 @@ impl PodcastService { id: i32, x: bool, username: String, - conn: &mut DbConnection, ) -> Result<(), CustomError> { - Favorite::update_podcast_favor(&id, x, conn, username) + Favorite::update_podcast_favor(&id, x, username) } - pub fn get_podcast_by_id(&mut self, conn: &mut DbConnection, id: i32) -> Podcast { - Podcast::get_podcast(conn, id).unwrap() + pub fn get_podcast_by_id(&mut self, id: i32) -> Podcast { + Podcast::get_podcast(id).unwrap() } pub fn get_favored_podcasts( &mut self, found_username: String, - conn: &mut DbConnection, ) -> Result, CustomError> { - Favorite::get_favored_podcasts(found_username, conn) + Favorite::get_favored_podcasts(found_username) } - pub fn update_active_podcast(conn: &mut DbConnection, id: i32) -> Result<(), CustomError> { - Podcast::update_podcast_active(conn, id) + pub fn update_active_podcast(id: i32) -> Result<(), CustomError> { + Podcast::update_podcast_active(id) } fn compute_podindex_header(&mut self) -> HeaderMap { @@ -345,17 +332,15 @@ impl PodcastService { } pub fn get_podcast( - conn: &mut DbConnection, podcast_id_to_be_searched: i32, ) -> Result { - Podcast::get_podcast(conn, podcast_id_to_be_searched) + Podcast::get_podcast(podcast_id_to_be_searched) } pub fn get_podcasts( - conn: &mut DbConnection, u: String, ) -> Result, CustomError> { - Podcast::get_podcasts(conn, u) + Podcast::get_podcasts(u) } pub fn search_podcasts_favored( @@ -363,23 +348,22 @@ impl PodcastService { order: OrderCriteria, title: Option, latest_pub: OrderOption, - conn: &mut DbConnection, designated_username: String, tag: Option, ) -> Result, CustomError> { let podcasts = - Favorite::search_podcasts_favored(conn, order, title, latest_pub, + Favorite::search_podcasts_favored(order, title, latest_pub, &designated_username)?; let mut podcast_dto_vec = Vec::new(); for podcast in podcasts { - let tags_of_podcast = Tag::get_tags_of_podcast(conn, podcast.0.id, &designated_username)?; + let tags_of_podcast = Tag::get_tags_of_podcast(podcast.0.id, &designated_username)?; let podcast_dto = MappingService::map_podcast_to_podcast_dto_with_favorites_option(&podcast, tags_of_podcast); podcast_dto_vec.push(podcast_dto); } if let Some(tag) = tag { - let found_tag = Tag::get_tag_by_id_and_username(conn, &tag, &designated_username)?; + let found_tag = Tag::get_tag_by_id_and_username(&tag, &designated_username)?; if let Some(foud_tag) = found_tag { podcast_dto_vec = podcast_dto_vec.into_iter().filter(|p|{ @@ -396,23 +380,22 @@ impl PodcastService { order: OrderCriteria, title: Option, latest_pub: OrderOption, - conn: &mut DbConnection, designated_username: String, tag: Option, ) -> Result, CustomError> { let podcasts = - Favorite::search_podcasts(conn, order, title, latest_pub, &designated_username)?; + Favorite::search_podcasts(order, title, latest_pub, &designated_username)?; let mut mapped_result = podcasts .iter() .map(|podcast| { - let tags = Tag::get_tags_of_podcast(conn, podcast.0.id, &designated_username).unwrap(); + let tags = Tag::get_tags_of_podcast(podcast.0.id, &designated_username).unwrap(); MappingService::map_podcast_to_podcast_dto_with_favorites(podcast, tags) }) .collect::>(); if let Some(tag) = tag { - let found_tag = Tag::get_tag_by_id_and_username(conn, &tag, &designated_username)?; + let found_tag = Tag::get_tag_by_id_and_username(&tag, &designated_username)?; if let Some(foud_tag) = found_tag { mapped_result = mapped_result.into_iter().filter(|p|{ diff --git a/src/service/settings_service.rs b/src/service/settings_service.rs index b3e0dc0f..498709e1 100644 --- a/src/service/settings_service.rs +++ b/src/service/settings_service.rs @@ -6,7 +6,6 @@ use crate::service::file_service::{ }; use crate::utils::error::CustomError; use crate::utils::rss_feed_parser::PodcastParsed; -use crate::DBType as DbConnection; #[derive(Clone)] pub struct SettingsService {} @@ -18,25 +17,22 @@ impl SettingsService { pub fn get_settings( &mut self, - conn: &mut DbConnection, ) -> Result, CustomError> { - Setting::get_settings(conn) + Setting::get_settings() } pub fn update_settings( &mut self, settings: Setting, - conn: &mut DbConnection, ) -> Result { - Setting::update_settings(settings, conn) + Setting::update_settings(settings) } pub fn update_name( &mut self, update_model: UpdateNameSettings, - conn: &mut DbConnection, ) -> Result { - let mut settings_ = self.get_settings(conn)?.unwrap(); + let mut settings_ = self.get_settings()?.unwrap(); Self::validate_settings(update_model.clone())?; settings_.replace_invalid_characters = update_model.replace_invalid_characters; @@ -45,7 +41,7 @@ impl SettingsService { settings_.replacement_strategy = update_model.replacement_strategy.to_string(); settings_.episode_format = update_model.episode_format; settings_.podcast_format = update_model.podcast_format; - self.update_settings(settings_, conn) + self.update_settings(settings_) } fn validate_settings( diff --git a/src/service/user_management_service.rs b/src/service/user_management_service.rs index fe14be75..7e982e05 100644 --- a/src/service/user_management_service.rs +++ b/src/service/user_management_service.rs @@ -5,8 +5,8 @@ use crate::models::invite::Invite; use crate::models::user::{User, UserWithoutPassword}; use crate::service::environment_service::EnvironmentService; use crate::utils::error::CustomError; -use crate::DBType as DbConnection; use sha256::digest; +use crate::adapters::persistence::dbconfig::db::get_connection; pub struct UserManagementService {} @@ -38,10 +38,9 @@ impl UserManagementService { username: String, password: String, invite_id: String, - conn: &mut DbConnection, ) -> Result { // Check if the invite is valid - match Invite::find_invite(invite_id.clone(), conn) { + match Invite::find_invite(invite_id.clone()) { Ok(invite) => { match invite { Some(invite) => { @@ -62,9 +61,9 @@ impl UserManagementService { // This is safe as only when basic auth is enabled, the password is set if Self::is_valid_password(password.clone()) { - match User::insert_user(&mut actual_user, conn) { + match User::insert_user(&mut actual_user) { Ok(user) => { - Invite::invalidate_invite(invite_id.clone(), conn) + Invite::invalidate_invite(invite_id.clone()) .expect("Error invalidating invite"); Ok(user) } @@ -93,11 +92,10 @@ impl UserManagementService { pub fn create_invite( role: Role, explicit_consent_i: bool, - conn: &mut DbConnection, user: User, ) -> Result { if Self::may_onboard_user(user) { - let invite = Invite::insert_invite(&role, explicit_consent_i, conn).expect( + let invite = Invite::insert_invite(&role, explicit_consent_i).expect( "Error \ inserting invite", ); @@ -106,17 +104,16 @@ impl UserManagementService { Err(CustomError::Forbidden) } - pub fn delete_user(user: User, conn: &mut DbConnection) -> Result { - User::delete_user(&user, conn) + pub fn delete_user(user: User) -> Result { + User::delete_user(&user) } pub fn update_user( user_to_update: User, - conn: &mut DbConnection, ) -> Result { - match User::update_role(&user_to_update, conn) { + match User::update_role(&user_to_update) { Ok(user) => { - match User::update_explicit_consent(&user_to_update, conn) { + match User::update_explicit_consent(&user_to_update) { Ok(_) => {} Err(e) => { log::error!("The following error occured when updating a user {}", e); @@ -135,17 +132,16 @@ impl UserManagementService { pub fn get_invite_link( invite_id: String, environment_service: &EnvironmentService, - conn: &mut DbConnection, ) -> Result { - let invite = Invite::find_invite(invite_id, conn)?; + let invite = Invite::find_invite(invite_id)?; match invite { Some(invite) => Ok(environment_service.clone().server_url + "ui/invite/" + &invite.id), None => Err(CustomError::NotFound), } } - pub fn get_invite(invite_id: String, conn: &mut DbConnection) -> Result { - let invite = Invite::find_invite(invite_id, conn)?; + pub fn get_invite(invite_id: String) -> Result { + let invite = Invite::find_invite(invite_id)?; match invite { Some(invite) => { @@ -158,8 +154,8 @@ impl UserManagementService { } } - pub fn get_invites(conn: &mut DbConnection) -> Result, CustomError> { - match Invite::find_all_invites(conn) { + pub fn get_invites() -> Result, CustomError> { + match Invite::find_all_invites() { Ok(invites) => Ok(invites), Err(e) => { log::error!("The following error occured when finding an invite {}", e); @@ -170,20 +166,19 @@ impl UserManagementService { pub fn get_users( requester: User, - conn: &mut DbConnection, ) -> Result, CustomError> { if !Self::may_onboard_user(requester) { return Err(CustomError::Forbidden); } - Ok(User::find_all_users(conn)) + Ok(User::find_all_users(&mut get_connection())) } - pub fn delete_invite(invite_id: String, conn: &mut DbConnection) -> Result<(), CustomError> { - let invite = Invite::find_invite(invite_id, conn)?; + pub fn delete_invite(invite_id: String) -> Result<(), CustomError> { + let invite = Invite::find_invite(invite_id)?; match invite { Some(invite) => { - Invite::delete_invite(invite.id, conn)?; + Invite::delete_invite(invite.id)?; Ok(()) } None => Err(CustomError::NotFound), diff --git a/src/utils/podcast_key_checker.rs b/src/utils/podcast_key_checker.rs index c857f8cc..8e2a720b 100644 --- a/src/utils/podcast_key_checker.rs +++ b/src/utils/podcast_key_checker.rs @@ -1,4 +1,3 @@ -use crate::config::dbconfig::establish_connection; use crate::constants::inner_constants::{BASIC_AUTH, OIDC_AUTH}; use crate::models::user::User; use crate::utils::environment_variables::is_env_var_present_and_true; @@ -37,8 +36,7 @@ where return async { Err(ErrorUnauthorized("Unauthorized")) }.boxed_local(); } - let conn = &mut establish_connection(); - let api_key_exists = User::check_if_api_key_exists(api_key.unwrap().to_string(), conn); + let api_key_exists = User::check_if_api_key_exists(api_key.unwrap().to_string()); if !api_key_exists { return async { Err(ErrorUnauthorized("Unauthorized")) }.boxed_local(); }