// MMS attachments cached on disk in /media, next to the database, so // backups include them and they outlive voip.ms's copies. Files are named by // content hash; messages reference them via MediaRef.file. import { nativeImage, net } from 'electron' import crypto from 'node:crypto' import fs from 'node:fs' import path from 'node:path' import { extFor, guessMime } from '@shared/mime' import type { MediaRef } from '@shared/types' import type { MessageDb, NewMessage } from './db' // Long edge of a thumbnail: twice the chat's largest picture box, for HiDPI. const THUMB_EDGE = 720 export class MediaStore { private inflight = new Map>() constructor( readonly dir: string, private db: MessageDb, // How to fetch a MediaRef.url; Google Voice's gv: refs need its session. private fetchUrl: (url: string, at?: { id: number; index: number }) => Promise = (url) => net.fetch(url) ) {} filePath(file: string): string { return path.join(this.dir, path.basename(file)) } // A smaller copy of a still picture for the chat and Get info, made once // and kept in /thumbs (outside media/, so it never goes to the // Rabbit or into backups as if it were an attachment). The chat shows // pictures at most 300x360, so a phone's 4000 px photo was being decoded // whole, again and again as rows scrolled in and out. Undefined = use the // original: already small, animated (GIF), or a format nativeImage can't read. async thumb(ref: MediaRef): Promise { if (!ref.file) return undefined const mime = ref.mime ?? guessMime(ref.file) ?? '' if (!mime.startsWith('image/') || mime === 'image/gif') return undefined const png = mime === 'image/png' || mime === 'image/webp' // may be see-through const out = path.join(this.dir, '..', 'thumbs', `${path.basename(ref.file)}.${THUMB_EDGE}.${png ? 'png' : 'jpg'}`) if (fs.existsSync(out)) return out const img = nativeImage.createFromPath(this.filePath(ref.file)) if (img.isEmpty()) return undefined const { width, height } = img.getSize() if (Math.max(width, height) <= THUMB_EDGE) return undefined const scale = THUMB_EDGE / Math.max(width, height) const small = img.resize({ width: Math.round(width * scale), height: Math.round(height * scale), quality: 'good' }) await fs.promises.mkdir(path.dirname(out), { recursive: true }) await fs.promises.writeFile(out, png ? small.toPNG() : small.toJPEG(85)) return out } save(data: Uint8Array, mime: string): string { const file = `${crypto.createHash('sha1').update(data).digest('hex')}.${extFor(mime)}` fs.mkdirSync(this.dir, { recursive: true }) const dest = this.filePath(file) if (!fs.existsSync(dest)) fs.writeFileSync(dest, data) return file } // The local copy of attachment `index` of message `id`, downloading it first // if we only have the provider's URL. Undefined when it can't be had. async resolve(id: number, index: number): Promise { const ref = this.db.getMessage(id)?.media?.[index] if (!ref) return undefined if (ref.file && fs.existsSync(this.filePath(ref.file))) return ref if (!ref.url) return undefined const key = `${id}/${index}` let p = this.inflight.get(key) if (!p) { p = this.download(id, index, ref.url).finally(() => this.inflight.delete(key)) this.inflight.set(key, p) } return p } private async download(id: number, index: number, url: string): Promise { try { const res = await this.fetchUrl(url, { id, index }) const header = res.headers.get('content-type')?.split(';')[0].trim() // voip.ms answers expired/unknown media with a 200 HTML page. if (!res.ok || header === 'text/html') return undefined const mime = header && header !== 'application/octet-stream' ? header : (guessMime(url) ?? 'application/octet-stream') const data = new Uint8Array(await res.arrayBuffer()) const file = this.save(data, mime) // Remember the size so the chat can reserve space before the image loads. const patch: MediaRef = { file, mime } if (mime.startsWith('image/')) { const size = nativeImage.createFromBuffer(Buffer.from(data)).getSize() if (size.width) Object.assign(patch, size) } this.db.setMediaFile(id, index, patch) return { url, ...patch } } catch { return undefined } } // Cache attachments of freshly synced messages right away, one at a time. prefetch(msgs: NewMessage[]): void { const todo = msgs.flatMap((m) => (m.media ?? []).map((_, i) => [m.id, i] as const)) void (async () => { for (const [id, i] of todo) await this.resolve(id, i) })() } }