rustango_cms/
uploaded_file.rs1use chrono::{DateTime, Duration, Utc};
19use rustango::sql::Auto;
20use rustango::Model;
21use serde::{Deserialize, Serialize};
22
23pub const STALE_THRESHOLD_HOURS: i64 = 24;
26
27#[derive(Model, Debug, Clone, Serialize, Deserialize)]
28#[rustango(
29 table = "cms_uploaded_file",
30 app = "cms",
31 display = "original_filename",
32 admin(
33 list_display = "user_id, original_filename, mime, size, uploaded_at",
34 ordering = "-uploaded_at",
35 )
36)]
37pub struct UploadedFile {
38 #[rustango(primary_key)]
39 pub id: Auto<i64>,
40
41 #[rustango(fk = "rustango_users", on = "id", index)]
43 pub user_id: i64,
44
45 #[rustango(max_length = 512)]
49 pub storage_key: String,
50
51 #[rustango(max_length = 255)]
52 pub original_filename: String,
53
54 #[rustango(max_length = 128)]
55 pub mime: String,
56
57 pub size: i64,
58
59 #[rustango(max_length = 64, index)]
62 pub content_hash: String,
63
64 #[rustango(auto_now_add)]
65 pub uploaded_at: Auto<DateTime<Utc>>,
66}
67
68pub async fn create(
73 pool: &rustango::sql::Pool,
74 user_id: i64,
75 storage_key: String,
76 original_filename: String,
77 mime: String,
78 size: i64,
79 content_hash: String,
80) -> Result<UploadedFile, rustango::sql::ExecError> {
81 let mut row = UploadedFile {
82 id: Auto::Unset,
83 user_id,
84 storage_key,
85 original_filename,
86 mime,
87 size,
88 content_hash,
89 uploaded_at: Auto::Unset,
90 };
91 row.insert_pool(pool).await?;
92 Ok(row)
93}
94
95pub async fn get(
101 pool: &rustango::sql::Pool,
102 id: i64,
103) -> Result<Option<UploadedFile>, rustango::sql::ExecError> {
104 use rustango::core::Column as _;
105 use rustango::sql::FetcherPool as _;
106 let mut rows: Vec<UploadedFile> = UploadedFile::objects()
107 .where_(UploadedFile::id.eq(id))
108 .fetch(pool)
109 .await?;
110 Ok(rows.pop())
111}
112
113pub async fn delete(
120 pool: &rustango::sql::Pool,
121 id: i64,
122) -> Result<usize, rustango::sql::ExecError> {
123 use rustango::core::Column as _;
124 use rustango::sql::FetcherPool as _;
125 let rows: Vec<UploadedFile> = UploadedFile::objects()
126 .where_(UploadedFile::id.eq(id))
127 .fetch(pool)
128 .await?;
129 let mut removed = 0;
130 for row in rows {
131 row.delete_pool(pool).await?;
132 removed += 1;
133 }
134 Ok(removed)
135}
136
137pub async fn gc_stale(pool: &rustango::sql::Pool) -> Result<Vec<String>, rustango::sql::ExecError> {
145 use rustango::sql::FetcherPool as _;
146 let cutoff = Utc::now() - Duration::hours(STALE_THRESHOLD_HOURS);
147 let all: Vec<UploadedFile> = UploadedFile::objects().fetch(pool).await?;
148 let mut unlinked: Vec<String> = Vec::new();
149 for row in all {
150 let uploaded_at = row.uploaded_at.get().copied();
151 let Some(ts) = uploaded_at else {
152 continue;
153 };
154 if ts >= cutoff {
155 continue;
156 }
157 let key = row.storage_key.clone();
158 if row.delete_pool(pool).await.is_ok() {
159 unlinked.push(key);
160 }
161 }
162 Ok(unlinked)
163}