Files
bubble/src/main/media.ts
T
trav dd994c5bc3 v0.8.8: bubble for Android 0.7.5 — the composer is always the small size; smoother scrolling past photos
Android: the composer used to shrink only with the keyboard up; now it is always that size (small text, tight padding, 60 dp buttons), and the keyboard only takes a line off the text box and the subtitle. Checked on the Rabbit with the dev app, at rest and typing.

Desktop: the chat and Get info show a smaller copy of each still picture (720 px long edge, made once into <dataDir>/thumbs) instead of decoding a phone's 4000 px photo every time a row scrolls in. Full size, Save and Copy still use the original; GIFs and pictures already that small are served as they are. Pictures decode off the main thread.
2026-11-13 12:01:56 -08:00

107 lines
4.7 KiB
TypeScript

// MMS attachments cached on disk in <dataDir>/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<string, Promise<MediaRef | undefined>>()
constructor(
readonly dir: string,
private db: MessageDb,
// How to fetch a MediaRef.url; Google Voice's gv:<id> refs need its session.
private fetchUrl: (url: string, at?: { id: number; index: number }) => Promise<Response> = (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 <dataDir>/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<string | undefined> {
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<MediaRef | undefined> {
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<MediaRef | undefined> {
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)
})()
}
}