diff --git a/Cargo.lock b/Cargo.lock index d05d3ad..2783b28 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1221,7 +1221,6 @@ dependencies = [ "chrono", "futures", "serde", - "sqlx", "thiserror 2.0.17", "uuid", ] @@ -1231,7 +1230,9 @@ name = "libertas_infra" version = "0.1.0" dependencies = [ "async-trait", + "chrono", "libertas_core", + "serde", "sqlx", "uuid", ] diff --git a/compose.yml b/compose.yml index 76b105a..805501d 100644 --- a/compose.yml +++ b/compose.yml @@ -7,3 +7,17 @@ services: - "6222:6222" - "8222:8222" restart: unless-stopped + db: + image: postgres:17 + container_name: libertas_db + environment: + POSTGRES_USER: libertas + POSTGRES_PASSWORD: libertas_password + POSTGRES_DB: libertas_db + ports: + - "5436:5432" + volumes: + - libertas_db_data:/var/lib/postgresql/data + restart: unless-stopped +volumes: + libertas_db_data: diff --git a/libertas_api/src/config.rs b/libertas_api/src/config.rs index a239a55..0236691 100644 --- a/libertas_api/src/config.rs +++ b/libertas_api/src/config.rs @@ -7,12 +7,13 @@ pub fn load_config() -> CoreResult { Ok(Config { database: DatabaseConfig { db_type: DatabaseType::Postgres, - url: "postgres://postgres:postgres@localhost:5432/libertas_db".to_string(), + url: "postgres://libertas:libertas_password@localhost:5436/libertas_db".to_string(), }, server_address: "127.0.0.1:8080".to_string(), jwt_secret: "super_secret_jwt_key".to_string(), media_library_path: "media_library".to_string(), broker_url: "nats://localhost:4222".to_string(), max_upload_size_mb: Some(100), + default_storage_quota_gb: Some(10), }) } diff --git a/libertas_api/src/factory.rs b/libertas_api/src/factory.rs index d735322..97f9bb2 100644 --- a/libertas_api/src/factory.rs +++ b/libertas_api/src/factory.rs @@ -38,6 +38,7 @@ pub async fn build_app_state(config: Config) -> CoreResult { user_repo.clone(), hasher, tokenizer.clone(), + Arc::new(config.clone()), )); let media_service = Arc::new(MediaServiceImpl::new( media_repo.clone(), diff --git a/libertas_api/src/handlers/media_handlers.rs b/libertas_api/src/handlers/media_handlers.rs index 4469e16..3a84c4c 100644 --- a/libertas_api/src/handlers/media_handlers.rs +++ b/libertas_api/src/handlers/media_handlers.rs @@ -37,14 +37,12 @@ impl From for MediaResponse { } } -pub fn media_routes() -> Router { - let max_size_mb = 100; // todo: get from config - +pub fn media_routes(max_upload_size: usize) -> Router { Router::new() .route("/", post(upload_media)) .route("/{id}", get(get_media_details).delete(delete_media)) .route("/{id}/file", get(get_media_file)) - .layer(DefaultBodyLimit::max(max_size_mb * 1024 * 1024)) + .layer(DefaultBodyLimit::max(max_upload_size)) } async fn upload_media( diff --git a/libertas_api/src/main.rs b/libertas_api/src/main.rs index bcb4be2..1942e9b 100644 --- a/libertas_api/src/main.rs +++ b/libertas_api/src/main.rs @@ -28,8 +28,10 @@ async fn main() -> anyhow::Result<()> { let addr: SocketAddr = config.server_address.parse()?; let app_state = factory::build_app_state(config).await?; + let max_upload_size = + (app_state.config.max_upload_size_mb.unwrap_or(100) * 1024 * 1024) as usize; - let app = routes::api_routes().with_state(app_state); + let app = routes::api_routes(max_upload_size).with_state(app_state); println!("Starting server at http://{}", addr); diff --git a/libertas_api/src/routes.rs b/libertas_api/src/routes.rs index 072aa73..779eb20 100644 --- a/libertas_api/src/routes.rs +++ b/libertas_api/src/routes.rs @@ -5,10 +5,10 @@ use crate::{ state::AppState, }; -pub fn api_routes() -> Router { +pub fn api_routes(max_upload_size: usize) -> Router { let auth_routes = auth_handlers::auth_routes(); let user_routes = user_handlers::user_routes(); - let media_routes = media_handlers::media_routes(); + let media_routes = media_handlers::media_routes(max_upload_size); let album_routes = album_handlers::album_routes(); Router::new() diff --git a/libertas_api/src/services/media_service.rs b/libertas_api/src/services/media_service.rs index 57beef5..ea30f05 100644 --- a/libertas_api/src/services/media_service.rs +++ b/libertas_api/src/services/media_service.rs @@ -46,89 +46,24 @@ impl MediaServiceImpl { #[async_trait] impl MediaService for MediaServiceImpl { async fn upload_media(&self, mut data: UploadMediaData<'_>) -> CoreResult { - let user = self - .user_repo - .find_by_id(data.owner_id) - .await? - .ok_or(CoreError::NotFound("User".to_string(), data.owner_id))?; + let (file_bytes, hash, file_size) = self.hash_and_buffer_stream(&mut data).await?; - let mut hasher = Sha256::new(); - let mut file_bytes = Vec::new(); + let owner_id = data.owner_id; + let filename = data.filename; + let mime_type = data.mime_type; - while let Some(chunk_result) = data.stream.next().await { - let chunk = chunk_result.map_err(|e| CoreError::Io(e))?; - hasher.update(&chunk); - file_bytes.extend_from_slice(&chunk); - } - let file_size = file_bytes.len() as i64; - - if user.storage_used + file_size > user.storage_quota { - return Err(CoreError::Auth(format!( - "Storage quota exceeded. Used: {}, Quota: {}", - user.storage_used, user.storage_quota - ))); - } - - let hash = format!("{:x}", hasher.finalize()); - - if self.repo.find_by_hash(&hash).await?.is_some() { - return Err(CoreError::Duplicate( - "A file with this content already exists".to_string(), - )); - } - - let now = chrono::Utc::now(); - let year = now.year().to_string(); - let month = format!("{:02}", now.month()); - let mut dest_path = PathBuf::from(&self.config.media_library_path); - dest_path.push(year.clone()); - dest_path.push(month.clone()); - - fs::create_dir_all(&dest_path) - .await - .map_err(|e| CoreError::Io(e))?; - - dest_path.push(&data.filename); - - let storage_path_str = PathBuf::from(&year) - .join(&month) - .join(&data.filename) - .to_string_lossy() - .to_string(); - - let mut file = fs::File::create(&dest_path) - .await - .map_err(|e| CoreError::Io(e))?; - - file.write_all(&file_bytes) - .await - .map_err(|e| CoreError::Io(e))?; - - let media_model = Media { - id: Uuid::new_v4(), - owner_id: data.owner_id, - storage_path: storage_path_str, - original_filename: data.filename, - mime_type: data.mime_type, - hash, - created_at: now, - extracted_location: None, - width: None, - height: None, - }; - - self.repo.create(&media_model).await?; - self.user_repo - .update_storage_used(user.id, file_size) + self.check_upload_prerequisites(owner_id, file_size, &hash) .await?; - let job_payload = json!({ "media_id": media_model.id }); - self.nats_client - .publish("media.new".to_string(), job_payload.to_string().into()) - .await - .map_err(|e| CoreError::Unknown(format!("Failed to publish NATS job: {}", e)))?; + let storage_path = self.persist_media_file(&file_bytes, &filename).await?; - Ok(media_model) + let media = self + .persist_media_metadata(owner_id, filename, mime_type, storage_path, hash, file_size) + .await?; + + self.publish_new_media_job(media.id).await?; + + Ok(media) } async fn get_media_details(&self, id: Uuid, user_id: Uuid) -> CoreResult { @@ -235,3 +170,110 @@ impl MediaService for MediaServiceImpl { Ok(()) } } + +impl MediaServiceImpl { + async fn hash_and_buffer_stream( + &self, + stream: &mut UploadMediaData<'_>, + ) -> CoreResult<(Vec, String, i64)> { + let mut hasher = Sha256::new(); + let mut file_bytes = Vec::new(); + while let Some(chunk_result) = stream.stream.next().await { + let chunk = chunk_result.map_err(|e| CoreError::Io(e))?; + hasher.update(&chunk); + file_bytes.extend_from_slice(&chunk); + } + let file_size = file_bytes.len() as i64; + let hash = format!("{:x}", hasher.finalize()); + Ok((file_bytes, hash, file_size)) + } + + async fn check_upload_prerequisites( + &self, + user_id: Uuid, + file_size: i64, + hash: &str, + ) -> CoreResult<()> { + let user = self + .user_repo + .find_by_id(user_id) + .await? + .ok_or(CoreError::NotFound("User".to_string(), user_id))?; + + if user.storage_used + file_size > user.storage_quota { + return Err(CoreError::Auth(format!( + "Storage quota exceeded. Used: {}, Quota: {}", + user.storage_used, user.storage_quota + ))); + } + + if self.repo.find_by_hash(hash).await?.is_some() { + return Err(CoreError::Duplicate( + "A file with this content already exists".to_string(), + )); + } + + Ok(()) + } + + async fn persist_media_file(&self, file_bytes: &[u8], filename: &str) -> CoreResult { + let now = chrono::Utc::now(); + let year = now.year().to_string(); + let month = format!("{:02}", now.month()); + let mut dest_path = PathBuf::from(&self.config.media_library_path); + dest_path.push(year.clone()); + dest_path.push(month.clone()); + + fs::create_dir_all(&dest_path).await?; + dest_path.push(filename); + + let storage_path_str = PathBuf::from(&year) + .join(&month) + .join(filename) + .to_string_lossy() + .to_string(); + + let mut file = fs::File::create(&dest_path).await?; + file.write_all(&file_bytes).await?; + + Ok(storage_path_str) + } + + async fn persist_media_metadata( + &self, + owner_id: Uuid, + filename: String, + mime_type: String, + storage_path: String, + hash: String, + file_size: i64, + ) -> CoreResult { + let media_model = Media { + id: Uuid::new_v4(), + owner_id, + storage_path, + original_filename: filename, + mime_type, + hash, + created_at: chrono::Utc::now(), + extracted_location: None, + width: None, + height: None, + }; + + self.repo.create(&media_model).await?; + self.user_repo + .update_storage_used(owner_id, file_size) + .await?; + + Ok(media_model) + } + + async fn publish_new_media_job(&self, media_id: Uuid) -> CoreResult<()> { + let job_payload = json!({ "media_id": media_id }); + self.nats_client + .publish("media.new".to_string(), job_payload.to_string().into()) + .await + .map_err(|e| CoreError::Unknown(format!("Failed to publish NATS job: {}", e))) + } +} diff --git a/libertas_api/src/services/user_service.rs b/libertas_api/src/services/user_service.rs index f823333..de8d629 100644 --- a/libertas_api/src/services/user_service.rs +++ b/libertas_api/src/services/user_service.rs @@ -2,6 +2,7 @@ use std::sync::Arc; use async_trait::async_trait; use libertas_core::{ + config::Config, error::{CoreError, CoreResult}, models::{Role, User}, repositories::UserRepository, @@ -16,6 +17,7 @@ pub struct UserServiceImpl { repo: Arc, hasher: Arc, tokenizer: Arc, + config: Arc, } impl UserServiceImpl { @@ -23,11 +25,13 @@ impl UserServiceImpl { repo: Arc, hasher: Arc, tokenizer: Arc, + config: Arc, ) -> Self { Self { repo, hasher, tokenizer, + config, } } } @@ -50,6 +54,9 @@ impl UserService for UserServiceImpl { let hashed_password = self.hasher.hash_password(data.password).await?; + let quota_gb = self.config.default_storage_quota_gb.unwrap_or(10); + let storage_quota = (quota_gb * 1024 * 1024 * 1024) as i64; + let user = User { id: Uuid::new_v4(), username: data.username.to_string(), @@ -58,7 +65,7 @@ impl UserService for UserServiceImpl { created_at: chrono::Utc::now(), updated_at: chrono::Utc::now(), role: Role::User, - storage_quota: 10 * 1024 * 1024 * 1024, // 10 GB + storage_quota, storage_used: 0, }; diff --git a/libertas_core/Cargo.toml b/libertas_core/Cargo.toml index eec4097..1464cf0 100644 --- a/libertas_core/Cargo.toml +++ b/libertas_core/Cargo.toml @@ -10,12 +10,5 @@ bytes = "1.10.1" chrono = "0.4.42" futures = "0.3.31" thiserror = "2.0.17" -uuid = "1.18.1" -sqlx = { version = "0.8.6", features = [ - "runtime-tokio", - "postgres", - "uuid", - "chrono", - "sqlite", -] } +uuid = {version = "1.18.1", features = ["v4", "serde"] } serde = { version = "1.0.228", features = ["derive"] } diff --git a/libertas_core/src/config.rs b/libertas_core/src/config.rs index 511417d..99b572c 100644 --- a/libertas_core/src/config.rs +++ b/libertas_core/src/config.rs @@ -20,4 +20,5 @@ pub struct Config { pub media_library_path: String, pub broker_url: String, pub max_upload_size_mb: Option, + pub default_storage_quota_gb: Option, } diff --git a/libertas_core/src/models.rs b/libertas_core/src/models.rs index 70c1ba3..50093ad 100644 --- a/libertas_core/src/models.rs +++ b/libertas_core/src/models.rs @@ -1,8 +1,7 @@ use serde::Deserialize; -#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] -#[sqlx(rename_all = "lowercase")] -#[sqlx(type_name = "TEXT")] +#[derive(Debug, Clone, PartialEq, Eq)] + pub enum Role { User, Admin, @@ -17,6 +16,15 @@ impl Role { } } +impl From<&str> for Role { + fn from(s: &str) -> Self { + match s { + "admin" => Role::Admin, + _ => Role::User, + } + } +} + pub struct Media { pub id: uuid::Uuid, pub owner_id: uuid::Uuid, @@ -30,7 +38,7 @@ pub struct Media { pub height: Option, } -#[derive(Clone, sqlx::FromRow)] +#[derive(Clone)] pub struct User { pub id: uuid::Uuid, pub username: String, @@ -44,7 +52,7 @@ pub struct User { pub storage_used: i64, // in bytes } -#[derive(Clone, sqlx::FromRow)] +#[derive(Clone)] pub struct Album { pub id: uuid::Uuid, pub owner_id: uuid::Uuid, @@ -78,14 +86,30 @@ pub struct AlbumMedia { pub media_id: uuid::Uuid, } -#[derive(Debug, Clone, Copy, sqlx::Type, PartialEq, Eq, Deserialize)] -#[sqlx(rename_all = "lowercase")] -#[sqlx(type_name = "album_permission")] +#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)] pub enum AlbumPermission { View, Contribute, } +impl AlbumPermission { + pub fn as_str(&self) -> &'static str { + match self { + AlbumPermission::View => "view", + AlbumPermission::Contribute => "contribute", + } + } +} + +impl From<&str> for AlbumPermission { + fn from(s: &str) -> Self { + match s { + "contribute" => AlbumPermission::Contribute, + _ => AlbumPermission::View, + } + } +} + pub struct AlbumShare { pub album_id: uuid::Uuid, pub user_id: uuid::Uuid, diff --git a/libertas_infra/Cargo.toml b/libertas_infra/Cargo.toml index a11f87d..65f9c3a 100644 --- a/libertas_infra/Cargo.toml +++ b/libertas_infra/Cargo.toml @@ -14,3 +14,5 @@ sqlx = { version = "0.8.6", features = [ ] } async-trait = "0.1.89" uuid = { version = "1.18.1", features = ["v4"] } +chrono = "0.4.42" +serde = { version = "1.0.228", features = ["derive"] } diff --git a/libertas_infra/src/db_models.rs b/libertas_infra/src/db_models.rs new file mode 100644 index 0000000..a24dfdd --- /dev/null +++ b/libertas_infra/src/db_models.rs @@ -0,0 +1,64 @@ +use chrono::Utc; +use serde::Deserialize; +use uuid::Uuid; + +#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] +#[sqlx(rename_all = "lowercase")] +#[sqlx(type_name = "TEXT")] +pub enum PostgresRole { + User, + Admin, +} + + +#[derive(sqlx::FromRow)] +pub struct PostgresUser { + pub id: Uuid, + pub username: String, + pub email: String, + pub hashed_password: String, + pub created_at: chrono::DateTime, + pub updated_at: chrono::DateTime, + pub role: String, + pub storage_quota: i64, + pub storage_used: i64, +} + +#[derive(sqlx::FromRow)] +pub struct PostgresAlbum { + pub id: uuid::Uuid, + pub owner_id: uuid::Uuid, + pub name: String, + pub description: Option, + pub is_public: bool, + pub created_at: chrono::DateTime, + pub updated_at: chrono::DateTime, +} + +#[derive(sqlx::FromRow)] +pub struct PostgresMedia { + pub id: uuid::Uuid, + pub owner_id: uuid::Uuid, + pub storage_path: String, + pub original_filename: String, + pub mime_type: String, + pub hash: String, + pub created_at: chrono::DateTime, + pub extracted_location: Option, + pub width: Option, + pub height: Option, +} + +#[derive(Debug, Clone, Copy, sqlx::Type, PartialEq, Eq, Deserialize)] +#[sqlx(rename_all = "lowercase")] +#[sqlx(type_name = "album_permission")] +pub enum PostgresAlbumPermission { + View, + Contribute, +} + +pub struct PostgresAlbumShare { + pub album_id: uuid::Uuid, + pub user_id: uuid::Uuid, + pub permission: PostgresAlbumPermission, +} \ No newline at end of file diff --git a/libertas_infra/src/lib.rs b/libertas_infra/src/lib.rs index 12c05bb..1be526d 100644 --- a/libertas_infra/src/lib.rs +++ b/libertas_infra/src/lib.rs @@ -1,2 +1,4 @@ pub mod factory; pub mod repositories; +pub mod db_models; +pub mod mappers; \ No newline at end of file diff --git a/libertas_infra/src/mappers.rs b/libertas_infra/src/mappers.rs new file mode 100644 index 0000000..39d72d6 --- /dev/null +++ b/libertas_infra/src/mappers.rs @@ -0,0 +1,96 @@ +use libertas_core::models::{Album, AlbumPermission, AlbumShare, Media, Role, User}; + +use crate::db_models::{PostgresAlbum, PostgresAlbumPermission, PostgresAlbumShare, PostgresMedia, PostgresRole, PostgresUser}; + +impl From for Role { + fn from(pg_role: PostgresRole) -> Self { + match pg_role { + PostgresRole::User => Role::User, + PostgresRole::Admin => Role::Admin, + } + } +} + +impl From for PostgresRole { + fn from(role: Role) -> Self { + match role { + Role::User => PostgresRole::User, + Role::Admin => PostgresRole::Admin, + } + } +} + +impl From for User { + fn from(pg_user: PostgresUser) -> Self { + User { + id: pg_user.id, + username: pg_user.username, + email: pg_user.email, + hashed_password: pg_user.hashed_password, + created_at: pg_user.created_at, + updated_at: pg_user.updated_at, + role: Role::from(pg_user.role.as_str()), + storage_quota: pg_user.storage_quota, + storage_used: pg_user.storage_used, + } + } +} + +impl From for Album { + fn from(pg_album: PostgresAlbum) -> Self { + Album { + id: pg_album.id, + owner_id: pg_album.owner_id, + name: pg_album.name, + description: pg_album.description, + is_public: pg_album.is_public, + created_at: pg_album.created_at, + updated_at: pg_album.updated_at, + } + } +} + +impl From for Media { + fn from(pg_media: PostgresMedia) -> Self { + Media { + id: pg_media.id, + owner_id: pg_media.owner_id, + storage_path: pg_media.storage_path, + original_filename: pg_media.original_filename, + mime_type: pg_media.mime_type, + hash: pg_media.hash, + created_at: pg_media.created_at, + extracted_location: pg_media.extracted_location, + width: pg_media.width, + height: pg_media.height, + } + } +} + +impl From for AlbumPermission { + fn from(pg_permission: PostgresAlbumPermission) -> Self { + match pg_permission { + PostgresAlbumPermission::View => AlbumPermission::View, + PostgresAlbumPermission::Contribute => AlbumPermission::Contribute, + } + } +} + +impl From for PostgresAlbumPermission { + fn from(permission: AlbumPermission) -> Self { + match permission { + AlbumPermission::View => PostgresAlbumPermission::View, + AlbumPermission::Contribute => PostgresAlbumPermission::Contribute, + } + } +} + +impl From for AlbumShare { + fn from(pg_share: PostgresAlbumShare) -> Self { + AlbumShare { + album_id: pg_share.album_id, + user_id: pg_share.user_id, + permission: AlbumPermission::from(pg_share.permission), + } + } +} \ No newline at end of file diff --git a/libertas_infra/src/repositories/album_repository.rs b/libertas_infra/src/repositories/album_repository.rs index da3c6fc..7816002 100644 --- a/libertas_infra/src/repositories/album_repository.rs +++ b/libertas_infra/src/repositories/album_repository.rs @@ -7,6 +7,8 @@ use libertas_core::{ use sqlx::PgPool; use uuid::Uuid; +use crate::db_models::PostgresAlbum; + #[derive(Clone)] pub struct PostgresAlbumRepository { pool: PgPool, @@ -42,8 +44,8 @@ impl AlbumRepository for PostgresAlbumRepository { } async fn find_by_id(&self, id: Uuid) -> CoreResult> { - sqlx::query_as!( - Album, + let pg_album = sqlx::query_as!( + PostgresAlbum, r#" SELECT id, owner_id, name, description, is_public, created_at, updated_at FROM albums @@ -53,12 +55,13 @@ impl AlbumRepository for PostgresAlbumRepository { ) .fetch_optional(&self.pool) .await - .map_err(|e| CoreError::Database(e.to_string())) + .map_err(|e| CoreError::Database(e.to_string()))?; + Ok(pg_album.map(|a| a.into())) } async fn list_by_user(&self, user_id: Uuid) -> CoreResult> { - sqlx::query_as!( - Album, + let pg_albums = sqlx::query_as!( + PostgresAlbum, r#" SELECT id, owner_id, name, description, is_public, created_at, updated_at FROM albums @@ -68,7 +71,9 @@ impl AlbumRepository for PostgresAlbumRepository { ) .fetch_all(&self.pool) .await - .map_err(|e| CoreError::Database(e.to_string())) + .map_err(|e| CoreError::Database(e.to_string()))?; + + Ok(pg_albums.into_iter().map(|a| a.into()).collect()) } async fn add_media_to_album(&self, album_id: Uuid, media_ids: &[Uuid]) -> CoreResult<()> { diff --git a/libertas_infra/src/repositories/album_share_repository.rs b/libertas_infra/src/repositories/album_share_repository.rs index 165307c..d1c51c3 100644 --- a/libertas_infra/src/repositories/album_share_repository.rs +++ b/libertas_infra/src/repositories/album_share_repository.rs @@ -1,11 +1,10 @@ use async_trait::async_trait; use libertas_core::{ - error::{CoreError, CoreResult}, - models::AlbumPermission, - repositories::AlbumShareRepository, + error::{CoreError, CoreResult}, models::AlbumPermission, repositories::AlbumShareRepository }; use sqlx::PgPool; use uuid::Uuid; +use crate::db_models::PostgresAlbumPermission; #[derive(Clone)] pub struct PostgresAlbumShareRepository { @@ -35,7 +34,7 @@ impl AlbumShareRepository for PostgresAlbumShareRepository { "#, album_id, user_id, - permission as AlbumPermission, + PostgresAlbumPermission::from(permission) as PostgresAlbumPermission, ) .execute(&self.pool) .await @@ -51,7 +50,7 @@ impl AlbumShareRepository for PostgresAlbumShareRepository { ) -> CoreResult> { let result = sqlx::query!( r#" - SELECT permission as "permission: AlbumPermission" + SELECT permission as "permission: PostgresAlbumPermission" FROM album_shares WHERE album_id = $1 AND user_id = $2 "#, @@ -62,7 +61,7 @@ impl AlbumShareRepository for PostgresAlbumShareRepository { .await .map_err(|e| CoreError::Database(e.to_string()))?; - Ok(result.map(|row| row.permission)) + Ok(result.map(|row| row.permission.into())) } async fn is_media_in_shared_album(&self, media_id: Uuid, user_id: Uuid) -> CoreResult { diff --git a/libertas_infra/src/repositories/media_repository.rs b/libertas_infra/src/repositories/media_repository.rs index 1ed7710..a9d3e05 100644 --- a/libertas_infra/src/repositories/media_repository.rs +++ b/libertas_infra/src/repositories/media_repository.rs @@ -7,6 +7,8 @@ use libertas_core::{ use sqlx::PgPool; use uuid::Uuid; +use crate::db_models::PostgresMedia; + #[derive(Clone)] pub struct PostgresMediaRepository { pool: PgPool, @@ -44,8 +46,8 @@ impl MediaRepository for PostgresMediaRepository { } async fn find_by_hash(&self, hash: &str) -> CoreResult> { - sqlx::query_as!( - Media, + let pg_media = sqlx::query_as!( + PostgresMedia, r#" SELECT id, owner_id, storage_path, original_filename, mime_type, hash, created_at, extracted_location, width, height @@ -56,12 +58,14 @@ impl MediaRepository for PostgresMediaRepository { ) .fetch_optional(&self.pool) .await - .map_err(|e| CoreError::Database(e.to_string())) + .map_err(|e| CoreError::Database(e.to_string()))?; + + Ok(pg_media.map(|m| m.into())) } async fn find_by_id(&self, id: Uuid) -> CoreResult> { - sqlx::query_as!( - Media, + let pg_media = sqlx::query_as!( + PostgresMedia, r#" SELECT id, owner_id, storage_path, original_filename, mime_type, hash, created_at, extracted_location, width, height @@ -72,12 +76,14 @@ impl MediaRepository for PostgresMediaRepository { ) .fetch_optional(&self.pool) .await - .map_err(|e| CoreError::Database(e.to_string())) + .map_err(|e| CoreError::Database(e.to_string()))?; + + Ok(pg_media.map(|m| m.into())) } async fn list_by_user(&self, user_id: Uuid) -> CoreResult> { - sqlx::query_as!( - Media, + let pg_media = sqlx::query_as!( + PostgresMedia, r#" SELECT id, owner_id, storage_path, original_filename, mime_type, hash, created_at, extracted_location, width, height @@ -88,7 +94,9 @@ impl MediaRepository for PostgresMediaRepository { ) .fetch_all(&self.pool) .await - .map_err(|e| CoreError::Database(e.to_string())) + .map_err(|e| CoreError::Database(e.to_string()))?; + + Ok(pg_media.into_iter().map(|m| m.into()).collect()) } async fn update_metadata( diff --git a/libertas_infra/src/repositories/user_repository.rs b/libertas_infra/src/repositories/user_repository.rs index 09793d7..069ddf4 100644 --- a/libertas_infra/src/repositories/user_repository.rs +++ b/libertas_infra/src/repositories/user_repository.rs @@ -1,11 +1,13 @@ use async_trait::async_trait; use libertas_core::{ error::{CoreError, CoreResult}, - models::{Role, User}, + models::User, repositories::UserRepository, }; use sqlx::{PgPool, SqlitePool, types::Uuid}; +use crate::db_models::PostgresUser; + #[derive(Clone)] pub struct PostgresUserRepository { pool: PgPool, @@ -54,12 +56,12 @@ impl UserRepository for PostgresUserRepository { } async fn find_by_email(&self, email: &str) -> CoreResult> { - sqlx::query_as!( - User, + let pg_user = sqlx::query_as!( + PostgresUser, r#" SELECT id, username, email, hashed_password, created_at, updated_at, - role as "role: Role", + role, storage_quota, storage_used FROM users WHERE email = $1 @@ -68,17 +70,18 @@ impl UserRepository for PostgresUserRepository { ) .fetch_optional(&self.pool) .await - .map_err(|e| CoreError::Database(e.to_string())) + .map_err(|e| CoreError::Database(e.to_string()))?; + + Ok(pg_user.map(|u| u.into())) } async fn find_by_username(&self, username: &str) -> CoreResult> { - sqlx::query_as!( - User, + let pg_user = sqlx::query_as!( + PostgresUser, r#" SELECT id, username, email, hashed_password, created_at, updated_at, - role as "role: Role", - storage_quota, storage_used + role, storage_quota, storage_used FROM users WHERE username = $1 "#, @@ -86,16 +89,18 @@ impl UserRepository for PostgresUserRepository { ) .fetch_optional(&self.pool) .await - .map_err(|e| CoreError::Database(e.to_string())) + .map_err(|e| CoreError::Database(e.to_string()))?; + + Ok(pg_user.map(|u| u.into())) } async fn find_by_id(&self, id: Uuid) -> CoreResult> { - sqlx::query_as!( - User, + let pg_user = sqlx::query_as!( + PostgresUser, r#" SELECT id, username, email, hashed_password, created_at, updated_at, - role as "role: Role", + role, storage_quota, storage_used FROM users WHERE id = $1 @@ -104,7 +109,8 @@ impl UserRepository for PostgresUserRepository { ) .fetch_optional(&self.pool) .await - .map_err(|e| CoreError::Database(e.to_string())) + .map_err(|e| CoreError::Database(e.to_string()))?; + Ok(pg_user.map(|u| u.into())) } async fn update_storage_used(&self, user_id: Uuid, bytes: i64) -> CoreResult<()> { diff --git a/libertas_worker/src/config.rs b/libertas_worker/src/config.rs index a239a55..0236691 100644 --- a/libertas_worker/src/config.rs +++ b/libertas_worker/src/config.rs @@ -7,12 +7,13 @@ pub fn load_config() -> CoreResult { Ok(Config { database: DatabaseConfig { db_type: DatabaseType::Postgres, - url: "postgres://postgres:postgres@localhost:5432/libertas_db".to_string(), + url: "postgres://libertas:libertas_password@localhost:5436/libertas_db".to_string(), }, server_address: "127.0.0.1:8080".to_string(), jwt_secret: "super_secret_jwt_key".to_string(), media_library_path: "media_library".to_string(), broker_url: "nats://localhost:4222".to_string(), max_upload_size_mb: Some(100), + default_storage_quota_gb: Some(10), }) }