Skip to content

Commit db127d4

Browse files
Detect image extension from magic bytes when syncing blobs
Fall back to magic byte detection (PNG, JPEG, GIF, WebP, SVG) when the attachment:// URI isn't found in the rumor content, preventing blobs from being saved as .bin files.
1 parent 91acf03 commit db127d4

1 file changed

Lines changed: 21 additions & 2 deletions

File tree

src-tauri/src/sync.rs

Lines changed: 21 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1470,8 +1470,10 @@ async fn download_missing_blobs(
14701470
}
14711471
};
14721472

1473-
// Determine extension from attachment references in the content
1474-
let ext = extract_blob_extension(&rumor.content, plaintext_hash).unwrap_or("bin".to_string());
1473+
// Determine extension from attachment references in the content, or detect from magic bytes
1474+
let ext = extract_blob_extension(&rumor.content, plaintext_hash)
1475+
.or_else(|| detect_image_extension(&plaintext))
1476+
.unwrap_or_else(|| "bin".to_string());
14751477

14761478
// Save locally
14771479
if let Err(e) = crate::attachments::save_blob(app, plaintext_hash, &ext, &plaintext) {
@@ -1482,6 +1484,23 @@ async fn download_missing_blobs(
14821484
}
14831485
}
14841486

1487+
/// Detect image format from magic bytes.
1488+
fn detect_image_extension(data: &[u8]) -> Option<String> {
1489+
if data.starts_with(&[0x89, 0x50, 0x4E, 0x47]) {
1490+
Some("png".to_string())
1491+
} else if data.starts_with(&[0xFF, 0xD8, 0xFF]) {
1492+
Some("jpg".to_string())
1493+
} else if data.starts_with(b"GIF8") {
1494+
Some("gif".to_string())
1495+
} else if data.starts_with(b"RIFF") && data.len() > 11 && &data[8..12] == b"WEBP" {
1496+
Some("webp".to_string())
1497+
} else if data.starts_with(b"<svg") || data.starts_with(b"<?xml") {
1498+
Some("svg".to_string())
1499+
} else {
1500+
None
1501+
}
1502+
}
1503+
14851504
/// Extract the file extension for a blob hash from markdown content.
14861505
pub(crate) fn extract_blob_extension(content: &str, hash: &str) -> Option<String> {
14871506
let pattern = format!("attachment://{hash}.");

0 commit comments

Comments
 (0)