| 1 | // Ported from crates/malice-core/src/media.rs's attachment_content_type, so the |
| 2 | // service worker can sniff decrypted bytes without a round trip to the wasm host. |
| 3 | |
| 4 | function startsWith(bytes: Uint8Array, prefix: number[]): boolean { |
| 5 | if (bytes.length < prefix.length) return false; |
| 6 | for (let i = 0; i < prefix.length; i++) { |
| 7 | if (bytes[i] !== prefix[i]) return false; |
| 8 | } |
| 9 | return true; |
| 10 | } |
| 11 | |
| 12 | function ascii(text: string): number[] { |
| 13 | return Array.from(text, (ch) => ch.charCodeAt(0)); |
| 14 | } |
| 15 | |
| 16 | function bytesEqual(bytes: Uint8Array, offset: number, text: string): boolean { |
| 17 | const wanted = ascii(text); |
| 18 | if (bytes.length < offset + wanted.length) return false; |
| 19 | for (let i = 0; i < wanted.length; i++) { |
| 20 | if (bytes[offset + i] !== wanted[i]) return false; |
| 21 | } |
| 22 | return true; |
| 23 | } |
| 24 | |
| 25 | export function imageContentType(bytes: Uint8Array): string | null { |
| 26 | if (startsWith(bytes, [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])) return 'image/png'; |
| 27 | if (startsWith(bytes, [0xff, 0xd8, 0xff])) return 'image/jpeg'; |
| 28 | if (bytesEqual(bytes, 0, 'GIF87a') || bytesEqual(bytes, 0, 'GIF89a')) return 'image/gif'; |
| 29 | if (bytes.length >= 12 && bytesEqual(bytes, 0, 'RIFF') && bytesEqual(bytes, 8, 'WEBP')) return 'image/webp'; |
| 30 | if (bytes.length >= 12 && bytesEqual(bytes, 4, 'ftyp') && (bytesEqual(bytes, 8, 'avif') || bytesEqual(bytes, 8, 'avis'))) { |
| 31 | return 'image/avif'; |
| 32 | } |
| 33 | return null; |
| 34 | } |
| 35 | |
| 36 | export function attachmentContentType(bytes: Uint8Array): string | null { |
| 37 | const image = imageContentType(bytes); |
| 38 | if (image) return image; |
| 39 | if (startsWith(bytes, [0x1a, 0x45, 0xdf, 0xa3])) return 'video/webm'; |
| 40 | if (bytes.length >= 12 && bytesEqual(bytes, 0, 'RIFF') && bytesEqual(bytes, 8, 'WAVE')) return 'audio/wav'; |
| 41 | if (bytesEqual(bytes, 0, 'OggS')) return 'audio/ogg'; |
| 42 | if (bytesEqual(bytes, 0, 'ID3') || startsWith(bytes, [0xff, 0xfb])) return 'audio/mpeg'; |
| 43 | if ( |
| 44 | bytes.length >= 12 && |
| 45 | bytesEqual(bytes, 4, 'ftyp') && |
| 46 | ['isom', 'iso2', 'mp41', 'mp42', 'avc1'].some((brand) => bytesEqual(bytes, 8, brand)) |
| 47 | ) { |
| 48 | return 'video/mp4'; |
| 49 | } |
| 50 | return null; |
| 51 | } |