add admin command to delete individual media files

This commit is contained in:
Benjamin Lee 2024-09-14 20:20:02 -07:00
parent 7672cc8473
commit d7087c66bb
No known key found for this signature in database
GPG key ID: FB9624E2885D55A4
4 changed files with 78 additions and 3 deletions

View file

@ -3,7 +3,7 @@ use std::io::Cursor;
use image::imageops::FilterType;
use ruma::{http_headers::ContentDisposition, OwnedMxcUri};
use tokio::{
fs::File,
fs::{self, File},
io::{AsyncReadExt, AsyncWriteExt},
};
use tracing::{debug, warn};
@ -110,6 +110,37 @@ impl Service {
}
}
/// Deletes a media object and all associated thumbnails.
#[tracing::instrument(skip(self))]
pub(crate) async fn delete(&self, mxc: OwnedMxcUri) -> Result<()> {
let (_, key) = self.db.search_file_metadata(mxc.clone(), 0, 0)?;
let thumbnails = self.db.search_thumbnails_metadata(mxc)?;
for (_, thumbnail_key) in thumbnails {
self.delete_by_key(thumbnail_key).await?;
}
self.delete_by_key(key).await?;
Ok(())
}
/// Deletes a specific media key, which may or may not be a thumbnail.
///
/// When deleting a non-thumbnail key with this method, the associated
/// thumbnails are not deleted.
async fn delete_by_key(&self, key: MediaFileKey) -> Result<()> {
let path = services().globals.get_media_file(&key);
match fs::remove_file(path).await {
Ok(()) => (),
// The file in the fs may already have been deleted by hand
Err(e) if e.kind() == std::io::ErrorKind::NotFound => (),
other_error => other_error?,
}
self.db.delete_file_metadata(key)?;
Ok(())
}
/// Returns width, height of the thumbnail and whether it should be cropped.
/// Returns None when the server should send the original file.
fn thumbnail_properties(