|
| 1 | +use chrono::Utc; |
| 2 | +use sea_orm::entity::prelude::*; |
| 3 | +use sea_orm::*; |
| 4 | +use snafu::prelude::*; |
| 5 | + |
| 6 | +use crate::database::category; |
| 7 | +use crate::database::operation::{Operation, OperationId, OperationLog, OperationType, Table}; |
| 8 | +use crate::extractors::user::User; |
| 9 | +use crate::routes::content_folder::ContentFolderForm; |
| 10 | +use crate::state::AppState; |
| 11 | +use crate::state::logger::LoggerError; |
| 12 | + |
| 13 | +/// A content folder to store associated files. |
| 14 | +/// |
| 15 | +/// Each content folder has a name and an associated path on disk, a Category |
| 16 | +/// and it can have an Parent Content Folder (None if it's the first folder |
| 17 | +/// in category) |
| 18 | +#[sea_orm::model] |
| 19 | +#[derive(DeriveEntityModel, Clone, Debug, PartialEq, Eq)] |
| 20 | +#[sea_orm(table_name = "content_folder")] |
| 21 | +pub struct Model { |
| 22 | + #[sea_orm(primary_key)] |
| 23 | + pub id: i32, |
| 24 | + pub name: String, |
| 25 | + #[sea_orm(unique)] |
| 26 | + pub path: String, |
| 27 | + pub category_id: i32, |
| 28 | + #[sea_orm(belongs_to, from = "category_id", to = "id")] |
| 29 | + pub category: HasOne<category::Entity>, |
| 30 | + pub parent_id: Option<i32>, |
| 31 | + #[sea_orm(self_ref, relation_enum = "Parent", from = "parent_id", to = "id")] |
| 32 | + pub parent: HasOne<Entity>, |
| 33 | +} |
| 34 | + |
| 35 | +#[async_trait::async_trait] |
| 36 | +impl ActiveModelBehavior for ActiveModel {} |
| 37 | + |
| 38 | +#[derive(Debug, Snafu)] |
| 39 | +#[snafu(visibility(pub))] |
| 40 | +pub enum ContentFolderError { |
| 41 | + #[snafu(display("There is already a content folder called `{name}`"))] |
| 42 | + NameTaken { name: String }, |
| 43 | + #[snafu(display("There is already a content folder in dir `{path}`"))] |
| 44 | + PathTaken { path: String }, |
| 45 | + #[snafu(display("The Content Folder (Path: {path}) does not exist"))] |
| 46 | + NotFound { path: String }, |
| 47 | + #[snafu(display("Database error"))] |
| 48 | + DB { source: sea_orm::DbErr }, |
| 49 | + #[snafu(display("Failed to save the operation log"))] |
| 50 | + Logger { source: LoggerError }, |
| 51 | +} |
| 52 | + |
| 53 | +#[derive(Clone, Debug)] |
| 54 | +pub struct ContentFolderOperator { |
| 55 | + pub state: AppState, |
| 56 | + pub user: Option<User>, |
| 57 | +} |
| 58 | + |
| 59 | +impl ContentFolderOperator { |
| 60 | + pub fn new(state: AppState, user: Option<User>) -> Self { |
| 61 | + Self { state, user } |
| 62 | + } |
| 63 | + |
| 64 | + /// List Content Folders |
| 65 | + /// |
| 66 | + /// Should not fail, unless SQLite was corrupted for some reason. |
| 67 | + pub async fn list_by_parent_and_category( |
| 68 | + &self, |
| 69 | + parent_id: Option<i32>, |
| 70 | + category_id: i32, |
| 71 | + ) -> Result<Vec<Model>, ContentFolderError> { |
| 72 | + let mut query = Entity::find().filter(Column::CategoryId.eq(category_id)); |
| 73 | + // parent_id can be None when it's the first folder in categories |
| 74 | + match parent_id { |
| 75 | + Some(parent_id) => query = query.filter(Column::ParentId.eq(parent_id)), |
| 76 | + None => query = query.filter(Column::ParentId.is_null()), |
| 77 | + } |
| 78 | + |
| 79 | + query.all(&self.state.database).await.context(DBSnafu) |
| 80 | + } |
| 81 | + |
| 82 | + /// Find one Content Folder by path |
| 83 | + /// |
| 84 | + /// Should not fail, unless SQLite was corrupted for some reason. |
| 85 | + pub async fn find_by_path(&self, path: String) -> Result<Model, ContentFolderError> { |
| 86 | + let content_folder = Entity::find_by_path(path.clone()) |
| 87 | + .one(&self.state.database) |
| 88 | + .await |
| 89 | + .context(DBSnafu)?; |
| 90 | + |
| 91 | + match content_folder { |
| 92 | + Some(category) => Ok(category), |
| 93 | + None => Err(ContentFolderError::NotFound { path }), |
| 94 | + } |
| 95 | + } |
| 96 | + |
| 97 | + /// Find one Content Folder by ID |
| 98 | + /// |
| 99 | + /// Should not fail, unless SQLite was corrupted for some reason. |
| 100 | + pub async fn find_by_id(&self, id: i32) -> Result<Model, ContentFolderError> { |
| 101 | + let content_folder = Entity::find_by_id(id) |
| 102 | + .one(&self.state.database) |
| 103 | + .await |
| 104 | + .context(DBSnafu)?; |
| 105 | + |
| 106 | + match content_folder { |
| 107 | + Some(category) => Ok(category), |
| 108 | + None => Err(ContentFolderError::NotFound { |
| 109 | + path: id.to_string(), |
| 110 | + }), |
| 111 | + } |
| 112 | + } |
| 113 | + |
| 114 | + /// Create a new content folder |
| 115 | + /// |
| 116 | + /// Fails if: |
| 117 | + /// |
| 118 | + /// - name or path is already taken (they should be unique in one folder) |
| 119 | + /// - path parent directory does not exist (to avoid completely wrong paths) |
| 120 | + pub async fn create( |
| 121 | + &self, |
| 122 | + f: &ContentFolderForm, |
| 123 | + user: Option<User>, |
| 124 | + ) -> Result<Model, ContentFolderError> { |
| 125 | + // Check duplicates in same folder |
| 126 | + let list = self |
| 127 | + .list_by_parent_and_category(f.parent_id, f.category_id) |
| 128 | + .await?; |
| 129 | + |
| 130 | + if list.iter().any(|x| x.name == f.name) { |
| 131 | + return Err(ContentFolderError::NameTaken { |
| 132 | + name: f.name.clone(), |
| 133 | + }); |
| 134 | + } |
| 135 | + |
| 136 | + if list.iter().any(|x| x.path == f.path) { |
| 137 | + return Err(ContentFolderError::PathTaken { |
| 138 | + path: f.path.clone(), |
| 139 | + }); |
| 140 | + } |
| 141 | + |
| 142 | + let model = ActiveModel { |
| 143 | + name: Set(f.name.clone()), |
| 144 | + path: Set(f.path.clone()), |
| 145 | + category_id: Set(f.category_id), |
| 146 | + parent_id: Set(f.parent_id), |
| 147 | + ..Default::default() |
| 148 | + } |
| 149 | + .save(&self.state.database) |
| 150 | + .await |
| 151 | + .context(DBSnafu)?; |
| 152 | + |
| 153 | + // Should not fail |
| 154 | + let model = model.try_into_model().unwrap(); |
| 155 | + |
| 156 | + let operation_log = OperationLog { |
| 157 | + user, |
| 158 | + date: Utc::now(), |
| 159 | + table: Table::ContentFolder, |
| 160 | + operation: OperationType::Create, |
| 161 | + operation_id: OperationId { |
| 162 | + object_id: model.id.to_owned(), |
| 163 | + name: f.name.to_string(), |
| 164 | + }, |
| 165 | + operation_form: Some(Operation::ContentFolder(f.clone())), |
| 166 | + }; |
| 167 | + |
| 168 | + self.state |
| 169 | + .logger |
| 170 | + .write(operation_log) |
| 171 | + .await |
| 172 | + .context(LoggerSnafu)?; |
| 173 | + |
| 174 | + Ok(model) |
| 175 | + } |
| 176 | +} |
0 commit comments