Files
ThreadNet-Web/apps/web/src/Notifier.ts
T

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

689 lines
27 KiB
TypeScript
Raw Normal View History

/*
2024-09-09 14:57:16 +01:00
Copyright 2024 New Vector Ltd.
Copyright 2020 The Matrix.org Foundation C.I.C.
2017-03-23 10:38:00 +00:00
Copyright 2017 Vector Creations Ltd
2017-08-25 13:35:04 +01:00
Copyright 2017 New Vector Ltd
2024-09-09 14:57:16 +01:00
Copyright 2015, 2016 OpenMarket Ltd
SPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only OR LicenseRef-Element-Commercial
2024-09-09 14:57:16 +01:00
Please see LICENSE files in the repository root for full details.
*/
import {
MatrixEvent,
MatrixEventEvent,
2025-02-05 13:25:06 +00:00
type Room,
RoomEvent,
ClientEvent,
MsgType,
SyncState,
2025-02-05 13:25:06 +00:00
type SyncStateData,
type IRoomTimelineData,
M_LOCATION,
2023-11-21 18:12:08 +01:00
EventType,
TypedEventEmitter,
} from "matrix-js-sdk/src/matrix";
2021-12-09 09:10:23 +00:00
import { logger } from "matrix-js-sdk/src/logger";
2025-02-05 13:25:06 +00:00
import { type PermissionChanged as PermissionChangedEvent } from "@matrix-org/analytics-events/types/typescript/PermissionChanged";
import { type SessionMembershipData, type IRTCNotificationContent } from "matrix-js-sdk/src/matrixrtc";
2020-08-05 11:07:10 +01:00
2020-07-10 19:07:11 +01:00
import { MatrixClientPeg } from "./MatrixClientPeg";
2022-07-29 13:43:29 +02:00
import { PosthogAnalytics } from "./PosthogAnalytics";
2020-07-10 19:07:11 +01:00
import SdkConfig from "./SdkConfig";
2017-04-23 06:06:23 +01:00
import PlatformPeg from "./PlatformPeg";
2019-12-19 18:19:56 -07:00
import * as TextForEvent from "./TextForEvent";
import * as Avatar from "./Avatar";
2020-05-13 20:41:41 -06:00
import dis from "./dispatcher/dispatcher";
2017-05-25 11:39:08 +01:00
import { _t } from "./languageHandler";
import Modal from "./Modal";
import SettingsStore from "./settings/SettingsStore";
2020-08-05 11:07:10 +01:00
import { hideToast as hideNotificationsToast } from "./toasts/DesktopNotificationsToast";
2021-06-29 13:11:58 +01:00
import { SettingLevel } from "./settings/SettingLevel";
import { isPushNotifyDisabled } from "./settings/controllers/NotificationControllers";
import UserActivity from "./UserActivity";
2021-06-29 13:11:58 +01:00
import { mediaFromMxc } from "./customisations/Media";
2021-07-02 12:12:41 +02:00
import ErrorDialog from "./components/views/dialogs/ErrorDialog";
2026-07-01 13:49:18 +01:00
import { SDKContextClass } from "./contexts/SDKContextClass";
2022-11-07 13:45:34 +00:00
import { localNotificationsAreSilenced, createLocalNotificationSettingsIfNeeded } from "./utils/notifications";
import { getIncomingCallToastKey, getNotificationEventSendTs, IncomingCallToast } from "./toasts/IncomingCallToast";
import ToastStore from "./stores/ToastStore";
import { stripPlainReply } from "./utils/Reply";
import { BackgroundAudio } from "./audio/BackgroundAudio";
/*
* Dispatches:
* {
* action: "notifier_enabled",
* value: boolean
* }
*/
const MAX_PENDING_ENCRYPTED = 20;
/**
* Minimum interval (in milliseconds) between two *audible* notification plays.
*
* Coalesces bursts of backlogged notifications into a single sound. This is the
* in-repo remedy for https://github.com/element-hq/element-web/issues/31996: on
* macOS Sequoia, waking from sleep delivers the entire sync backlog in one
* batch, so every backlogged notifying event fires {@link
* NotifierClass.playAudioNotification} near-simultaneously and the identical
* audio buffers superimpose into one loud "stacked" sound.
*
* The throttle is keyed on the resolved sound, so a backlog of identical sounds
* coalesces to one play while two genuinely *different* sounds (e.g. a custom
* per-room sound) arriving within the window each still play. A conservative
* window is intentional: merging a burst of the same sound is preferable to a
* wall of overlapping audio.
*
* NOTE: This only cures the sounds-enabled renderer Web-Audio path (the default
* config). It does NOT fix the variant where macOS Sequoia ignores the OS
* banner's `silent: true` and plays its own coalesced banner sound on wake;
* that is purely OS/Electron behaviour with no in-repo lever.
*/
export const NOTIFICATION_SOUND_THROTTLE_MS = 1000;
/*
Override both the content body and the TextForEvent handler for specific msgtypes, in notifications.
This is useful when the content body contains fallback text that would explain that the client can't handle a particular
type of tile.
*/
const msgTypeHandlers: Record<string, (event: MatrixEvent) => string | null> = {
[MsgType.KeyVerificationRequest]: (event: MatrixEvent) => {
2024-10-16 17:38:22 +01:00
const name = event.sender?.name;
return _t("notifier|m.key.verification.request", { name });
},
2022-03-10 19:03:31 +01:00
[M_LOCATION.name]: (event: MatrixEvent) => {
return TextForEvent.textForLocationEvent(event)();
},
2022-03-10 19:03:31 +01:00
[M_LOCATION.altName]: (event: MatrixEvent) => {
return TextForEvent.textForLocationEvent(event)();
},
2023-01-03 10:02:28 +01:00
[MsgType.Audio]: (event: MatrixEvent): string | null => {
return TextForEvent.textForEvent(event, MatrixClientPeg.safeGet());
2023-01-03 10:02:28 +01:00
},
};
/**
* Extracts plain text from a message body, replacing any spoilered content
* with '[Spoiler]' to prevent spoilers in desktop notifications.
*/
function getNotificationBodyWithoutSpoilers(ev: MatrixEvent): string {
const content = ev.getContent();
const plainBody = content.body ?? "";
const formattedBody = content.formatted_body;
if (typeof formattedBody !== "string" || !formattedBody.length) {
return plainBody;
}
/** Recursively walks HTML tree to hide spoilers. */
function replaceSpoilers(node: Node): Node {
if (node.nodeType !== Node.ELEMENT_NODE || !(node instanceof Element)) {
return node;
}
if (node.hasAttribute("data-mx-spoiler")) {
const e = document.createElement("span");
e.appendChild(document.createTextNode("[Spoiler]"));
return e;
}
for (const childNode of node.childNodes) {
node.replaceChild(replaceSpoilers(childNode), childNode);
}
return node;
}
try {
// Dev note: ideally we would reuse more of the existing rendering stack
// rather than re-parsing and updating the generated HTML here. However,
// that rendering stack is currently quite consolidated and cannot
// easily be refactored to allow the call-site to control how spoilers
// are rendered. The problem is that we now need two different output
// formats:
// - The existing format where spoilers are wrapped in html <span> tags
// - The new format where the spoilered text is replaced with [Spoiler]
const parser = new DOMParser();
const doc = parser.parseFromString(formattedBody, "text/html");
// Use textContent rather than innerHTML/outerHTML since textContent is
// XSS-safe and the input is untrusted.
return replaceSpoilers(doc.body).textContent ?? plainBody;
} catch {
return plainBody;
}
}
export const enum NotifierEvent {
NotificationHiddenChange = "notification_hidden_change",
}
interface EmittedEvents {
[NotifierEvent.NotificationHiddenChange]: (hidden: boolean) => void;
}
2026-04-29 09:46:09 +01:00
/**
* Type representing a notification sound setting
*/
export type NotificationSound = {
url: string;
name?: string;
type?: string;
size?: number;
};
class NotifierClass extends TypedEventEmitter<keyof EmittedEvents, EmittedEvents> {
2023-02-13 11:39:16 +00:00
private notifsByRoom: Record<string, Notification[]> = {};
// A list of event IDs that we've received but need to wait until
// they're decrypted until we decide whether to notify for them
// or not
2023-02-13 11:39:16 +00:00
private pendingEncryptedEventIds: string[] = [];
2023-02-13 11:39:16 +00:00
private toolbarHidden?: boolean;
private isSyncing?: boolean;
private backgroundAudio = new BackgroundAudio();
/**
* Per-sound timestamp (ms, from {@link Date.now}) of the last *audible* notification, keyed by the
* resolved sound (custom sound url, or `"default"`). Used to throttle a burst of backlogged
* notifications of the *same* sound into a single play while letting distinct sounds through -
* see {@link NOTIFICATION_SOUND_THROTTLE_MS}.
*/
private readonly lastAudioNotificationMs = new Map<string, number>();
public notificationMessageForEvent(ev: MatrixEvent): string | null {
const msgType = ev.getContent().msgtype;
if (msgType && msgTypeHandlers.hasOwnProperty(msgType)) {
return msgTypeHandlers[msgType](ev);
}
return TextForEvent.textForEvent(ev, MatrixClientPeg.safeGet());
2023-02-13 11:39:16 +00:00
}
2023-02-13 11:39:16 +00:00
// XXX: exported for tests
public displayPopupNotification(ev: MatrixEvent, room: Room): void {
2016-11-02 17:35:31 +00:00
const plaf = PlatformPeg.get();
const cli = MatrixClientPeg.safeGet();
2016-11-02 17:35:31 +00:00
if (!plaf) {
return;
}
if (!plaf.supportsNotifications() || !plaf.maySendNotifications()) {
return;
}
if (localNotificationsAreSilenced(cli)) {
return;
}
2017-04-23 06:06:23 +01:00
let msg = this.notificationMessageForEvent(ev);
if (!msg) return;
let title: string | undefined;
2017-04-23 06:06:23 +01:00
if (!ev.sender || room.name === ev.sender.name) {
title = room.name;
// notificationMessageForEvent includes sender, but we already have the sender here
const msgType = ev.getContent().msgtype;
if (ev.getContent().body && (!msgType || !msgTypeHandlers.hasOwnProperty(msgType))) {
msg = stripPlainReply(getNotificationBodyWithoutSpoilers(ev));
}
2017-04-23 06:06:23 +01:00
} else if (ev.getType() === "m.room.member") {
// context is all in the message here, we don't need
// to display sender info
title = room.name;
} else if (ev.sender) {
title = ev.sender.name + " (" + room.name + ")";
// notificationMessageForEvent includes sender, but we've just out sender in the title
const msgType = ev.getContent().msgtype;
if (ev.getContent().body && (!msgType || !msgTypeHandlers.hasOwnProperty(msgType))) {
msg = stripPlainReply(getNotificationBodyWithoutSpoilers(ev));
}
}
if (!title) return;
if (!this.isBodyEnabled()) {
msg = "";
}
let avatarUrl: string | null = null;
if (ev.sender && !SettingsStore.getValue("lowBandwidth")) {
avatarUrl = Avatar.avatarUrlForMember(ev.sender, 40, 40, "crop");
}
const notif = plaf.displayNotification(title, msg!, avatarUrl, room, ev);
2016-11-02 17:35:31 +00:00
// if displayNotification returns non-null, the platform supports
// clearing notifications later, so keep track of this.
if (notif) {
if (this.notifsByRoom[ev.getRoomId()!] === undefined) this.notifsByRoom[ev.getRoomId()!] = [];
this.notifsByRoom[ev.getRoomId()!].push(notif);
2016-11-02 17:35:31 +00:00
}
2023-02-13 11:39:16 +00:00
}
2026-04-29 09:46:09 +01:00
public getSoundForRoom(roomId: string): NotificationSound | null {
2019-05-12 17:14:21 +01:00
// We do no caching here because the SDK caches setting
// and the browser will cache the sound.
2019-06-03 17:35:15 +01:00
const content = SettingsStore.getValue("notificationSound", roomId);
2019-04-19 22:31:51 +01:00
if (!content) {
2019-05-12 17:14:21 +01:00
return null;
2017-01-20 14:22:27 +00:00
}
2019-04-19 22:31:51 +01:00
if (typeof content.url !== "string") {
logger.warn(`${roomId} has custom notification sound event, but no url string`);
return null;
}
2019-09-18 09:27:43 +01:00
2019-05-12 17:14:21 +01:00
if (!content.url.startsWith("mxc://")) {
2021-10-15 16:31:29 +02:00
logger.warn(`${roomId} has custom notification sound event, but url is not a mxc url`);
2019-05-12 17:14:21 +01:00
return null;
}
// Ideally in here we could use MSC1310 to detect the type of file, and reject it.
2019-04-19 21:42:18 +01:00
const url = mediaFromMxc(content.url).srcHttp;
if (!url) {
logger.warn("Something went wrong when generating src http url for mxc");
return null;
}
2019-04-19 14:10:10 +01:00
return {
url,
2019-04-19 16:27:30 +01:00
name: content.name,
2019-04-19 14:10:10 +01:00
type: content.type,
2019-04-19 16:27:30 +01:00
size: content.size,
2019-04-19 14:10:10 +01:00
};
2023-02-13 11:39:16 +00:00
}
2023-02-13 11:39:16 +00:00
// XXX: Exported for tests
public async playAudioNotification(ev: MatrixEvent, room: Room): Promise<void> {
const cli = MatrixClientPeg.safeGet();
if (localNotificationsAreSilenced(cli)) {
return;
}
// Play notification sound here
2020-06-25 08:43:35 +01:00
const sound = this.getSoundForRoom(room.roomId);
2024-10-16 17:38:22 +01:00
logger.log(`Got sound ${sound?.name || "default"} for ${room.roomId}`);
2019-05-12 17:14:21 +01:00
// Throttle audible plays so a burst of backlogged notifications - e.g. the whole sync backlog
// delivered at once when macOS wakes from sleep - produces at most one sound per distinct sound
// within NOTIFICATION_SOUND_THROTTLE_MS, instead of many identical buffers superimposing into one
// loud "stacked" sound (#31996). Keyed on the resolved sound so two *different* sounds within the
// window both still play. Runs only after the silencing gate above, so it suppresses redundant
// *audible* plays, never the gating logic. We bail cleanly (no throw).
const soundKey = sound?.url ?? "default";
const now = Date.now();
const lastPlayed = this.lastAudioNotificationMs.get(soundKey);
if (lastPlayed !== undefined && now - lastPlayed < NOTIFICATION_SOUND_THROTTLE_MS) {
return;
}
this.lastAudioNotificationMs.set(soundKey, now);
if (sound) {
await this.backgroundAudio.play(sound.url);
} else {
await this.backgroundAudio.pickFormatAndPlay("media/message", ["mp3", "ogg"]);
2019-04-21 18:01:26 +01:00
}
2023-02-13 11:39:16 +00:00
}
2023-02-13 11:39:16 +00:00
public start(): void {
const cli = MatrixClientPeg.safeGet();
cli.on(RoomEvent.Timeline, this.onEvent);
cli.on(RoomEvent.Receipt, this.onRoomReceipt);
cli.on(MatrixEventEvent.Decrypted, this.onEventDecrypted);
cli.on(ClientEvent.Sync, this.onSyncStateChange);
this.toolbarHidden = false;
this.isSyncing = false;
2023-02-13 11:39:16 +00:00
}
2023-02-13 11:39:16 +00:00
public stop(): void {
2020-02-20 02:35:30 +00:00
if (MatrixClientPeg.get()) {
MatrixClientPeg.get()!.removeListener(RoomEvent.Timeline, this.onEvent);
MatrixClientPeg.get()!.removeListener(RoomEvent.Receipt, this.onRoomReceipt);
MatrixClientPeg.get()!.removeListener(MatrixEventEvent.Decrypted, this.onEventDecrypted);
MatrixClientPeg.get()!.removeListener(ClientEvent.Sync, this.onSyncStateChange);
}
this.isSyncing = false;
2023-02-13 11:39:16 +00:00
}
2023-02-13 11:39:16 +00:00
public supportsDesktopNotifications(): boolean {
return PlatformPeg.get()?.supportsNotifications() ?? false;
}
2023-02-13 11:39:16 +00:00
public setEnabled(enable: boolean, callback?: () => void): void {
2016-11-02 17:35:31 +00:00
const plaf = PlatformPeg.get();
if (!plaf) return;
// Dev note: We don't set the "notificationsEnabled" setting to true here because it is a
// calculated value. It is determined based upon whether or not the master rule is enabled
// and other flags. Setting it here would cause a circular reference.
// make sure that we persist the current setting audio_enabled setting
// before changing anything
2017-11-04 21:47:18 -07:00
if (SettingsStore.isLevelSupported(SettingLevel.DEVICE)) {
SettingsStore.setValue("audioNotificationsEnabled", null, SettingLevel.DEVICE, this.isEnabled());
}
if (enable) {
// Attempt to get permission from user
2019-11-18 10:03:05 +00:00
plaf.requestNotificationPermission().then((result) => {
if (result !== "granted") {
// The permission request was dismissed or denied
2017-11-04 21:47:18 -07:00
// TODO: Support alternative branding in messaging
2020-07-10 19:07:11 +01:00
const brand = SdkConfig.get().brand;
const description =
result === "denied"
? _t("settings|notifications|error_permissions_denied", { brand })
: _t("settings|notifications|error_permissions_missing", {
2020-07-10 19:07:11 +01:00
brand,
});
2022-06-14 17:51:51 +01:00
Modal.createDialog(ErrorDialog, {
title: _t("settings|notifications|error_title"),
description,
});
return;
}
2016-03-22 03:49:46 +05:30
if (callback) callback();
2022-07-29 13:43:29 +02:00
PosthogAnalytics.instance.trackEvent<PermissionChangedEvent>({
eventName: "PermissionChanged",
permission: "Notification",
granted: true,
});
dis.dispatch({
action: "notifier_enabled",
2017-04-23 06:06:23 +01:00
value: true,
});
});
2016-03-22 03:49:46 +05:30
} else {
2022-07-29 13:43:29 +02:00
PosthogAnalytics.instance.trackEvent<PermissionChangedEvent>({
eventName: "PermissionChanged",
permission: "Notification",
granted: false,
});
dis.dispatch({
action: "notifier_enabled",
2017-04-23 06:06:23 +01:00
value: false,
});
}
// set the notifications_hidden flag, as the user has knowingly interacted
// with the setting we shouldn't nag them any further
2020-09-15 13:58:29 +01:00
this.setPromptHidden(true);
2023-02-13 11:39:16 +00:00
}
2023-02-13 11:39:16 +00:00
public isEnabled(): boolean {
2017-11-04 21:47:18 -07:00
return this.isPossible() && SettingsStore.getValue("notificationsEnabled");
2023-02-13 11:39:16 +00:00
}
2017-11-04 21:47:18 -07:00
2023-02-13 11:39:16 +00:00
public isPossible(): boolean {
2016-11-02 17:35:31 +00:00
const plaf = PlatformPeg.get();
2023-02-13 11:39:16 +00:00
if (!plaf?.supportsNotifications()) return false;
2016-11-02 17:35:31 +00:00
if (!plaf.maySendNotifications()) return false;
2017-11-04 21:47:18 -07:00
return true; // possible, but not necessarily enabled
2023-02-13 11:39:16 +00:00
}
2023-02-13 11:39:16 +00:00
public isBodyEnabled(): boolean {
2017-11-04 21:47:18 -07:00
return this.isEnabled() && SettingsStore.getValue("notificationBodyEnabled");
2023-02-13 11:39:16 +00:00
}
2023-02-13 11:39:16 +00:00
public isAudioEnabled(): boolean {
// We don't route Audio via the HTML Notifications API so it is possible regardless of other things
return SettingsStore.getValue("audioNotificationsEnabled");
2023-02-13 11:39:16 +00:00
}
2023-02-13 11:39:16 +00:00
public setPromptHidden(hidden: boolean, persistent = true): void {
this.toolbarHidden = hidden;
2016-09-09 02:09:12 +01:00
hideNotificationsToast();
2016-03-22 03:49:46 +05:30
// update the info to localStorage for persistent settings
2017-11-08 17:06:36 -07:00
if (persistent && global.localStorage) {
2020-08-05 11:07:10 +01:00
global.localStorage.setItem("notifications_hidden", String(hidden));
2016-03-22 03:49:46 +05:30
}
this.emit(NotifierEvent.NotificationHiddenChange, hidden);
2023-02-13 11:39:16 +00:00
}
2023-02-13 11:39:16 +00:00
public shouldShowPrompt(): boolean {
const client = MatrixClientPeg.get();
if (!client) {
return false;
}
const isGuest = client.isGuest();
return (
!isGuest &&
this.supportsDesktopNotifications() &&
!isPushNotifyDisabled() &&
!this.isEnabled() &&
2023-02-13 11:39:16 +00:00
!this.isPromptHidden()
);
2023-02-13 11:39:16 +00:00
}
2023-02-13 11:39:16 +00:00
private isPromptHidden(): boolean {
// Check localStorage for any such meta data
2017-11-08 17:06:36 -07:00
if (global.localStorage) {
return global.localStorage.getItem("notifications_hidden") === "true";
}
return !!this.toolbarHidden;
2023-02-13 11:39:16 +00:00
}
2023-02-13 11:39:16 +00:00
// XXX: Exported for tests
public onSyncStateChange = (state: SyncState, prevState: SyncState | null, data?: SyncStateData): void => {
if (state === SyncState.Syncing) {
this.isSyncing = true;
} else if (state === SyncState.Stopped || state === SyncState.Error) {
this.isSyncing = false;
}
// wait for first non-cached sync to complete
if (![SyncState.Stopped, SyncState.Error].includes(state) && !data?.fromCache) {
createLocalNotificationSettingsIfNeeded(MatrixClientPeg.safeGet());
}
2023-02-13 11:39:16 +00:00
};
2023-02-13 11:39:16 +00:00
private onEvent = (
ev: MatrixEvent,
room: Room | undefined,
toStartOfTimeline: boolean | undefined,
removed: boolean,
data: IRoomTimelineData,
2023-02-13 11:39:16 +00:00
): void => {
if (removed) return; // only notify for new events, not removed ones
if (!data.liveEvent || !!toStartOfTimeline) return; // only notify for new things, not old.
if (!this.isSyncing) return; // don't alert for any messages initially
if (ev.getSender() === MatrixClientPeg.safeGet().getUserId()) return;
if (data.timeline.getTimelineSet().threadListType !== null) return; // Ignore events on the thread list generated timelines
MatrixClientPeg.safeGet().decryptEventIfNeeded(ev);
2021-05-18 16:24:38 +01:00
// If it's an encrypted event and the type is still 'm.room.encrypted',
// it hasn't yet been decrypted, so wait until it is.
2017-08-24 14:42:38 +01:00
if (ev.isBeingDecrypted() || ev.isDecryptionFailure()) {
this.pendingEncryptedEventIds.push(ev.getId()!);
// don't let the list fill up indefinitely
while (this.pendingEncryptedEventIds.length > MAX_PENDING_ENCRYPTED) {
this.pendingEncryptedEventIds.shift();
}
return;
}
2023-02-13 11:39:16 +00:00
this.evaluateEvent(ev);
};
2023-02-13 11:39:16 +00:00
private onEventDecrypted = (ev: MatrixEvent): void => {
2018-03-29 18:18:53 +01:00
// 'decrypted' means the decryption process has finished: it may have failed,
// in which case it might decrypt soon if the keys arrive
if (ev.isDecryptionFailure()) return;
const idx = this.pendingEncryptedEventIds.indexOf(ev.getId()!);
if (idx === -1) return;
this.pendingEncryptedEventIds.splice(idx, 1);
2023-02-13 11:39:16 +00:00
this.evaluateEvent(ev);
};
2016-11-02 17:35:31 +00:00
2023-02-13 11:39:16 +00:00
private onRoomReceipt = (ev: MatrixEvent, room: Room): void => {
2017-04-23 06:06:23 +01:00
if (room.getUnreadNotificationCount() === 0) {
2016-11-02 17:35:31 +00:00
// ideally we would clear each notification when it was read,
// but we have no way, given a read receipt, to know whether
// the receipt comes before or after an event, so we can't
// do this. Instead, clear all notifications for a room once
// there are no notifs left in that room., which is not quite
// as good but it's something.
if (this.notifsByRoom[room.roomId] === undefined) return;
for (const notif of this.notifsByRoom[room.roomId]) {
notif.close();
2016-11-02 17:35:31 +00:00
}
delete this.notifsByRoom[room.roomId];
}
2023-02-13 11:39:16 +00:00
};
2023-02-13 11:39:16 +00:00
// XXX: exported for tests
public evaluateEvent(ev: MatrixEvent): void {
2025-04-16 09:36:34 +01:00
const roomId = ev.getRoomId()!;
const room = MatrixClientPeg.safeGet().getRoom(roomId);
if (!room) {
// e.g we are in the process of joining a room.
// Seen in the Playwright lazy-loading test.
return;
}
const actions = MatrixClientPeg.safeGet().getPushActionsForEvent(ev);
if (actions?.notify) {
2023-02-13 11:39:16 +00:00
this.performCustomEventHandling(ev);
2026-07-01 13:49:18 +01:00
const store = SDKContextClass.instance.roomViewStore;
const isViewingRoom = store.getRoomId() === room.roomId;
const threadId: string | undefined = ev.getId() !== ev.threadRootId ? ev.threadRootId : undefined;
const isViewingThread = store.getThreadId() === threadId;
const isViewingEventTimeline = isViewingRoom && (!threadId || isViewingThread);
if (isViewingEventTimeline && UserActivity.sharedInstance().userActiveRecently() && !Modal.hasDialogs()) {
// don't bother notifying as user was recently active in this room
return;
}
if (this.isEnabled()) {
2023-02-13 11:39:16 +00:00
this.displayPopupNotification(ev, room);
}
if (actions.tweaks.sound && this.isAudioEnabled()) {
PlatformPeg.get()?.loudNotification(ev, room);
2023-02-13 11:39:16 +00:00
this.playAudioNotification(ev, room);
}
}
2023-02-13 11:39:16 +00:00
}
/**
* Handle `EventType.RTCNotification` notifications.
* @param ev The notification event.
* @param toaster The toast store.
* @param room The room that contains the notification
* @returns A promise that will always resolve.
*/
private async handleRTCNotification(ev: MatrixEvent, toaster: ToastStore, room: Room): Promise<void> {
// TODO: Use the call_id to get the *correct* call. We assume there is only one call per room here.
const rtcSession = room && room.client.matrixRTC.getRoomSession(room);
if (
rtcSession?.slotDescription?.application == "m.call" &&
rtcSession.memberships.some((membership) => membership.userId === room.client.getUserId())
) {
// If we're already joined to the session, don't notify.
return;
}
// XXX: Should use parseCallNotificationContent once the types are exported.
const content = ev.getContent() as IRTCNotificationContent;
const roomId = ev.getRoomId();
const referencedMembershipEventId = ev.getRelation()?.event_id;
// Check maximum age of a call notification event that will trigger a ringing notification
if (Date.now() - getNotificationEventSendTs(ev) > content.lifetime) {
logger.warn("Received outdated RTCNotification event.");
return;
}
if (!roomId) {
logger.warn("Could not get roomId for RTCNotification event");
return;
}
if (!referencedMembershipEventId) {
logger.warn("Could not get referenced membership for notification");
return;
}
if (content["m.relates_to"].rel_type !== "m.reference") {
logger.warn("Ignored RTCNotification due to invalid rel_type");
return;
}
let callMembership = room?.findEventById(referencedMembershipEventId);
if (!callMembership) {
// Attempt to fetch from the homeserver, if we do not have the event locally.
// This is a rare case as obviously the referenced event for a m.call notification must
// be sent first.
try {
callMembership = new MatrixEvent(await room.client.fetchRoomEvent(roomId, referencedMembershipEventId));
} catch (ex) {
logger.warn(`Call membership for notification could not be found`, ex);
2023-11-21 18:12:08 +01:00
}
}
// If the event could not be found even after requesting it from the homeserver.
if (!callMembership) {
// We will not show a call notification if there is no valid call membership.
logger.warn(
`Could not find call membership (${referencedMembershipEventId} ${roomId}) for notification event.`,
);
return;
}
// If we cannot determine the key, we'll accept it but assume it's empty string.
// This means if you have malformed notifications or call memberships your notifications
// will overwrite, but the solution to that is to use well-formed events.
const callId = callMembership.getContent<SessionMembershipData>().call_id ?? "";
const key = getIncomingCallToastKey(callId, roomId);
if (toaster.hasToast(key)) {
logger.debug(`Detected duplicate notification for call ${key}, ignoring`);
return;
}
toaster.addOrReplaceToast({
key,
priority: 100,
component: IncomingCallToast,
bodyClassName: "mx_IncomingCallToast",
props: { notificationEvent: ev },
});
}
/**
* Some events require special handling such as showing in-app toasts.
* This function may either create a toast or ignore the event based
* on current app state.
*/
private performCustomEventHandling(ev: MatrixEvent): void {
const toaster = ToastStore.sharedInstance();
const cli = MatrixClientPeg.safeGet();
const room = cli.getRoom(ev.getRoomId());
if (room && EventType.RTCNotification === ev.getType()) {
// We don't need to await this.
void this.handleRTCNotification(ev, toaster, room);
}
2023-02-13 11:39:16 +00:00
}
}
2020-08-05 11:07:10 +01:00
if (!window.mxNotifier) {
2023-02-13 11:39:16 +00:00
window.mxNotifier = new NotifierClass();
}
2020-08-05 11:07:10 +01:00
export default window.mxNotifier;
2023-02-13 11:39:16 +00:00
export const Notifier: NotifierClass = window.mxNotifier;