Skip to content

A free and open source instant messaging and VoIP chat app built for friends, groups, and communities.

TypeScript fluxerfluxerapp

feat(app): notify and badge for every signed-in account

Hampuscaede27ac4aa
diff --git a/fluxer_app/src/features/notification/utils/AccountEngineNotifications.ts b/fluxer_app/src/features/notification/utils/AccountEngineNotifications.ts
new file mode 100644
index 000000000..97d976c6a
--- /dev/null
+++ b/fluxer_app/src/features/notification/utils/AccountEngineNotifications.ts
@@ -0,0 +1,273 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+import i18n from '@app/app/I18n';
+import {Routes} from '@app/app/Routes';
+import AccountEngine from '@app/features/account_engine/state/AccountEngine';
+import {SENSITIVE_MESSAGE_PREVIEW_DESCRIPTOR} from '@app/features/account_engine/state/AccountEngineMessages';
+import {resolveAccountInstanceLabel} from '@app/features/auth/AccountDisplayUtils';
+import {parseAccountStorageKey} from '@app/features/auth/state/AccountStorageKey';
+import {GROUP_DM_DESCRIPTOR} from '@app/features/i18n/utils/CommonMessageDescriptors';
+import {
+ type AccountNotificationPreferences,
+ accountSoundEnabled,
+ shouldShowAccountNotification,
+} from '@app/features/notification/utils/AccountNotificationGate';
+import {buildWireMessageNotificationBody} from '@app/features/notification/utils/MessageNotificationPreview';
+import {NATIVE_NOTIFICATION_ICON_CSS_SIZE} from '@app/features/notification/utils/NotificationIconURL';
+import {clearChannelNotifications, trackNotification} from '@app/features/notification/utils/NotificationTracker';
+import * as NotificationUtils from '@app/features/notification/utils/NotificationUtils';
+import {SoundType} from '@app/features/notification/utils/SoundUtils';
+import {AppStorageKey} from '@app/features/platform/state/AppStorageKeys';
+import SessionManager, {type Account} from '@app/features/platform/state/AuthSession';
+import {getPersistentStorageBackend} from '@app/features/platform/state/PersistentStorageBackend';
+import {Logger} from '@app/features/platform/utils/AppLogger';
+import StreamerMode from '@app/features/streamer_mode/state/StreamerMode';
+import * as AvatarUtils from '@app/features/user/utils/AvatarUtils';
+import {ChannelTypes} from '@fluxer/constants/src/ChannelConstants';
+import type {AccountEngineNotification} from '@fluxer/desktop_ipc/src/AccountEngineContract';
+import type {Message as WireMessage} from '@fluxer/schema/src/domains/message/MessageResponseSchemas';
+import {msg} from '@lingui/core/macro';
+import {LRUCache} from 'lru-cache';
+
+const ACCOUNT_NOTIFICATION_CONTEXT_DESCRIPTOR = msg({
+ message: '{context} · {accountName}',
+ comment:
+ 'Desktop notification title or subtitle for a message received by a signed-in account that is not the active one. context is the sender or channel label, accountName is the receiving account name.',
+});
+const ACCOUNT_ON_HOST_DESCRIPTOR = msg({
+ message: '{accountName} on {host}',
+ comment:
+ 'Names the receiving account in a desktop notification when the signed-in accounts are on more than one instance. host is the instance address, such as fluxer.example.com.',
+});
+
+const SYNCED_PREFERENCES_LOCAL_KEY = 'UserSettings:syncedPreferencesLocal';
+
+const GUILD_CHANNEL_TYPES: ReadonlySet<number> = new Set([
+ ChannelTypes.GUILD_TEXT,
+ ChannelTypes.GUILD_ANNOUNCEMENT,
+ ChannelTypes.GUILD_VOICE,
+]);
+
+const logger = new Logger('AccountEngineNotifications');
+const notifiedMessages = new LRUCache<string, true>({max: 500});
+
+function parseNotificationsEnabled(value: string): boolean {
+ try {
+ const parsed: unknown = JSON.parse(value);
+ return (
+ typeof parsed === 'object' &&
+ parsed !== null &&
+ (parsed as {browserNotificationsEnabled?: unknown}).browserNotificationsEnabled === true
+ );
+ } catch {
+ return false;
+ }
+}
+
+interface StoredAccountNotificationPreferences {
+ readonly notification: string | null;
+ readonly syncedPreferences: string | null;
+}
+
+const PREFERENCES_CACHE_TTL_MS = 5_000;
+const storedPreferences = new LRUCache<string, Promise<StoredAccountNotificationPreferences>>({
+ max: 256,
+ ttl: PREFERENCES_CACHE_TTL_MS,
+});
+
+function readStoredPreferences(accountKey: string): Promise<StoredAccountNotificationPreferences> {
+ const cached = storedPreferences.get(accountKey);
+ if (cached !== undefined) return cached;
+ const backend = getPersistentStorageBackend();
+ const read = Promise.all([
+ backend.get(accountKey, AppStorageKey.NOTIFICATION),
+ backend.get(accountKey, SYNCED_PREFERENCES_LOCAL_KEY),
+ ]).then(([notification, syncedPreferences]) => ({
+ notification: notification?.value ?? null,
+ syncedPreferences: syncedPreferences?.value ?? null,
+ }));
+ storedPreferences.set(accountKey, read);
+ read.catch(() => storedPreferences.delete(accountKey));
+ return read;
+}
+
+async function readAccountNotificationPreferences(
+ accountKey: string,
+ soundType: SoundType,
+): Promise<AccountNotificationPreferences> {
+ const stored = await readStoredPreferences(accountKey);
+ return {
+ notificationsEnabled: stored.notification === null ? false : parseNotificationsEnabled(stored.notification),
+ soundEnabled: accountSoundEnabled(stored.syncedPreferences, soundType),
+ };
+}
+
+function parseWireMessage(value: unknown): WireMessage | null {
+ if (typeof value !== 'object' || value === null) return null;
+ const message = value as Partial<WireMessage>;
+ const author = message.author as Partial<WireMessage['author']> | undefined;
+ if (typeof message.id !== 'string' || typeof message.channel_id !== 'string') return null;
+ if (typeof author !== 'object' || author === null) return null;
+ if (typeof author.id !== 'string' || typeof author.username !== 'string') return null;
+ return {
+ ...message,
+ content: typeof message.content === 'string' ? message.content : '',
+ mentions: Array.isArray(message.mentions) ? message.mentions : [],
+ attachments: Array.isArray(message.attachments) ? message.attachments : [],
+ embeds: Array.isArray(message.embeds) ? message.embeds : [],
+ stickers: Array.isArray(message.stickers) ? message.stickers : [],
+ } as WireMessage;
+}
+
+function accountsSpanSeveralInstances(): boolean {
+ const instanceKeys = new Set<string>();
+ for (const account of SessionManager.accounts) {
+ instanceKeys.add(parseAccountStorageKey(account.storageKey)?.instanceKey ?? account.storageKey);
+ if (instanceKeys.size > 1) return true;
+ }
+ return false;
+}
+
+function accountNotificationLabel(account: Account, includeHost: boolean): string {
+ const accountName = account.userData?.globalName || account.userData?.username || account.userId;
+ const host = includeHost ? resolveAccountInstanceLabel(account) : null;
+ return host === null ? accountName : i18n._(ACCOUNT_ON_HOST_DESCRIPTOR, {accountName, host});
+}
+
+function notificationIcon(account: Account, message: WireMessage): string {
+ const author = message.author;
+ const endpoint = account.instance?.mediaEndpoint;
+ if (typeof endpoint !== 'string' || endpoint.length === 0) {
+ return AvatarUtils.getDefaultAvatarURL(author.id);
+ }
+ return AvatarUtils.getUserNotificationAvatarURLForEndpoint(
+ {id: author.id, avatar: author.avatar ?? null},
+ endpoint,
+ NATIVE_NOTIFICATION_ICON_CSS_SIZE,
+ );
+}
+
+interface AccountNotificationPresentation {
+ readonly title: string;
+ readonly subtitle: string | undefined;
+}
+
+function presentAccountNotification(
+ notification: Pick<AccountEngineNotification, 'guildName' | 'channelName' | 'channelType'>,
+ message: Pick<WireMessage, 'author' | 'member'>,
+ accountLabel: string,
+ macOSPresentation: boolean,
+): AccountNotificationPresentation {
+ const {guildName, channelName, channelType} = notification;
+ const author = message.author;
+ let title = message.member?.nick || author.global_name || author.username;
+ let context: string | null = null;
+ if (channelType !== null && GUILD_CHANNEL_TYPES.has(channelType) && channelName !== null) {
+ const channelLabel = `${channelType === ChannelTypes.GUILD_VOICE ? '' : '#'}${channelName}`;
+ context = macOSPresentation && guildName !== null ? `${guildName} ${channelLabel}` : channelLabel;
+ } else if (channelType === ChannelTypes.GROUP_DM) {
+ context = channelName || i18n._(GROUP_DM_DESCRIPTOR);
+ }
+ if (macOSPresentation) {
+ const subtitle =
+ context === null
+ ? accountLabel
+ : i18n._(ACCOUNT_NOTIFICATION_CONTEXT_DESCRIPTOR, {context, accountName: accountLabel});
+ return {title, subtitle};
+ }
+ if (context !== null) {
+ title = `${title} (${context})`;
+ }
+ return {
+ title: i18n._(ACCOUNT_NOTIFICATION_CONTEXT_DESCRIPTOR, {context: title, accountName: accountLabel}),
+ subtitle: undefined,
+ };
+}
+
+function gate(
+ accountKey: string,
+ notificationKey: string,
+ preferences: AccountNotificationPreferences | null,
+): Account | null {
+ const account = SessionManager.getAccount(accountKey);
+ const allowed = shouldShowAccountNotification({
+ accountKey,
+ currentAccountKey: SessionManager.currentAccountKey,
+ account,
+ streamerModeBlocksNotifications: StreamerMode.shouldDisableNotifications,
+ alreadyNotified: notifiedMessages.has(notificationKey),
+ preferences,
+ now: Date.now(),
+ });
+ return allowed ? account : null;
+}
+
+async function showAccountEngineNotification(notification: AccountEngineNotification): Promise<void> {
+ const {accountKey} = notification;
+ const message = parseWireMessage(notification.message);
+ if (message === null) return;
+ const notificationKey = `${accountKey}:${message.id}`;
+ if (gate(accountKey, notificationKey, null) === null) return;
+ const guildId = message.guild_id ?? null;
+ const soundType = guildId === null ? SoundType.DirectMessage : SoundType.Message;
+ const preferences = await readAccountNotificationPreferences(accountKey, soundType);
+ const account = gate(accountKey, notificationKey, preferences);
+ if (account === null) return;
+ notifiedMessages.set(notificationKey, true);
+ const body = notification.gated
+ ? i18n._(SENSITIVE_MESSAGE_PREVIEW_DESCRIPTOR)
+ : buildWireMessageNotificationBody(message, i18n);
+ if (!body) return;
+ if (preferences.soundEnabled) {
+ if (guildId === null) {
+ NotificationUtils.playDirectMessageNotificationSoundIfEnabled();
+ } else {
+ NotificationUtils.playNotificationSoundIfEnabled();
+ }
+ }
+ const {title, subtitle} = presentAccountNotification(
+ notification,
+ message,
+ accountNotificationLabel(account, accountsSpanSeveralInstances()),
+ NotificationUtils.isMacOSDesktopNotification(),
+ );
+ try {
+ const result = await NotificationUtils.showNotification({
+ id: notificationKey,
+ title,
+ subtitle,
+ body,
+ icon: notificationIcon(account, message),
+ url:
+ guildId === null
+ ? Routes.dmChannelMessage(message.channel_id, message.id)
+ : Routes.channelMessage(guildId, message.channel_id, message.id),
+ playSound: false,
+ accountKey,
+ });
+ trackNotification(accountKey, message.channel_id, {
+ browserNotification: result.browserNotification,
+ nativeId: result.nativeNotificationId,
+ });
+ } catch (error) {
+ logger.error('Failed to show a notification for another account', {accountKey, messageId: message.id}, error);
+ }
+}
+
+let stopListening: (() => void) | null = null;
+
+export function startAccountEngineNotifications(): () => void {
+ if (stopListening !== null) return stopListening;
+ const disposeNotification = AccountEngine.onNotification((notification) => {
+ void showAccountEngineNotification(notification);
+ });
+ const disposeChannelRead = AccountEngine.onChannelRead((accountKey, channelId) => {
+ clearChannelNotifications(accountKey, channelId);
+ });
+ stopListening = () => {
+ disposeNotification();
+ disposeChannelRead();
+ stopListening = null;
+ };
+ return stopListening;
+}
diff --git a/fluxer_app/src/features/notification/utils/AccountNotificationGate.ts b/fluxer_app/src/features/notification/utils/AccountNotificationGate.ts
new file mode 100644
index 000000000..5ed5fab81
--- /dev/null
+++ b/fluxer_app/src/features/notification/utils/AccountNotificationGate.ts
@@ -0,0 +1,50 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+import type {AccountPresenceIntent} from '@app/features/auth/state/AccountStorageContract';
+import type {SoundType} from '@app/features/notification/utils/SoundUtils';
+import type {Account} from '@app/features/platform/state/AuthSession';
+import {StatusTypes} from '@fluxer/constants/src/StatusConstants';
+import {decodeSyncedPreferencesLenient} from '@fluxer/schema/src/domains/user/SyncedPreferencesCodec';
+
+export interface AccountNotificationPreferences {
+ readonly notificationsEnabled: boolean;
+ readonly soundEnabled: boolean;
+}
+
+interface AccountNotificationGateInput {
+ readonly accountKey: string;
+ readonly currentAccountKey: string | null;
+ readonly account: Pick<Account, 'isValid' | 'presenceIntent'> | null;
+ readonly streamerModeBlocksNotifications: boolean;
+ readonly alreadyNotified: boolean;
+ readonly preferences: AccountNotificationPreferences | null;
+ readonly now: number;
+}
+
+function effectivePresenceStatus(intent: AccountPresenceIntent | null | undefined, now: number): string | null {
+ if (intent == null) return null;
+ if (intent.statusResetsAt != null && intent.statusResetsTo != null) {
+ const resetsAt = Date.parse(intent.statusResetsAt);
+ if (!Number.isNaN(resetsAt) && resetsAt <= now) {
+ return intent.statusResetsTo;
+ }
+ }
+ return intent.status;
+}
+
+export function shouldShowAccountNotification(input: AccountNotificationGateInput): boolean {
+ if (input.streamerModeBlocksNotifications) return false;
+ if (input.accountKey === input.currentAccountKey) return false;
+ if (input.account === null || !input.account.isValid) return false;
+ if (effectivePresenceStatus(input.account.presenceIntent, input.now) === StatusTypes.DND) return false;
+ if (input.alreadyNotified) return false;
+ return input.preferences === null || input.preferences.notificationsEnabled;
+}
+
+export function accountSoundEnabled(encodedPreferences: string | null, soundType: SoundType): boolean {
+ if (encodedPreferences === null) return true;
+ const sound = decodeSyncedPreferencesLenient(encodedPreferences).sound;
+ if (sound === undefined) return true;
+ if (sound.allSoundsDisabled) return false;
+ return sound.disabledSounds[soundType] !== true;
+}
diff --git a/fluxer_app/src/features/notification/utils/BackgroundAccountNotifications.ts b/fluxer_app/src/features/notification/utils/BackgroundAccountNotifications.ts
deleted file mode 100644
index 0a70d9306..000000000
--- a/fluxer_app/src/features/notification/utils/BackgroundAccountNotifications.ts
+++ /dev/null
@@ -1,159 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import i18n from '@app/app/I18n';
-import {Routes} from '@app/app/Routes';
-import type {AccountPresenceIntent} from '@app/features/auth/state/AccountStorageContract';
-import type {BackgroundMessageNotification} from '@app/features/gateway/transport/BackgroundSnapshotSink';
-import {GROUP_DM_DESCRIPTOR} from '@app/features/i18n/utils/CommonMessageDescriptors';
-import {buildWireMessageNotificationBody} from '@app/features/notification/utils/MessageNotificationPreview';
-import {NATIVE_NOTIFICATION_ICON_CSS_SIZE} from '@app/features/notification/utils/NotificationIconURL';
-import * as NotificationUtils from '@app/features/notification/utils/NotificationUtils';
-import {AppStorageKey} from '@app/features/platform/state/AppStorageKeys';
-import SessionManager, {type Account} from '@app/features/platform/state/AuthSession';
-import {getPersistentStorageBackend} from '@app/features/platform/state/PersistentStorageBackend';
-import {Logger} from '@app/features/platform/utils/AppLogger';
-import StreamerMode from '@app/features/streamer_mode/state/StreamerMode';
-import * as AvatarUtils from '@app/features/user/utils/AvatarUtils';
-import {ChannelTypes} from '@fluxer/constants/src/ChannelConstants';
-import {StatusTypes} from '@fluxer/constants/src/StatusConstants';
-import {msg} from '@lingui/core/macro';
-import {LRUCache} from 'lru-cache';
-
-const ACCOUNT_NOTIFICATION_CONTEXT_DESCRIPTOR = msg({
- message: '{context} · {accountName}',
- comment:
- 'Desktop notification title or subtitle for a message received by a signed-in account that is not the active one. context is the sender or channel label, accountName is the receiving account name.',
-});
-
-const GUILD_CHANNEL_TYPES: ReadonlySet<number> = new Set([
- ChannelTypes.GUILD_TEXT,
- ChannelTypes.GUILD_ANNOUNCEMENT,
- ChannelTypes.GUILD_VOICE,
-]);
-
-const logger = new Logger('BackgroundAccountNotifications');
-const notifiedMessages = new LRUCache<string, true>({max: 500});
-
-function effectivePresenceStatus(intent: AccountPresenceIntent | null | undefined, now: number): string | null {
- if (intent == null) return null;
- if (intent.statusResetsAt != null && intent.statusResetsTo != null) {
- const resetsAt = Date.parse(intent.statusResetsAt);
- if (!Number.isNaN(resetsAt) && resetsAt <= now) {
- return intent.statusResetsTo;
- }
- }
- return intent.status;
-}
-
-function parseNotificationsEnabled(value: string): boolean {
- try {
- const parsed: unknown = JSON.parse(value);
- return (
- typeof parsed === 'object' &&
- parsed !== null &&
- (parsed as {browserNotificationsEnabled?: unknown}).browserNotificationsEnabled === true
- );
- } catch {
- return false;
- }
-}
-
-export async function readAccountNotificationsEnabled(accountKey: string): Promise<boolean> {
- const entry = await getPersistentStorageBackend().get(accountKey, AppStorageKey.NOTIFICATION);
- return entry === null ? false : parseNotificationsEnabled(entry.value);
-}
-
-function accountDisplayName(account: Account): string {
- return account.userData?.globalName || account.userData?.username || account.userId;
-}
-
-function notificationIcon(account: Account, notification: BackgroundMessageNotification): string {
- const author = notification.message.author;
- const endpoint = account.instance?.mediaEndpoint;
- if (typeof endpoint !== 'string' || endpoint.length === 0) {
- return AvatarUtils.getDefaultAvatarURL(author.id);
- }
- return AvatarUtils.getUserNotificationAvatarURLForEndpoint(
- {id: author.id, avatar: author.avatar ?? null},
- endpoint,
- NATIVE_NOTIFICATION_ICON_CSS_SIZE,
- );
-}
-
-export interface BackgroundNotificationPresentation {
- readonly title: string;
- readonly subtitle: string | undefined;
-}
-
-export function presentBackgroundNotification(
- notification: BackgroundMessageNotification,
- accountName: string,
- macOSPresentation: boolean,
-): BackgroundNotificationPresentation {
- const {message, guildName, channelName, channelType} = notification;
- const author = message.author;
- let title = message.member?.nick || author.global_name || author.username;
- let context: string | null = null;
- if (channelType !== null && GUILD_CHANNEL_TYPES.has(channelType) && channelName !== null) {
- const channelLabel = `${channelType === ChannelTypes.GUILD_VOICE ? '' : '#'}${channelName}`;
- context = macOSPresentation && guildName !== null ? `${guildName} ${channelLabel}` : channelLabel;
- } else if (channelType === ChannelTypes.GROUP_DM) {
- context = channelName || i18n._(GROUP_DM_DESCRIPTOR);
- }
- if (macOSPresentation) {
- const subtitle =
- context === null ? accountName : i18n._(ACCOUNT_NOTIFICATION_CONTEXT_DESCRIPTOR, {context, accountName});
- return {title, subtitle};
- }
- if (context !== null) {
- title = `${title} (${context})`;
- }
- return {title: i18n._(ACCOUNT_NOTIFICATION_CONTEXT_DESCRIPTOR, {context: title, accountName}), subtitle: undefined};
-}
-
-export async function showBackgroundAccountNotification(
- accountKey: string,
- notification: BackgroundMessageNotification,
-): Promise<void> {
- if (StreamerMode.shouldDisableNotifications) return;
- if (accountKey === SessionManager.currentAccountKey) return;
- const account = SessionManager.getAccount(accountKey);
- if (account === null || !account.isValid) return;
- if (effectivePresenceStatus(account.presenceIntent, Date.now()) === StatusTypes.DND) return;
- const {message} = notification;
- const notificationKey = `${accountKey}:${message.id}`;
- if (notifiedMessages.has(notificationKey)) return;
- if (!(await readAccountNotificationsEnabled(accountKey))) return;
- if (notifiedMessages.has(notificationKey) || accountKey === SessionManager.currentAccountKey) return;
- notifiedMessages.set(notificationKey, true);
- const body = buildWireMessageNotificationBody(message, i18n);
- if (!body) return;
- const guildId = message.guild_id ?? null;
- if (guildId === null) {
- NotificationUtils.playDirectMessageNotificationSoundIfEnabled();
- } else {
- NotificationUtils.playNotificationSoundIfEnabled();
- }
- const {title, subtitle} = presentBackgroundNotification(
- notification,
- accountDisplayName(account),
- NotificationUtils.isMacOSDesktopNotification(),
- );
- try {
- await NotificationUtils.showNotification({
- id: notificationKey,
- title,
- subtitle,
- body,
- icon: notificationIcon(account, notification),
- url:
- guildId === null
- ? Routes.dmChannelMessage(message.channel_id, message.id)
- : Routes.channelMessage(guildId, message.channel_id, message.id),
- playSound: false,
- accountKey,
- });
- } catch (error) {
- logger.error('Failed to show a background account notification', {accountKey, messageId: message.id}, error);
- }
-}
diff --git a/fluxer_app/src/features/notification/utils/NotificationTracker.ts b/fluxer_app/src/features/notification/utils/NotificationTracker.ts
new file mode 100644
index 000000000..6a6259a03
--- /dev/null
+++ b/fluxer_app/src/features/notification/utils/NotificationTracker.ts
@@ -0,0 +1,47 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+import * as NotificationUtils from '@app/features/notification/utils/NotificationUtils';
+
+const MAX_PER_CHANNEL = 5;
+
+export interface TrackedNotification {
+ readonly browserNotification: Notification | null;
+ readonly nativeId: string | null;
+}
+
+const trackedByChannel = new Map<string, Array<TrackedNotification>>();
+
+function trackerKey(accountKey: string | null, channelId: string): string {
+ return `${accountKey ?? ''}\u0000${channelId}`;
+}
+
+function closeTracked(notifications: ReadonlyArray<TrackedNotification>): void {
+ for (const notification of notifications) {
+ notification.browserNotification?.close();
+ }
+ const nativeIds = notifications.map((n) => n.nativeId).filter((id): id is string => id != null);
+ NotificationUtils.closeNativeNotifications(nativeIds);
+}
+
+export function trackNotification(
+ accountKey: string | null,
+ channelId: string,
+ notification: TrackedNotification,
+): void {
+ if (notification.browserNotification === null && notification.nativeId === null) return;
+ const key = trackerKey(accountKey, channelId);
+ const notifications = trackedByChannel.get(key) ?? [];
+ notifications.push(notification);
+ trackedByChannel.set(key, notifications);
+ if (notifications.length > MAX_PER_CHANNEL) {
+ closeTracked(notifications.splice(0, notifications.length - MAX_PER_CHANNEL));
+ }
+}
+
+export function clearChannelNotifications(accountKey: string | null, channelId: string): void {
+ const key = trackerKey(accountKey, channelId);
+ const notifications = trackedByChannel.get(key);
+ if (notifications === undefined) return;
+ trackedByChannel.delete(key);
+ closeTracked(notifications);
+}
diff --git a/fluxer_app/src/features/notification/utils/NotificationUtils.ts b/fluxer_app/src/features/notification/utils/NotificationUtils.ts
index ab1bf2dec..79583e461 100644
--- a/fluxer_app/src/features/notification/utils/NotificationUtils.ts
+++ b/fluxer_app/src/features/notification/utils/NotificationUtils.ts
@@ -15,7 +15,7 @@ import Sound from '@app/features/ui/state/Sound';
import {getElectronAPI, hasUnavailableElectronNativeContext, isDesktop} from '@app/features/ui/utils/NativeUtils';
import {isInstalledIOSPwa, isInstalledPwa, isMobileOrTablet} from '@app/features/ui/utils/PwaUtils';
import Users from '@app/features/user/state/Users';
-import type {I18n} from '@lingui/core';
+import type {I18n, MessageDescriptor} from '@lingui/core';
import {msg} from '@lingui/core/macro';
const logger = new Logger('NotificationUtils');
@@ -53,28 +53,12 @@ export function ensureDesktopNotificationClickHandler(): void {
const electronApi = getElectronAPI();
if (!electronApi) return;
setDesktopNotificationClickHandlerInitialized();
- electronApi.onNotificationClick((id: string, url?: string) => {
- const accountKey = notificationAccountKeys.get(id) ?? null;
- notificationAccountKeys.delete(id);
- void openNotificationTarget(accountKey, url ?? null);
+ electronApi.onNotificationClick((_id, url, accountKey) => {
+ void openNotificationTarget(accountKey ?? null, url ?? null);
});
}
-const MAX_TRACKED_NOTIFICATION_ACCOUNTS = 500;
-const notificationAccountKeys = new Map<string, string>();
-
-function rememberNotificationAccount(id: string, accountKey: string | null): void {
- notificationAccountKeys.delete(id);
- if (accountKey === null) return;
- notificationAccountKeys.set(id, accountKey);
- while (notificationAccountKeys.size > MAX_TRACKED_NOTIFICATION_ACCOUNTS) {
- const oldest = notificationAccountKeys.keys().next().value;
- if (oldest === undefined) break;
- notificationAccountKeys.delete(oldest);
- }
-}
-
-export async function openNotificationTarget(accountKey: string | null, url: string | null): Promise<void> {
+async function openNotificationTarget(accountKey: string | null, url: string | null): Promise<void> {
if (accountKey !== null) {
const {default: Accounts} = await import('@app/features/auth/state/Accounts');
if (accountKey !== Accounts.currentAccountKey) {
@@ -82,7 +66,6 @@ export async function openNotificationTarget(accountKey: string | null, url: str
const {switchStoredAccountFromSwitcher} = await import('@app/features/auth/utils/AccountSwitcherModalUtils');
await switchStoredAccountFromSwitcher({
accountKey,
- onSessionExpired: null,
onSuccess: null,
redirectAfterSwitch: url,
switchAccount: null,
@@ -97,7 +80,7 @@ export async function openNotificationTarget(accountKey: string | null, url: str
const NATIVE_NOTIFICATION_ICON_URL_PATTERN = /^(?:https?:|data:)/i;
-export async function resolveNativeNotificationIcon(icon: string | undefined): Promise<string> {
+async function resolveNativeNotificationIcon(icon: string | undefined): Promise<string> {
if (!icon) return '';
const unwrapped = unwrapDesktopLocalResourceURL(icon);
if (NATIVE_NOTIFICATION_ICON_URL_PATTERN.test(unwrapped)) return unwrapped;
@@ -177,7 +160,8 @@ const requestBrowserPermission = async (): Promise<PermissionResult> => {
try {
const permission = await Notification.requestPermission();
return permission === 'granted' ? 'granted' : 'denied';
- } catch {
+ } catch (error) {
+ logger.warn('Browser notification permission request failed', {error});
return 'denied';
}
};
@@ -201,11 +185,14 @@ const applyGrantedPermission = async (i18n: I18n): Promise<void> => {
playNotificationSoundIfEnabled();
const icon = getCurrentUserAvatar() ?? '';
const isPwa = !isDesktop() && isInstalledPwa();
- const body = isDesktop()
- ? HUZZAH_DESKTOP_NOTIFICATIONS_ARE_ENABLED_DESCRIPTOR
- : isPwa
- ? HUZZAH_NOTIFICATIONS_ARE_ENABLED_DESCRIPTOR
- : HUZZAH_BROWSER_NOTIFICATIONS_ARE_ENABLED_DESCRIPTOR;
+ let body: MessageDescriptor;
+ if (isDesktop()) {
+ body = HUZZAH_DESKTOP_NOTIFICATIONS_ARE_ENABLED_DESCRIPTOR;
+ } else if (isPwa) {
+ body = HUZZAH_NOTIFICATIONS_ARE_ENABLED_DESCRIPTOR;
+ } else {
+ body = HUZZAH_BROWSER_NOTIFICATIONS_ARE_ENABLED_DESCRIPTOR;
+ }
void showNotification({
title: i18n._(ACCESS_GRANTED_DESCRIPTOR),
body: i18n._(body),
@@ -241,7 +228,7 @@ export async function requestPermission(i18n: I18n): Promise<void> {
await applyGrantedPermission(i18n);
}
-export interface NotificationResult {
+interface NotificationResult {
browserNotification: Notification | null;
nativeNotificationId: string | null;
}
@@ -256,7 +243,8 @@ const getServiceWorkerRegistration = async (): Promise<ServiceWorkerRegistration
}
try {
return (await navigator.serviceWorker.getRegistration()) ?? null;
- } catch {
+ } catch (error) {
+ logger.warn('Failed to read notification service worker registration', {error});
return null;
}
};
@@ -364,7 +352,9 @@ export async function showNotification({
if (typeof electronApi.flashFrame === 'function' && !document.hasFocus()) {
electronApi.flashFrame(false);
}
- } catch {}
+ } catch (error) {
+ logger.warn('Failed to flash the desktop window for a notification', {error});
+ }
const result = await electronApi.showNotification({
id,
title,
@@ -372,8 +362,8 @@ export async function showNotification({
body,
icon: await resolveNativeNotificationIcon(icon),
url,
+ accountKey: accountKey ?? undefined,
});
- rememberNotificationAccount(result.id, accountKey);
return {browserNotification: null, nativeNotificationId: result.id};
} catch (error) {
logger.error('Electron native notification show failed; refusing browser/Web Push fallback', {error});
@@ -394,24 +384,19 @@ export async function showNotification({
if (typeof Notification !== 'undefined' && Notification.permission === 'granted') {
try {
return tryShowNotificationViaWindowNotification({title, body, url, icon, accountKey});
- } catch {
+ } catch (error) {
+ logger.warn('Window notification failed; retrying through service worker', {error});
const swFallback = await tryShowNotificationViaServiceWorker({title, body, url, icon, targetUserId});
return swFallback.result;
}
}
return swAttempt.result;
- } catch {
+ } catch (error) {
+ logger.warn('Notification delivery failed', {error});
return {browserNotification: null, nativeNotificationId: null};
}
}
-export function closeNativeNotification(id: string): void {
- const electronApi = getElectronAPI();
- if (electronApi) {
- electronApi.closeNotification(id);
- }
-}
-
export function closeNativeNotifications(ids: Array<string>): void {
if (ids.length === 0) return;
const electronApi = getElectronAPI();
diff --git a/fluxer_app/src/features/ui/state/Notification.ts b/fluxer_app/src/features/ui/state/Notification.ts
index 44db15ad5..10043f7a1 100644
--- a/fluxer_app/src/features/ui/state/Notification.ts
+++ b/fluxer_app/src/features/ui/state/Notification.ts
@@ -17,8 +17,10 @@ import {Message} from '@app/features/messaging/models/MessagingMessage';
import * as MessageUtils from '@app/features/messaging/utils/MessageUtils';
import Navigation from '@app/features/navigation/state/Navigation';
import SelectedChannel from '@app/features/navigation/state/SelectedChannel';
+import {startAccountEngineNotifications} from '@app/features/notification/utils/AccountEngineNotifications';
import {buildMessageNotificationBody} from '@app/features/notification/utils/MessageNotificationPreview';
import {getNotificationIconURL} from '@app/features/notification/utils/NotificationIconURL';
+import {clearChannelNotifications, trackNotification} from '@app/features/notification/utils/NotificationTracker';
import * as NotificationUtils from '@app/features/notification/utils/NotificationUtils';
import * as PushSubscriptionService from '@app/features/platform/push/PushSubscriptionService';
import {IS_DEV} from '@app/features/platform/types/Env';
@@ -71,50 +73,12 @@ export enum TTSNotificationMode {
NEVER = 2,
}
-const MAX_PER_CHANNEL = 5;
const CACHE_SIZE = 500;
-interface TrackedNotification {
- browserNotification: Notification | null;
- nativeId: string | null;
+function clearCurrentAccountChannelNotifications(channelId: string): void {
+ clearChannelNotifications(Accounts.currentAccountKey, channelId);
}
-const notificationTracker = new (class {
- private channels: Record<string, Array<TrackedNotification>> = {};
-
- track(channelId: string, notification: TrackedNotification): void {
- let notifications = this.channels[channelId];
- if (notifications == null) {
- notifications = [];
- this.channels[channelId] = notifications;
- }
- notifications.push(notification);
- while (notifications.length > MAX_PER_CHANNEL) {
- const old = notifications.shift();
- if (old) {
- old.browserNotification?.close();
- if (old.nativeId) {
- NotificationUtils.closeNativeNotification(old.nativeId);
- }
- }
- }
- }
-
- clearChannel(channelId: string): void {
- const notifications = this.channels[channelId];
- if (notifications == null) return;
- delete this.channels[channelId];
- const browserNotifications = notifications
- .map((n) => n.browserNotification)
- .filter((n): n is Notification => n != null);
- browserNotifications.forEach((notification) => notification.close());
- const nativeIds = notifications.map((n) => n.nativeId).filter((id): id is string => id != null);
- if (nativeIds.length > 0) {
- NotificationUtils.closeNativeNotifications(nativeIds);
- }
- }
-})();
-
type NotificationData = Readonly<{
message: WireMessage;
messageRecord: Message;
@@ -157,6 +121,7 @@ class NotificationState {
});
queueMicrotask(() => {
NotificationUtils.ensureDesktopNotificationClickHandler();
+ startAccountEngineNotifications();
});
queueMicrotask(() => {
this.accountReactionDisposer = reaction(
@@ -260,6 +225,7 @@ class NotificationState {
if (StreamerMode.shouldDisableNotifications) return null;
const channel = Channels.getChannel(message.channel_id);
if (!channel) return null;
+ if (channel.isPrivate() && RuntimeConfig.directMessagesDisabled) return null;
if (message.author.id === Authentication.currentUserId) return null;
if (Relationships.isBlocked(message.author.id)) return null;
if (LocalPresence.getStatus() === StatusTypes.DND) return null;
@@ -376,6 +342,7 @@ class NotificationState {
channel.guildId && channel.guildId !== ME
? Routes.channelMessage(channel.guildId, channel.id, message.id)
: Routes.dmChannelMessage(channel.id, message.id);
+ const accountKey = Accounts.currentAccountKey;
try {
const result = await NotificationUtils.showNotification({
id: message.id,
@@ -385,9 +352,9 @@ class NotificationState {
icon: getNotificationIconURL(user, channel.guildId),
url: notificationUrl,
playSound: false,
- accountKey: Accounts.currentAccountKey,
+ accountKey,
});
- notificationTracker.track(channel.id, {
+ trackNotification(accountKey, channel.id, {
browserNotification: result.browserNotification,
nativeId: result.nativeNotificationId,
});
@@ -478,23 +445,23 @@ class NotificationState {
if (focused) {
const channelId = SelectedChannel.currentChannelId;
if (channelId) {
- notificationTracker.clearChannel(channelId);
+ clearCurrentAccountChannelNotifications(channelId);
}
}
}
handleChannelSelect({channelId}: {channelId?: string | null}): void {
if (channelId) {
- notificationTracker.clearChannel(channelId);
+ clearCurrentAccountChannelNotifications(channelId);
}
}
handleMessageAck({channelId}: {channelId: string}): void {
- notificationTracker.clearChannel(channelId);
+ clearCurrentAccountChannelNotifications(channelId);
}
handleMessageDelete({channelId}: {channelId: string}): void {
- notificationTracker.clearChannel(channelId);
+ clearCurrentAccountChannelNotifications(channelId);
}
handleRelationshipNotification(
@@ -503,7 +470,7 @@ class NotificationState {
event?: 'add' | 'update';
},
): void {
- if (RuntimeConfig.directMessagesDisabled) {
+ if (RuntimeConfig.friendsDisabled) {
return;
}
if (StreamerMode.shouldDisableNotifications) {
diff --git a/fluxer_app/src/types/electron.d.ts b/fluxer_app/src/types/electron.d.ts
index 2f65cc792..2f038a637 100644
--- a/fluxer_app/src/types/electron.d.ts
+++ b/fluxer_app/src/types/electron.d.ts
@@ -1,6 +1,7 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
import type {DesktopAccountStorageAPI} from '@fluxer/desktop_ipc/src/AccountContract';
+import type {AccountEngineRendererAPI} from '@fluxer/desktop_ipc/src/AccountEngineContract';
import type {DesktopHandoffAPI} from '@fluxer/desktop_ipc/src/BrowserHandoffContract';
import type {DesktopCapabilityManifest} from '@fluxer/desktop_ipc/src/CapabilityManifest';
import type {
@@ -120,7 +121,9 @@ export type TrayActionPayload =
| {action: 'toggle-mute'}
| {action: 'toggle-deafen'}
| {action: 'disconnect-voice'}
- | {action: 'check-for-updates'};
+ | {action: 'check-for-updates'}
+ | {action: 'switch-account'; accountKey: string}
+ | {action: 'open-account-switcher'};
export interface TextareaContextMenuParams {
x: number;
@@ -145,6 +148,7 @@ export interface NotificationPayload {
body: string;
icon?: string;
url?: string;
+ accountKey?: string;
}
export interface GlobalShortcutsPortalStatus {
@@ -279,7 +283,7 @@ export interface ElectronAPI {
getInitialDeepLink(): Promise<string | null>;
onDeepLink(callback: (url: string) => void): () => void;
onTextareaContextMenu(callback: (params: TextareaContextMenuParams) => void): () => void;
- onNotificationClick(callback: (id: string, url?: string) => void): () => void;
+ onNotificationClick(callback: (id: string, url?: string | null, accountKey?: string | null) => void): () => void;
showNotification(payload: NotificationPayload): Promise<{id: string}>;
shouldPlayNotificationSound?(): Promise<boolean>;
closeNotification(id: string): void;
@@ -326,12 +330,14 @@ export interface ElectronAPI {
getAccessibilitySupportEnabled?(): Promise<boolean>;
onAccessibilitySupportChanged?(callback: (enabled: boolean) => void): () => void;
getLinuxAppearance?(): Promise<LinuxAppearanceSnapshot>;
+ setPrebootTheme?(theme: string): void;
onLinuxAppearanceChanged?(callback: (snapshot: LinuxAppearanceSnapshot) => void): () => void;
onZoomIn?(callback: () => void): () => void;
onZoomOut?(callback: () => void): () => void;
onZoomReset?(callback: () => void): () => void;
onOpenSettings?(callback: () => void): () => void;
setTrayRuntimeState?(state: Partial<TrayRuntimeStatePayload>): void;
+ setDirectMessagesAvailable?(available: boolean): void;
acquireStreamingPriority?(): void;
releaseStreamingPriority?(): void;
getStreamingPriorityDiagnostics?(): Promise<StreamingPriorityDiagnostics>;
@@ -352,9 +358,9 @@ export interface ElectronAPI {
onWindowLiveResizeChange?(callback: (isResizing: boolean) => void): () => void;
onWindowMaximizeChange?(callback: (isMaximized: boolean) => void): () => void;
windowIsMaximized?(): Promise<boolean>;
- focusThemeStudioPopout?(): Promise<boolean>;
popoutSetAlwaysOnTop?(key: string, flag: boolean): Promise<boolean>;
popoutFocus?(key: string): Promise<boolean>;
+ cssEditorWindow?: true;
openVoiceDebugEventSinkPopout?(entries: Array<DesktopVoiceDebugEventSinkEntry>): Promise<void>;
appendVoiceDebugEventSinkEntries?(entries: Array<DesktopVoiceDebugEventSinkEntry>): void;
setVoiceDebugEventSinkStatsHtml?(html: string): void;
@@ -385,10 +391,12 @@ export interface ElectronAPI {
desktopModules?: DesktopModuleAPI;
desktopUpdate?: DesktopUpdateAPI;
reportLastRoute?: (routePath: string) => void;
+ reportInstanceProductName?: (instanceKey: string, productName: string) => void;
notifyFirstContentPainted?: () => void;
localAppUpload?: DesktopLocalAppUploadAPI;
localApp?: DesktopLocalAppInfo;
nativeGatewayTransport?: NativeGatewayTransportAPI;
+ accountEngine?: AccountEngineRendererAPI;
setZoomFactor(factor: number): void;
}