Verify imported audio and keep resolved uploads out of the review queue
Build and Publish / Build and Publish Docker Image (push) Successful in 2m31s

This commit is contained in:
Aleksandr Bogomiakov committed 2026-11-24 19:38:16 +02:00
1 parent 2352f359f4
commit 2a7179702b
24 files changed
+1760 -559

No files matched your search

+19 -1
View File
@@ -11,6 +11,12 @@ use super::dto::NormalizedFields;
#[derive(Debug)]
pub struct DuplicateReview(pub String);
impl DuplicateReview {
pub fn is_recorded(message: Option<&str>) -> bool {
message.is_some_and(|message| message.starts_with("Duplicate check needs review:"))
}
}
impl std::fmt::Display for DuplicateReview {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "Duplicate check needs review: {}", self.0)
@@ -242,6 +248,17 @@ async fn probe(path: &Path) -> Result<AudioInfo> {
})
}
pub async fn verify_separate_recording(path: &Path) -> Result<()> {
let info = probe(path)
.await
.context("cannot inspect incoming recording")?;
ensure!(
info.duration > 0.0,
"incoming recording has no audio duration"
);
Ok(())
}
#[derive(Deserialize)]
struct AudioFingerprint {
duration: f64,
@@ -443,7 +460,8 @@ pub async fn merge_existing(
}
// A repeated YouTube import must still resolve to this existing media ID.
if let Some(sha) = context["sha256"].as_str() {
if let Err(error) = crate::import_playlists::link_media(pool, sha, candidate.media_id).await {
if let Err(error) = crate::import_playlists::link_media(pool, sha, candidate.media_id).await
{
tracing::warn!(%error, "could not link deduplicated import to destination playlists");
}
if let Err(error) = sqlx::query(
+57 -5
View File
@@ -21,10 +21,7 @@ pub async fn move_to_storage(
filename: &str,
source: &Path,
) -> anyhow::Result<MoveOutcome> {
let artist_dir = sanitize_dir_name(artist);
let album_dir = sanitize_dir_name(album);
let dest_dir = storage_dir.join(&artist_dir).join(&album_dir);
let dest_dir = album_directory(storage_dir, artist, album);
tokio::fs::create_dir_all(&dest_dir).await?;
let mut dest = dest_dir.join(filename);
@@ -54,6 +51,54 @@ pub async fn move_to_storage(
Ok(MoveOutcome::Moved(dest))
}
fn album_directory(storage_dir: &Path, artist: &str, album: &str) -> PathBuf {
storage_dir
.join(sanitize_dir_name(artist))
.join(sanitize_dir_name(album))
}
/// Recover a file published before an interrupted catalog write, including a
/// destination that move_to_storage renamed to avoid a filename collision.
pub async fn find_moved_file(
storage_dir: &Path,
artist: &str,
album: &str,
filename: &str,
sha256: &str,
) -> anyhow::Result<Option<PathBuf>> {
if sha256.is_empty() {
return Ok(None);
}
let directory = album_directory(storage_dir, artist, album);
let mut entries = match tokio::fs::read_dir(directory).await {
Ok(entries) => entries,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
Err(error) => return Err(error.into()),
};
let name = Path::new(filename);
let stem = name.file_stem().and_then(|s| s.to_str()).unwrap_or("audio");
let ext = name.extension().and_then(|s| s.to_str()).unwrap_or("audio");
let prefix = format!("{stem} [");
let suffix = format!("].{ext}");
while let Some(entry) = entries.next_entry().await? {
let entry_name = entry.file_name();
let Some(entry_name) = entry_name.to_str() else {
continue;
};
let is_collision = entry_name
.strip_prefix(&prefix)
.and_then(|name| name.strip_suffix(&suffix))
.is_some_and(|id| uuid::Uuid::parse_str(id).is_ok());
if (entry_name == filename || is_collision)
&& entry.file_type().await?.is_file()
&& sha256_file(&entry.path()).await? == sha256
{
return Ok(Some(entry.path()));
}
}
Ok(None)
}
/// Copy into the destination filesystem, then expose the complete file without
/// replacing an existing destination. The source remains available on errors.
pub async fn publish_copy(source: &Path, destination: &Path) -> anyhow::Result<()> {
@@ -131,7 +176,14 @@ mod tests {
};
assert_ne!(new, old);
assert_eq!(tokio::fs::read(&old).await.unwrap(), b"original recording");
assert_eq!(tokio::fs::read(new).await.unwrap(), b"different recording");
assert_eq!(tokio::fs::read(&new).await.unwrap(), b"different recording");
let sha256 = sha256_file(&new).await.unwrap();
assert_eq!(
find_moved_file(&storage, "Artist", "Album", "song.mp3", &sha256)
.await
.unwrap(),
Some(new)
);
tokio::fs::remove_dir_all(root).await.unwrap();
}
}
+45 -30
View File
@@ -77,46 +77,61 @@ pub async fn find_similar_releases(
.collect())
}
/// Check if a file with the given SHA-256 hash is actively used in the library.
/// Returns true only if a media_file with this hash exists AND at least one
/// track references it via audio_file_id. Orphaned media_files (no track)
/// are ignored so that re-discovery is possible after the user deletes
/// artists/releases/tracks.
pub async fn file_hash_exists(pool: &PgPool, sha256: &str) -> anyhow::Result<bool> {
sqlx::query_scalar(
"SELECT EXISTS(SELECT 1 FROM furumusic__media_file mf \
JOIN furumusic__track t ON t.audio_file_id = mf.id \
WHERE mf.sha256_hash = $1)",
)
.bind(sha256)
.fetch_one(pool)
.await
.map_err(Into::into)
}
/// Verify the bytes on disk as well as the database hash before dropping an
/// inbox upload. Stale catalog hashes must not discard a replacement file.
pub async fn file_hash_exists_verified(
pub async fn verified_audio_media(
pool: &PgPool,
sha256: &str,
storage_dir: &str,
) -> anyhow::Result<bool> {
let paths: Vec<String> = sqlx::query_scalar(
"SELECT DISTINCT mf.file_path FROM furumusic__media_file mf \
JOIN furumusic__track t ON t.audio_file_id = mf.id \
WHERE mf.sha256_hash = $1",
) -> anyhow::Result<Option<i64>> {
if sha256.is_empty() || storage_dir.is_empty() {
return Ok(None);
}
let paths: Vec<(i64, String)> = sqlx::query_as(
"SELECT mf.id, mf.file_path FROM furumusic__media_file mf
WHERE mf.file_type = 'audio' AND mf.sha256_hash = $1
AND EXISTS (SELECT 1 FROM furumusic__track t WHERE t.audio_file_id = mf.id)
ORDER BY mf.id",
)
.bind(sha256)
.fetch_all(pool)
.await?;
for path in paths {
if paths.is_empty() {
return Ok(None);
}
let library = match tokio::fs::canonicalize(storage_dir).await {
Ok(path) => path,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
Err(error) => return Err(error.into()),
};
let mut read_error = None;
for (id, path) in paths {
let path = crate::media_paths::resolve_media_file_path(storage_dir, &path);
if super::mover::sha256_file(&path)
.await
.is_ok_and(|actual| actual == sha256)
{
return Ok(true);
// A legacy absolute path or symlink can point straight back to the
// inbox. It does not provide an independent archived copy.
let physical = match tokio::fs::canonicalize(&path).await {
Ok(physical) if physical.starts_with(&library) => physical,
Ok(_) => continue,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => continue,
Err(error) => {
read_error = Some(
anyhow::Error::from(error).context(format!("resolving {}", path.display())),
);
continue;
}
};
match super::mover::sha256_file(&physical).await {
Ok(actual) if actual == sha256 => return Ok(Some(id)),
Ok(_) => {}
Err(error)
if error
.downcast_ref::<std::io::Error>()
.is_some_and(|e| e.kind() == std::io::ErrorKind::NotFound) => {}
Err(error) => read_error = Some(error.context(format!("reading {}", path.display()))),
}
}
Ok(false)
match read_error {
Some(error) => Err(error),
None => Ok(None),
}
}