-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcontent_folder.rs
More file actions
230 lines (202 loc) · 7.04 KB
/
content_folder.rs
File metadata and controls
230 lines (202 loc) · 7.04 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
use chrono::Utc;
use sea_orm::entity::prelude::*;
use sea_orm::*;
use snafu::prelude::*;
use crate::database::category::{self, CategoryError, CategoryOperator};
use crate::database::operation::{Operation, OperationId, OperationLog, OperationType, Table};
use crate::extractors::user::User;
use crate::routes::content_folder::ContentFolderForm;
use crate::state::AppState;
use crate::state::logger::LoggerError;
/// A content folder to store associated files.
///
/// Each content folder has a name and an associated path on disk, a Category
/// and it can have an Parent Content Folder (None if it's the first folder
/// in category)
#[sea_orm::model]
#[derive(DeriveEntityModel, Clone, Debug, PartialEq, Eq)]
#[sea_orm(table_name = "content_folder")]
pub struct Model {
#[sea_orm(primary_key)]
pub id: i32,
pub name: String,
#[sea_orm(unique)]
pub path: String,
pub category_id: i32,
#[sea_orm(belongs_to, from = "category_id", to = "id")]
pub category: HasOne<category::Entity>,
pub parent_id: Option<i32>,
#[sea_orm(self_ref, relation_enum = "Parent", from = "parent_id", to = "id")]
pub parent: HasOne<Entity>,
}
#[async_trait::async_trait]
impl ActiveModelBehavior for ActiveModel {}
#[derive(Debug, Snafu)]
#[snafu(visibility(pub))]
pub enum ContentFolderError {
#[snafu(display("There is already a content folder called `{name}`"))]
NameTaken { name: String },
#[snafu(display("There is already a content folder in dir `{path}`"))]
PathTaken { path: String },
#[snafu(display("The Content Folder (Path: {path}) does not exist"))]
NotFound { path: String },
#[snafu(display("Database error"))]
DB { source: sea_orm::DbErr },
#[snafu(display("Failed to save the operation log"))]
Logger { source: LoggerError },
#[snafu(display("Category operation failed"))]
Category { source: CategoryError },
}
#[derive(Clone, Debug)]
pub struct ContentFolderOperator {
pub state: AppState,
pub user: Option<User>,
}
impl ContentFolderOperator {
pub fn new(state: AppState, user: Option<User>) -> Self {
Self { state, user }
}
/// list All child folders for 1 folder
///
/// Should not fail, unless SQLite was corrupted for some reason.
pub async fn list_child_folders(
&self,
content_folder_id: i32,
) -> Result<Vec<Model>, ContentFolderError> {
Entity::find()
.filter(Column::ParentId.eq(content_folder_id))
.all(&self.state.database)
.await
.context(DBSnafu)
}
/// Find one Content Folder by path
///
/// Should not fail, unless SQLite was corrupted for some reason.
pub async fn find_by_path(&self, path: String) -> Result<Model, ContentFolderError> {
let content_folder = Entity::find_by_path(path.clone())
.one(&self.state.database)
.await
.context(DBSnafu)?;
match content_folder {
Some(category) => Ok(category),
None => Err(ContentFolderError::NotFound { path }),
}
}
/// Find one Content Folder by ID
///
/// Should not fail, unless SQLite was corrupted for some reason.
pub async fn find_by_id(&self, id: i32) -> Result<Model, ContentFolderError> {
let content_folder = Entity::find_by_id(id)
.one(&self.state.database)
.await
.context(DBSnafu)?;
match content_folder {
Some(category) => Ok(category),
None => Err(ContentFolderError::NotFound {
path: id.to_string(),
}),
}
}
/// Create a new content folder
///
/// Fails if:
///
/// - name or path is already taken (they should be unique in one folder)
/// - path parent directory does not exist (to avoid completely wrong paths)
pub async fn create(
&self,
f: &ContentFolderForm,
user: Option<User>,
) -> Result<Model, ContentFolderError> {
// Check duplicates in same folder
let list = if let Some(parent_id) = f.parent_id {
self.list_child_folders(parent_id).await?
} else {
let category = CategoryOperator::new(self.state.clone(), None);
category
.list_folders(f.category_id)
.await
.context(CategorySnafu)?
};
if list.iter().any(|x| x.name == f.name) {
return Err(ContentFolderError::NameTaken {
name: f.name.clone(),
});
}
if list.iter().any(|x| x.path == f.path) {
return Err(ContentFolderError::PathTaken {
path: f.path.clone(),
});
}
let model = ActiveModel {
name: Set(f.name.clone()),
path: Set(f.path.clone()),
category_id: Set(f.category_id),
parent_id: Set(f.parent_id),
..Default::default()
}
.save(&self.state.database)
.await
.context(DBSnafu)?;
// Should not fail
let model = model.try_into_model().unwrap();
let operation_log = OperationLog {
user,
date: Utc::now(),
table: Table::ContentFolder,
operation: OperationType::Create,
operation_id: OperationId {
object_id: model.id.to_owned(),
name: f.name.to_string(),
},
operation_form: Some(Operation::ContentFolder(f.clone())),
};
self.state
.logger
.write(operation_log)
.await
.context(LoggerSnafu)?;
Ok(model)
}
pub async fn ancestors(
&self,
folder: &Model,
) -> Result<ContentFolderAncestors, ContentFolderError> {
let mut ancestors = ContentFolderAncestors::default();
// Fetch the parent model
ancestors.parent = {
let Some(parent_id) = folder.parent_id else {
// No parent, no ancestors
return Ok(ancestors);
};
Some(self.find_by_id(parent_id).await?)
};
ancestors.breadcrumbs.push(PathBreadcrumb {
name: ancestors.parent.as_ref().unwrap().name.to_string(),
path: ancestors.parent.as_ref().unwrap().path.to_string(),
});
let mut next_id = ancestors.parent.as_ref().unwrap().parent_id;
while let Some(id) = next_id {
let folder = self.find_by_id(id).await?;
ancestors.breadcrumbs.push(PathBreadcrumb {
name: folder.name,
path: folder.path,
});
next_id = folder.parent_id;
}
// We walked from the bottom to the top of the folder hierarchy,
// but we want breadcrumbs navigation the other way around.
ancestors.breadcrumbs.reverse();
Ok(ancestors)
}
}
#[derive(Debug, Default)]
pub struct ContentFolderAncestors {
pub parent: Option<Model>,
pub breadcrumbs: Vec<PathBreadcrumb>,
}
#[derive(Clone, Debug, PartialEq)]
pub struct PathBreadcrumb {
pub name: String,
pub path: String,
}