Skip to content

A platform for community discussion. Free, open, simple.

FEATURE: custom chat notification sound API (#44970)

Kris4060428dfe0e
diff --git a/plugins/chat/assets/javascripts/discourse/connectors/user-preferences-notifications/chat-notifications.gjs b/plugins/chat/assets/javascripts/discourse/connectors/user-preferences-notifications/chat-notifications.gjs
index 101acb8a322..d0f744f2f32 100644
--- a/plugins/chat/assets/javascripts/discourse/connectors/user-preferences-notifications/chat-notifications.gjs
+++ b/plugins/chat/assets/javascripts/discourse/connectors/user-preferences-notifications/chat-notifications.gjs
@@ -14,7 +14,7 @@ import {
HEADER_INDICATOR_PREFERENCE_ONLY_MENTIONS,
} from "discourse/plugins/chat/discourse/lib/chat-constants";
import {
- CHAT_SOUNDS,
+ chatSoundOptions,
normalizeChatSoundName,
} from "discourse/plugins/chat/discourse/services/chat-audio-manager";
@@ -44,10 +44,7 @@ export default class ChatNotifications extends Component {
}
get chatSounds() {
- return Object.keys(CHAT_SOUNDS).map((value) => ({
- name: i18n(`chat.sounds.${value}`),
- value,
- }));
+ return chatSoundOptions();
}
get headerIndicatorOptions() {
diff --git a/plugins/chat/assets/javascripts/discourse/pre-initializers/chat-plugin-api.js b/plugins/chat/assets/javascripts/discourse/pre-initializers/chat-plugin-api.js
index b9ed9d56c15..638960a5ed9 100644
--- a/plugins/chat/assets/javascripts/discourse/pre-initializers/chat-plugin-api.js
+++ b/plugins/chat/assets/javascripts/discourse/pre-initializers/chat-plugin-api.js
@@ -9,6 +9,11 @@ import {
registerTranscriptSourceType,
resetTranscriptSourceTypes,
} from "discourse/plugins/chat/discourse/lib/transcript-source-types";
+import {
+ registerChatSound,
+ resetChatSounds,
+ setDefaultChatSound,
+} from "discourse/plugins/chat/discourse/services/chat-audio-manager";
import { addChatDrawerStateCallback } from "discourse/plugins/chat/discourse/services/chat-state-manager";
/**
@@ -148,6 +153,42 @@ import { addChatDrawerStateCallback } from "discourse/plugins/chat/discourse/ser
* });
*/
+/**
+ * Registers a chat notification sound users can pick in their preferences.
+ * Registering a built-in name (eg: "classic") replaces that sound.
+ *
+ * @memberof PluginApi
+ * @instance
+ * @function registerChatSound
+ * @param {string} name - stored in the user's `chat_sound` option
+ * @param {Object} options
+ * @param {string|function} options.incoming - audio file URL, or a function receiving `(audioContext, startTime)` that schedules Web Audio nodes
+ * @param {string|function} [options.mention] - played for mentions, defaults to `incoming`
+ * @param {string} [options.label] - translation key for the preference option
+ * @param {string} [options.translatedLabel] - preference option text
+ * @example
+ *
+ * api.registerChatSound("ping", {
+ * incoming: settings.theme_uploads.ping,
+ * mention: settings.theme_uploads.ping_mention,
+ * label: themePrefix("chat_sounds.ping"),
+ * });
+ */
+
+/**
+ * Sets the sound used when a user hasn't picked one for new messages in the
+ * open channel, or picked one that no longer exists. Users who haven't opted
+ * into notification sounds stay silent.
+ *
+ * @memberof PluginApi
+ * @instance
+ * @function setDefaultChatSound
+ * @param {string} name - a built-in or registered sound
+ * @example
+ *
+ * api.setDefaultChatSound("ping");
+ */
+
export default {
name: "chat-plugin-api",
after: "inject-discourse-objects",
@@ -209,6 +250,22 @@ export default {
);
}
+ if (!apiPrototype.hasOwnProperty("registerChatSound")) {
+ Object.defineProperty(apiPrototype, "registerChatSound", {
+ value(name, options) {
+ registerChatSound(name, options);
+ },
+ });
+ }
+
+ if (!apiPrototype.hasOwnProperty("setDefaultChatSound")) {
+ Object.defineProperty(apiPrototype, "setDefaultChatSound", {
+ value(name) {
+ setDefaultChatSound(name);
+ },
+ });
+ }
+
if (!apiPrototype.hasOwnProperty("removeChatComposerSecondaryActions")) {
Object.defineProperty(
apiPrototype,
@@ -226,5 +283,6 @@ export default {
teardown() {
resetChatMessageDecorators();
resetTranscriptSourceTypes();
+ resetChatSounds();
},
};
diff --git a/plugins/chat/assets/javascripts/discourse/services/chat-audio-manager.js b/plugins/chat/assets/javascripts/discourse/services/chat-audio-manager.js
index 387327be77e..57fdf6d8f90 100644
--- a/plugins/chat/assets/javascripts/discourse/services/chat-audio-manager.js
+++ b/plugins/chat/assets/javascripts/discourse/services/chat-audio-manager.js
@@ -2,16 +2,9 @@ import { cancel } from "@ember/runloop";
import Service from "@ember/service";
import { isTesting } from "discourse/lib/environment";
import discourseLater from "discourse/lib/later";
+import { i18n } from "discourse-i18n";
-export const CHAT_SOUNDS = {
- classic: {},
- soft: {},
- retro: {},
- bubble: {},
- ethereal: {},
-};
-
-export const DEFAULT_SOUND_NAME = "classic";
+const BUILT_IN_DEFAULT_SOUND = "classic";
const THROTTLE_TIME = 3000; // 3 seconds
const RESUME_TIMEOUT = 500;
@@ -19,14 +12,6 @@ const MIN_GAIN = 0.001;
let sharedAudioContext;
-export function normalizeChatSoundName(name) {
- if (!name) {
- return null;
- }
-
- return CHAT_SOUNDS[name] ? name : DEFAULT_SOUND_NAME;
-}
-
async function getAudioContext() {
const AudioContext = window.AudioContext || window.webkitAudioContext;
@@ -102,7 +87,7 @@ function playSweep(ctx, options) {
oscillator.stop(options.endTime);
}
-const SOUND_SEQUENCES = {
+const BUILT_IN_SOUNDS = {
classic: {
incoming(ctx, now) {
playOscillator(ctx, "sine", 587.33, now, 0.1, 0.15);
@@ -197,6 +182,68 @@ const SOUND_SEQUENCES = {
},
};
+const sounds = new Map();
+let defaultSound;
+resetChatSounds();
+
+/**
+ * @param {string} name
+ * @param {Object} options
+ * @param {string|function} options.incoming - audio file URL, or a function receiving `(audioContext, startTime)`
+ * @param {string|function} [options.mention] - same as `incoming`, defaults to it
+ * @param {string} [options.label] - translation key for the preference option
+ * @param {string} [options.translatedLabel] - preference option text
+ */
+export function registerChatSound(
+ name,
+ { incoming, mention, label, translatedLabel }
+) {
+ sounds.set(name, {
+ incoming,
+ mention,
+ label: label ?? `chat.sounds.${name}`,
+ translatedLabel,
+ });
+}
+
+/**
+ * @param {string} name - a registered sound, used when the user's choice is
+ * unset or unknown
+ */
+export function setDefaultChatSound(name) {
+ defaultSound = name;
+}
+
+export function defaultChatSoundName() {
+ // checked on read so the default can be set before its sound is registered
+ return sounds.has(defaultSound) ? defaultSound : BUILT_IN_DEFAULT_SOUND;
+}
+
+export function resetChatSounds() {
+ sounds.clear();
+ defaultSound = BUILT_IN_DEFAULT_SOUND;
+
+ Object.entries(BUILT_IN_SOUNDS).forEach(([name, sequence]) =>
+ registerChatSound(name, sequence)
+ );
+}
+
+export function chatSoundOptions() {
+ return [...sounds].map(([value, { label, translatedLabel }]) => ({
+ name: translatedLabel ?? i18n(label),
+ value,
+ }));
+}
+
+export function normalizeChatSoundName(name) {
+ if (!name) {
+ return null;
+ }
+
+ // also covers sounds from a theme that has since been removed
+ return sounds.has(name) ? name : defaultChatSoundName();
+}
+
export default class ChatAudioManager extends Service {
canPlay = true;
@@ -233,10 +280,17 @@ export default class ChatAudioManager extends Service {
}
async #tryPlay(name, type) {
+ const sound = sounds.get(normalizeChatSoundName(name));
+ const source = sound[type] || sound.incoming;
+
try {
- const ctx = await getAudioContext();
- const sequence = SOUND_SEQUENCES[normalizeChatSoundName(name)];
- (sequence[type] || sequence.incoming)(ctx, ctx.currentTime);
+ if (typeof source === "string") {
+ // rejects when autoplay is blocked or the file can't be loaded
+ await new Audio(source).play();
+ } else {
+ const ctx = await getAudioContext();
+ source(ctx, ctx.currentTime);
+ }
return true;
} catch {
if (!isTesting()) {
diff --git a/plugins/chat/assets/javascripts/discourse/services/chat-new-message-announcer.js b/plugins/chat/assets/javascripts/discourse/services/chat-new-message-announcer.js
index a1d77e77dde..d7c161c1913 100644
--- a/plugins/chat/assets/javascripts/discourse/services/chat-new-message-announcer.js
+++ b/plugins/chat/assets/javascripts/discourse/services/chat-new-message-announcer.js
@@ -7,7 +7,7 @@ import {
confirmChatAlert,
} from "discourse/plugins/chat/discourse/lib/chat-alert-dedup";
import { messageAnnouncementText } from "discourse/plugins/chat/discourse/lib/chat-message-announcement";
-import { DEFAULT_SOUND_NAME } from "discourse/plugins/chat/discourse/services/chat-audio-manager";
+import { defaultChatSoundName } from "discourse/plugins/chat/discourse/services/chat-audio-manager";
// a burst is summarized rather than overwriting the shared live region message by message
const ANNOUNCEMENT_INTERVAL_MS = 1000;
@@ -99,7 +99,7 @@ export default class ChatNewMessageAnnouncer extends Service {
this.#lastMessageSoundAt = now;
// fall back to the default when no sound is selected.
- const sound = this.currentUser.chat_sound || DEFAULT_SOUND_NAME;
+ const sound = this.currentUser.chat_sound || defaultChatSoundName();
// throttle false so this doesn't consume the shared chat-audio throttle
const handled = await this.chatAudioManager.play(sound, {
throttle: false,
diff --git a/plugins/chat/test/javascripts/unit/services/chat-audio-manager-test.js b/plugins/chat/test/javascripts/unit/services/chat-audio-manager-test.js
index 4a5f8a9346e..161c0128f23 100644
--- a/plugins/chat/test/javascripts/unit/services/chat-audio-manager-test.js
+++ b/plugins/chat/test/javascripts/unit/services/chat-audio-manager-test.js
@@ -1,7 +1,13 @@
import { getOwner } from "@ember/owner";
import { setupTest } from "ember-qunit";
import { module, test } from "qunit";
-import { normalizeChatSoundName } from "discourse/plugins/chat/discourse/services/chat-audio-manager";
+import {
+ chatSoundOptions,
+ normalizeChatSoundName,
+ registerChatSound,
+ resetChatSounds,
+ setDefaultChatSound,
+} from "discourse/plugins/chat/discourse/services/chat-audio-manager";
class MockAudioContext {
state = "running";
@@ -77,6 +83,7 @@ module("Unit | Service | chat-audio-manager", function (hooks) {
hooks.afterEach(function () {
this.context.state = "closed";
window.AudioContext = this.originalAudioContext;
+ resetChatSounds();
});
test("plays the incoming variant for the selected theme", async function (assert) {
@@ -163,4 +170,102 @@ module("Unit | Service | chat-audio-manager", function (hooks) {
"uses the default theme for legacy sound names"
);
});
+
+ test("plays a registered sound sequence", async function (assert) {
+ registerChatSound("custom", {
+ incoming: (ctx) => ctx.createOscillator(),
+ translatedLabel: "Custom",
+ });
+
+ await this.subject.play("custom", { type: "mention" });
+
+ assert.strictEqual(
+ this.context.oscillators.length,
+ 1,
+ "falls back to the incoming variant"
+ );
+ assert.deepEqual(
+ chatSoundOptions().at(-1),
+ { name: "Custom", value: "custom" },
+ "lists the sound as a preference option"
+ );
+ assert.strictEqual(
+ normalizeChatSoundName("custom"),
+ "custom",
+ "keeps the registered name"
+ );
+ });
+
+ test("plays a registered audio file", async function (assert) {
+ const originalAudio = window.Audio;
+ const played = [];
+ let rejectPlay = false;
+
+ window.Audio = class {
+ constructor(src) {
+ this.src = src;
+ }
+
+ play() {
+ if (rejectPlay) {
+ return Promise.reject(new Error("NotAllowedError"));
+ }
+
+ played.push(this.src);
+ return Promise.resolve();
+ }
+ };
+
+ try {
+ registerChatSound("file", {
+ incoming: "/incoming.mp3",
+ mention: "/mention.mp3",
+ });
+
+ assert.true(
+ await this.subject.play("file", { type: "mention", throttle: false })
+ );
+ assert.deepEqual(played, ["/mention.mp3"], "plays the mention file");
+
+ rejectPlay = true;
+
+ assert.false(
+ await this.subject.play("file", { throttle: false }),
+ "reports a blocked file as unplayable"
+ );
+ } finally {
+ window.Audio = originalAudio;
+ }
+ });
+
+ test("falls back to a configured default sound", function (assert) {
+ setDefaultChatSound("custom");
+
+ assert.strictEqual(
+ normalizeChatSoundName("ding"),
+ "classic",
+ "ignores a default that isn't registered"
+ );
+
+ registerChatSound("custom", { incoming() {} });
+
+ assert.strictEqual(
+ normalizeChatSoundName("ding"),
+ "custom",
+ "uses the default once it is registered"
+ );
+ assert.strictEqual(
+ normalizeChatSoundName(null),
+ null,
+ "keeps an unset sound silent"
+ );
+
+ resetChatSounds();
+
+ assert.strictEqual(
+ normalizeChatSoundName("ding"),
+ "classic",
+ "restores the built-in default on reset"
+ );
+ });
});