atagen

malice

public
Star0
Watch0
5059ed753f8be331e027bc2b84dfbf30b240252e
2
ssh://brewery@pls.lobotomise.me:33/atagen/malice.git
web/src/lib/message-sound.tsTypescript101 lines3.2 KB
1
import { get, writable } from 'svelte/store';
2
import { getAccountData, messageMediaUrl, setAccountData, uploadMedia } from './api';
3
import {
4
  DEFAULT_MESSAGE_SOUND,
5
  SOUND_MAX_BYTES,
6
  parseMessageSound,
7
  type MessageSoundSettings
8
} from './message-sound-model';
9
10
const EVENT_TYPE = 'dev.malice.message_sound';
11
const DEFAULT_URL = '/sounds/message.wav';
12
const CACHE_NAME = 'malice-sounds';
13
14
export const messageSound = writable<MessageSoundSettings>(DEFAULT_MESSAGE_SOUND);
15
16
const resolved = new Map<string, Promise<string>>();
17
18
export async function loadMessageSound(): Promise<void> {
19
  try {
20
    messageSound.set(parseMessageSound(await getAccountData(EVENT_TYPE)));
21
  } catch {
22
    messageSound.set(DEFAULT_MESSAGE_SOUND);
23
  }
24
}
25
26
export async function saveMessageSound(settings: MessageSoundSettings): Promise<void> {
27
  await setAccountData(EVENT_TYPE, { mode: settings.mode, sound: settings.sound });
28
  messageSound.set(settings);
29
}
30
31
export function resetMessageSound(): void {
32
  messageSound.set(DEFAULT_MESSAGE_SOUND);
33
  for (const url of resolved.values()) void url.then((u) => URL.revokeObjectURL(u), () => undefined);
34
  resolved.clear();
35
}
36
37
const cacheKey = (mxc: string) => `/__sounds/${encodeURIComponent(mxc)}`;
38
39
async function remember(mxc: string, blob: Blob): Promise<void> {
40
  try {
41
    await (await caches.open(CACHE_NAME)).put(cacheKey(mxc), new Response(blob, { headers: { 'content-type': blob.type } }));
42
  } catch {}
43
}
44
45
async function fetchSound(mxc: string): Promise<Blob> {
46
  try {
47
    const hit = await (await caches.open(CACHE_NAME)).match(cacheKey(mxc));
48
    if (hit) return await hit.blob();
49
  } catch {}
50
  const res = await fetch(messageMediaUrl(mxc, 'Full'), { credentials: 'same-origin' });
51
  if (!res.ok) throw new Error('Sound unavailable');
52
  const blob = await res.blob();
53
  await remember(mxc, blob);
54
  return blob;
55
}
56
57
function resolve(mxc: string | null): Promise<string> {
58
  if (!mxc) return Promise.resolve(DEFAULT_URL);
59
  let url = resolved.get(mxc);
60
  if (!url) {
61
    url = fetchSound(mxc).then(
62
      (blob) => URL.createObjectURL(blob),
63
      () => DEFAULT_URL
64
    );
65
    resolved.set(mxc, url);
66
  }
67
  return url;
68
}
69
70
export async function playMessageSound(): Promise<void> {
71
  try {
72
    const audio = new Audio(await resolve(get(messageSound).sound));
73
    await audio.play();
74
  } catch {}
75
}
76
77
function decodes(file: File): Promise<boolean> {
78
  return new Promise((done) => {
79
    const url = URL.createObjectURL(file);
80
    const audio = new Audio();
81
    const finish = (ok: boolean) => {
82
      clearTimeout(timer);
83
      URL.revokeObjectURL(url);
84
      done(ok);
85
    };
86
    const timer = setTimeout(() => finish(false), 5000);
87
    audio.oncanplaythrough = () => finish(true);
88
    audio.onerror = () => finish(false);
89
    audio.preload = 'auto';
90
    audio.src = url;
91
  });
92
}
93
94
export async function uploadMessageSound(file: File): Promise<void> {
95
  if (!file.type.startsWith('audio/')) throw new Error('Choose an audio file.');
96
  if (file.size > SOUND_MAX_BYTES) throw new Error('Sounds must be smaller than 1 MB.');
97
  if (!(await decodes(file))) throw new Error('That audio file could not be played.');
98
  const { mxc } = await uploadMedia(file);
99
  await remember(mxc, file);
100
  await saveMessageSound({ ...get(messageSound), sound: mxc });
101
}