Skip to main content

sunday_slate/media/
mod.rs

1use std::{io, path::Path};
2
3use sqlx::SqliteConnection;
4use uuid::Uuid;
5
6use crate::AppError;
7
8pub mod model;
9pub mod process;
10pub mod store;
11
12pub use model::{Media, MediaId};
13
14pub(crate) async fn write_file_atomic(dir: &Path, file_name: &str, bytes: &[u8]) -> io::Result<()> {
15    let final_path = dir.join(file_name);
16    let tmp_path = dir.join(format!("{file_name}.tmp"));
17    if let Some(parent) = final_path.parent() {
18        tokio::fs::create_dir_all(parent).await?;
19    }
20
21    let result = async {
22        tokio::fs::write(&tmp_path, bytes).await?;
23        tokio::fs::rename(&tmp_path, &final_path).await
24    }
25    .await;
26
27    if result.is_err() {
28        let _ = tokio::fs::remove_file(&tmp_path).await;
29    }
30    result
31}
32
33/// `file_name` is the path relative to `media_dir`. `None` picks a uuid name.
34/// When `existing` is `Some`, the row's current path is kept.
35pub async fn save_png(
36    conn: &mut SqliteConnection,
37    media_dir: &Path,
38    existing: Option<MediaId>,
39    file_name: Option<&str>,
40    png: &[u8],
41    width: u32,
42    height: u32,
43) -> Result<MediaId, AppError> {
44    let byte_size = png.len() as i64;
45    let (id, file_name) = match existing {
46        Some(id) => {
47            let current = store::get(&mut *conn, id)
48                .await?
49                .expect("media foreign key references an existing row");
50            store::update_bytes(
51                &mut *conn,
52                id,
53                byte_size,
54                i64::from(width),
55                i64::from(height),
56            )
57            .await?;
58            (id, current.path)
59        }
60        None => {
61            let file_name = match file_name {
62                Some(name) => name.to_owned(),
63                None => format!("{}.png", Uuid::new_v4()),
64            };
65            let id = store::insert(
66                &mut *conn,
67                &file_name,
68                "image/png",
69                byte_size,
70                i64::from(width),
71                i64::from(height),
72            )
73            .await?;
74            (id, file_name)
75        }
76    };
77    write_file_atomic(media_dir, &file_name, png)
78        .await
79        .map_err(|e| AppError::Internal(e.to_string()))?;
80    Ok(id)
81}
82
83#[cfg(test)]
84mod tests {
85    use super::*;
86    use crate::media::store;
87
88    #[sqlx::test]
89    async fn save_png_uses_the_given_file_name(pool: sqlx::SqlitePool) {
90        let dir = tempfile::tempdir().expect("temp media dir");
91        let mut conn = pool.acquire().await.expect("conn");
92        let id = save_png(
93            &mut conn,
94            dir.path(),
95            None,
96            Some("headshots/00-TEST.png"),
97            b"png",
98            1,
99            1,
100        )
101        .await
102        .expect("save");
103        let media = store::get(&mut *conn, id).await.expect("get").expect("row");
104        assert_eq!(media.path, "headshots/00-TEST.png");
105        assert!(dir.path().join("headshots/00-TEST.png").is_file());
106    }
107
108    #[sqlx::test]
109    async fn save_png_without_a_name_uses_a_uuid(pool: sqlx::SqlitePool) {
110        let dir = tempfile::tempdir().expect("temp media dir");
111        let mut conn = pool.acquire().await.expect("conn");
112        let id = save_png(&mut conn, dir.path(), None, None, b"png", 1, 1)
113            .await
114            .expect("save");
115        let media = store::get(&mut *conn, id).await.expect("get").expect("row");
116        assert!(media.path.ends_with(".png"));
117        assert!(!media.path.contains('/'));
118        assert!(dir.path().join(&media.path).is_file());
119    }
120}