diff --git a/plume-models/src/medias.rs b/plume-models/src/medias.rs index 1882b8fe..ba477657 100644 --- a/plume-models/src/medias.rs +++ b/plume-models/src/medias.rs @@ -19,7 +19,7 @@ use url::Url; const REMOTE_MEDIA_DIRECTORY: &str = "remote"; -#[derive(Clone, Identifiable, Queryable)] +#[derive(Clone, Identifiable, Queryable, AsChangeset)] pub struct Media { pub id: i32, pub file_path: String, @@ -225,32 +225,65 @@ impl Media { .copy_to(&mut dest) .ok()?; - // TODO: upsert - Media::insert( - conn, - NewMedia { - file_path: path.to_str()?.to_string(), - alt_text: image.object_props.content_string().ok()?, - is_remote: false, - remote_url: None, - sensitive: image.object_props.summary_string().is_ok(), - content_warning: image.object_props.summary_string().ok(), - owner_id: User::from_id( + Media::find_by_file_path(conn, &path.to_str()?) + .and_then(|mut media| { + let mut updated = false; + + let alt_text = image.object_props.content_string().ok()?; + let sensitive = image.object_props.summary_string().is_ok(); + let content_warning = image.object_props.summary_string().ok(); + if media.alt_text != alt_text { + media.alt_text = alt_text; + updated = true; + } + if media.is_remote { + media.is_remote = false; + updated = true; + } + if media.remote_url.is_some() { + media.remote_url = None; + updated = true; + } + if media.sensitive != sensitive { + media.sensitive = sensitive; + updated = true; + } + if media.content_warning != content_warning { + media.content_warning = content_warning; + updated = true; + } + if updated { + diesel::update(&media).set(&media).execute(&**conn)?; + } + Ok(media) + }) + .or_else(|_| { + Media::insert( conn, - image - .object_props - .attributed_to_link_vec::() - .ok()? - .into_iter() - .next()? - .as_ref(), - None, - CONFIG.proxy(), + NewMedia { + file_path: path.to_str()?.to_string(), + alt_text: image.object_props.content_string().ok()?, + is_remote: false, + remote_url: None, + sensitive: image.object_props.summary_string().is_ok(), + content_warning: image.object_props.summary_string().ok(), + owner_id: User::from_id( + conn, + image + .object_props + .attributed_to_link_vec::() + .ok()? + .into_iter() + .next()? + .as_ref(), + None, + CONFIG.proxy(), + ) + .map_err(|(_, e)| e)? + .id, + }, ) - .map_err(|(_, e)| e)? - .id, - }, - ) + }) } pub fn get_media_processor<'a>(conn: &'a Connection, user: Vec<&User>) -> MediaProcessor<'a> {