| 1 | import { get, writable } from 'svelte/store'; |
| 2 | import { getAccountData, messageMediaUrl, setAccountData, uploadMedia } from './api'; |
| 3 | import { effectiveRooms } from './mute'; |
| 4 | import { arrivalIn, isRoomWatched } from './notification-model'; |
| 5 | import { |
| 6 | DEFAULT_MESSAGE_SOUND, |
| 7 | SOUND_MAX_BYTES, |
| 8 | parseMessageSound, |
| 9 | shouldPlaySound, |
| 10 | type MessageSoundSettings |
| 11 | } from './message-sound-model'; |
| 12 | import { selectedRoomId } from './store'; |
| 13 | import type { RoomSummary } from './types'; |
| 14 | |
| 15 | const EVENT_TYPE = 'dev.malice.message_sound'; |
| 16 | const DEFAULT_URL = '/sounds/message.wav'; |
| 17 | const CACHE_NAME = 'malice-sounds'; |
| 18 | |
| 19 | export const messageSound = writable<MessageSoundSettings>(DEFAULT_MESSAGE_SOUND); |
| 20 | |
| 21 | const resolved = new Map<string, Promise<string>>(); |
| 22 | let lastPlayedAt = 0; |
| 23 | |
| 24 | export async function loadMessageSound(): Promise<void> { |
| 25 | try { |
| 26 | messageSound.set(parseMessageSound(await getAccountData(EVENT_TYPE))); |
| 27 | } catch { |
| 28 | messageSound.set(DEFAULT_MESSAGE_SOUND); |
| 29 | } |
| 30 | } |
| 31 | |
| 32 | export async function saveMessageSound(settings: MessageSoundSettings): Promise<void> { |
| 33 | await setAccountData(EVENT_TYPE, { mode: settings.mode, sound: settings.sound }); |
| 34 | messageSound.set(settings); |
| 35 | } |
| 36 | |
| 37 | export function resetMessageSound(): void { |
| 38 | messageSound.set(DEFAULT_MESSAGE_SOUND); |
| 39 | for (const url of resolved.values()) void url.then((u) => URL.revokeObjectURL(u), () => undefined); |
| 40 | resolved.clear(); |
| 41 | } |
| 42 | |
| 43 | const cacheKey = (mxc: string) => `/__sounds/${encodeURIComponent(mxc)}`; |
| 44 | |
| 45 | async function remember(mxc: string, blob: Blob): Promise<void> { |
| 46 | try { |
| 47 | await (await caches.open(CACHE_NAME)).put(cacheKey(mxc), new Response(blob, { headers: { 'content-type': blob.type } })); |
| 48 | } catch {} |
| 49 | } |
| 50 | |
| 51 | async function fetchSound(mxc: string): Promise<Blob> { |
| 52 | try { |
| 53 | const hit = await (await caches.open(CACHE_NAME)).match(cacheKey(mxc)); |
| 54 | if (hit) return await hit.blob(); |
| 55 | } catch {} |
| 56 | const res = await fetch(messageMediaUrl(mxc, 'Full'), { credentials: 'same-origin' }); |
| 57 | if (!res.ok) throw new Error('Sound unavailable'); |
| 58 | const blob = await res.blob(); |
| 59 | await remember(mxc, blob); |
| 60 | return blob; |
| 61 | } |
| 62 | |
| 63 | function resolve(mxc: string | null): Promise<string> { |
| 64 | if (!mxc) return Promise.resolve(DEFAULT_URL); |
| 65 | let url = resolved.get(mxc); |
| 66 | if (!url) { |
| 67 | url = fetchSound(mxc).then( |
| 68 | (blob) => URL.createObjectURL(blob), |
| 69 | () => DEFAULT_URL |
| 70 | ); |
| 71 | resolved.set(mxc, url); |
| 72 | } |
| 73 | return url; |
| 74 | } |
| 75 | |
| 76 | export async function playMessageSound(): Promise<void> { |
| 77 | try { |
| 78 | const audio = new Audio(await resolve(get(messageSound).sound)); |
| 79 | await audio.play(); |
| 80 | } catch {} |
| 81 | } |
| 82 | |
| 83 | function decodes(file: File): Promise<boolean> { |
| 84 | return new Promise((done) => { |
| 85 | const url = URL.createObjectURL(file); |
| 86 | const audio = new Audio(); |
| 87 | const finish = (ok: boolean) => { |
| 88 | clearTimeout(timer); |
| 89 | URL.revokeObjectURL(url); |
| 90 | done(ok); |
| 91 | }; |
| 92 | const timer = setTimeout(() => finish(false), 5000); |
| 93 | audio.oncanplaythrough = () => finish(true); |
| 94 | audio.onerror = () => finish(false); |
| 95 | audio.preload = 'auto'; |
| 96 | audio.src = url; |
| 97 | }); |
| 98 | } |
| 99 | |
| 100 | export async function uploadMessageSound(file: File): Promise<void> { |
| 101 | if (!file.type.startsWith('audio/')) throw new Error('Choose an audio file.'); |
| 102 | if (file.size > SOUND_MAX_BYTES) throw new Error('Sounds must be smaller than 1 MB.'); |
| 103 | if (!(await decodes(file))) throw new Error('That audio file could not be played.'); |
| 104 | const { mxc } = await uploadMedia(file); |
| 105 | await remember(mxc, file); |
| 106 | await saveMessageSound({ ...get(messageSound), sound: mxc }); |
| 107 | } |
| 108 | |
| 109 | export function startMessageSound(): () => void { |
| 110 | let previous = new Map<string, RoomSummary>(); |
| 111 | const unsubscribe = effectiveRooms.subscribe((list) => { |
| 112 | const prior = previous; |
| 113 | previous = new Map(list.map((room) => [room.room_id, room])); |
| 114 | const now = Date.now(); |
| 115 | const mode = get(messageSound).mode; |
| 116 | for (const room of list) { |
| 117 | const arrival = arrivalIn(prior.get(room.room_id), room, now); |
| 118 | if (!arrival) continue; |
| 119 | if (isRoomWatched(room.room_id, get(selectedRoomId), document.visibilityState === 'visible', document.hasFocus())) continue; |
| 120 | if (!shouldPlaySound(mode, room, arrival, lastPlayedAt, now)) continue; |
| 121 | lastPlayedAt = now; |
| 122 | void playMessageSound(); |
| 123 | } |
| 124 | }); |
| 125 | return unsubscribe; |
| 126 | } |