Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/native-push-notifications.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
default: minor
---

Add native push notifications with reply actions, content preview, and configurable gateway
2 changes: 1 addition & 1 deletion src-tauri/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 3 additions & 3 deletions src-tauri/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -75,12 +75,12 @@ windows = { version = "0.61", features = [
tauri-plugin-single-instance = { version = "2.4.3", features = ["deep-link"] }

[target.'cfg(any(windows, target_os = "linux"))'.dependencies]
tauri-plugin-notifications = { git = "https://github.com/SableClient/tauri-plugin-notifications.git", rev = "0ca647a8d762cbba2ecfbefed7ff13565ec46229" }
tauri-plugin-notifications = { git = "https://github.com/SableClient/tauri-plugin-notifications.git", rev = "cc3a468263db75e40a8a4751f3dae9bce5bc4234" }

# default-features = false drops notify-rust so macOS uses the native
# UNUserNotificationCenter backend (needs a signed .app to deliver).
[target.'cfg(target_os = "macos")'.dependencies]
tauri-plugin-notifications = { git = "https://github.com/SableClient/tauri-plugin-notifications.git", rev = "0ca647a8d762cbba2ecfbefed7ff13565ec46229", default-features = false }
tauri-plugin-notifications = { git = "https://github.com/SableClient/tauri-plugin-notifications.git", rev = "cc3a468263db75e40a8a4751f3dae9bce5bc4234", default-features = false }

[target.'cfg(not(any(target_os = "android", target_os = "ios")))'.dependencies]
tauri-plugin-updater = { version = "2", optional = true }
Expand All @@ -104,7 +104,7 @@ cef = { version = "=148.0.0", optional = true }
libloading = "0.8"

[target.'cfg(any(target_os = "android", target_os = "ios"))'.dependencies]
tauri-plugin-notifications = { git = "https://github.com/SableClient/tauri-plugin-notifications.git", rev = "0ca647a8d762cbba2ecfbefed7ff13565ec46229", features = [
tauri-plugin-notifications = { git = "https://github.com/SableClient/tauri-plugin-notifications.git", rev = "cc3a468263db75e40a8a4751f3dae9bce5bc4234", features = [
"push-notifications",
] }
tauri-plugin-edge-to-edge = { git = "https://github.com/SableClient/tauri-plugin-edge-to-edge.git", rev = "33c6116c27be28c06df5a9d02231ecc5fdeb93c5" }
Expand Down
16 changes: 16 additions & 0 deletions src-tauri/tauri.conf.json
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,22 @@
"appLink": false
}
]
},
"notifications": {
"actionTypes": [
{
"id": "sable-message",
"actions": [
{
"id": "sable-reply",
"title": "Reply",
"input": true,
"inputButtonTitle": "Send",
"inputPlaceholder": "Type a reply"
}
]
}
]
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,8 @@ export function NotificationTransportRuntimeFeature() {
settingsAtom,
'showMessageContentInEncryptedNotifications'
);
const [useRichPushPayloads] = useSetting(settingsAtom, 'useRichPushPayloads');
const [pushNotifyUrlOverride] = useSetting(settingsAtom, 'pushNotifyUrlOverride');

const runtimeRef = useRef<NotificationTransportRuntime>();
if (!runtimeRef.current) runtimeRef.current = new NotificationTransportRuntime();
Expand Down Expand Up @@ -99,6 +101,8 @@ export function NotificationTransportRuntimeFeature() {
vapidPublicKey?: string;
webPushAppID?: string;
pushNotifyUrl?: string;
useRichPushPayloads?: boolean;
pushNotifyUrlOverride?: string;
}>({});
upConfigRef.current = {
unifiedPushAppID:
Expand All @@ -110,6 +114,8 @@ export function NotificationTransportRuntimeFeature() {
vapidPublicKey: clientConfig.pushNotificationDetails?.vapidPublicKey,
webPushAppID: clientConfig.pushNotificationDetails?.webPushAppID,
pushNotifyUrl: clientConfig.pushNotificationDetails?.pushNotifyUrl,
useRichPushPayloads,
pushNotifyUrlOverride,
};

// Keep the pusher current: establish it when UnifiedPush becomes the active
Expand Down Expand Up @@ -149,7 +155,14 @@ export function NotificationTransportRuntimeFeature() {
})();

return () => {};
}, [provider, mx, setBackgroundPushEnabled, setBackgroundPushProvider]);
}, [
provider,
mx,
useRichPushPayloads,
pushNotifyUrlOverride,
setBackgroundPushEnabled,
setBackgroundPushProvider,
]);

useEffect(
() => () => {
Expand Down
37 changes: 37 additions & 0 deletions src/app/features/settings/notifications/PushPusherConfig.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
export type PushPusherSettings = {
useRichPushPayloads?: boolean;
pushNotifyUrlOverride?: string;
};

export function resolvePushNotifyUrl(
configuredUrl: string | undefined,
override: string | undefined
): string {
const candidate = override?.trim() || configuredUrl?.trim();
if (!candidate)
throw new Error('Push requires pushNotificationDetails.pushNotifyUrl in config.json.');

let url: URL;
try {
url = new URL(candidate);
} catch {
throw new Error('Push gateway URL must be a full HTTPS URL ending in /notify.');
}
if (
url.protocol !== 'https:' ||
url.username ||
url.password ||
url.hash ||
url.pathname !== '/_matrix/push/v1/notify'
) {
throw new Error('Push gateway URL must be an HTTPS Matrix /_matrix/push/v1/notify endpoint.');
}
return url.toString();
}

export function withPushPayloadFormat<T extends Record<string, unknown>>(
data: T,
useRichPushPayloads = false
): T | (T & { format: 'event_id_only' }) {
return useRichPushPayloads ? data : { ...data, format: 'event_id_only' };
}
21 changes: 21 additions & 0 deletions src/app/features/settings/notifications/SystemNotification.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -458,6 +458,8 @@ function BackgroundPushNotificationSetting() {
settingsAtom,
'pushTransportOverride'
);
const [useRichPushPayloads] = useSetting(settingsAtom, 'useRichPushPayloads');
const [pushNotifyUrlOverride] = useSetting(settingsAtom, 'pushNotifyUrlOverride');
const [legacyPushNotifications, setLegacyPushNotifications] = useSetting(
settingsAtom,
'usePushNotifications'
Expand Down Expand Up @@ -591,6 +593,8 @@ function BackgroundPushNotificationSetting() {
vapidPublicKey: clientConfig.pushNotificationDetails?.vapidPublicKey,
webPushAppID: clientConfig.pushNotificationDetails?.webPushAppID,
pushNotifyUrl: clientConfig.pushNotificationDetails?.pushNotifyUrl,
useRichPushPayloads,
pushNotifyUrlOverride,
});

const buildRegisteredUnifiedPushState = (
Expand Down Expand Up @@ -1002,6 +1006,10 @@ export function SystemNotification() {
settingsAtom,
'clearNotificationsOnRead'
);
const [useRichPushPayloads, setUseRichPushPayloads] = useSetting(
settingsAtom,
'useRichPushPayloads'
);
const [showUnreadCounts, setShowUnreadCounts] = useSetting(settingsAtom, 'showUnreadCounts');
const [badgeCountDMsOnly, setBadgeCountDMsOnly] = useSetting(settingsAtom, 'badgeCountDMsOnly');
const [showPingCounts, setShowPingCounts] = useSetting(settingsAtom, 'showPingCounts');
Expand Down Expand Up @@ -1126,6 +1134,19 @@ export function SystemNotification() {
}
/>
</SequenceCard>
<SequenceCard
className={SequenceCardStyle}
variant="SurfaceVariant"
direction="Column"
gap="400"
>
<SettingTile
title="Rich Push Payloads"
focusId="rich-push-payloads"
description="Include message content in push payloads for faster notifications. Your push gateway can see unencrypted message text."
after={<Switch value={useRichPushPayloads} onChange={setUseRichPushPayloads} />}
/>
</SequenceCard>
<SequenceCard
className={SequenceCardStyle}
variant="SurfaceVariant"
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { isTauri } from '@tauri-apps/api/core';
import { addPluginListener, invoke, isTauri } from '@tauri-apps/api/core';
import { type as osType } from '@tauri-apps/plugin-os';

export type NotificationPluginListener = {
Expand Down Expand Up @@ -30,14 +30,84 @@ export type TauriNotificationsApi = {
onNotificationClicked: (
listener: (data: { id: number; data?: Record<string, string> }) => void
) => Promise<NotificationPluginListener>;
registerActionTypes: (types: NotificationActionType[]) => Promise<void>;
onAction: (
listener: (event: NotificationActionEvent) => void
) => Promise<NotificationPluginListener>;
};

export type NotificationActionType = {
id: string;
actions: Array<{ id: string; title: string; input?: boolean }>;
};

export type NotificationActionNotification = Record<string, unknown> & {
actionTypeId: string;
extra?: Record<string, unknown>;
};

export type NotificationActionEvent = {
actionId: string;
inputValue?: string | null;
notification: NotificationActionNotification;
};

type ActionListenerDependencies = { addListener: typeof addPluginListener; invoke: typeof invoke };
let actionListenerCount = 0;
let actionListenerTransition: Promise<void> = Promise.resolve();

const transitionActionListener = (invokeFn: typeof invoke, active: boolean): Promise<void> => {
actionListenerTransition = actionListenerTransition
.catch(() => {})
.then(async () => {
await invokeFn('plugin:notifications|set_action_listener_active', { active });
});
return actionListenerTransition;
};

export async function subscribeToNativeNotificationActions(
listener: (event: NotificationActionEvent) => void,
dependencies: ActionListenerDependencies = { addListener: addPluginListener, invoke }
): Promise<NotificationPluginListener> {
const pluginListener = await dependencies.addListener(
'notifications',
'actionPerformed',
listener
);
try {
actionListenerCount += 1;
if (actionListenerCount === 1) await transitionActionListener(dependencies.invoke, true);
} catch (error) {
actionListenerCount = Math.max(0, actionListenerCount - 1);
await pluginListener.unregister();
throw error;
}
return {
unregister: async () => {
try {
actionListenerCount = Math.max(0, actionListenerCount - 1);
if (actionListenerCount === 0) await transitionActionListener(dependencies.invoke, false);
} finally {
await pluginListener.unregister();
}
},
};
}

let notificationsApiPromise: Promise<TauriNotificationsApi> | null = null;

export async function getTauriNotificationsApi(): Promise<TauriNotificationsApi> {
if (!notificationsApiPromise) {
notificationsApiPromise =
import('@choochmeque/tauri-plugin-notifications-api') as unknown as Promise<TauriNotificationsApi>;
notificationsApiPromise = import('@choochmeque/tauri-plugin-notifications-api').then(
(api) =>
({
...api,
onAction: subscribeToNativeNotificationActions,
}) as unknown as TauriNotificationsApi
);
notificationsApiPromise.catch(() => {
notificationsApiPromise = null;
});
}

return notificationsApiPromise;
Expand Down Expand Up @@ -70,6 +140,7 @@ export async function ensureTauriNotificationPermission(): Promise<boolean> {
const DESKTOP_TAURI_OS = new Set(['linux', 'macos', 'windows']);
export const isDesktopTauri = (): boolean => isTauri() && DESKTOP_TAURI_OS.has(osType());
export const isIosTauri = (): boolean => isTauri() && osType() === 'ios';
export const isAndroidTauri = (): boolean => isTauri() && osType() === 'android';
// Platforms where OS notifications go through the native plugin instead of web APIs.
export const isNativeNotificationTauri = (): boolean => isDesktopTauri() || isIosTauri();

Expand All @@ -84,15 +155,20 @@ export type NativeTauriNotification = {
title: string;
body?: string;
silent?: boolean;
/** Attached to the notification and handed back by onNotificationClicked. */
extra?: Record<string, string>;
actionTypeId?: string;
group?: string;
icon?: string;
};

export async function sendNativeTauriNotification({
title,
body,
silent,
extra,
actionTypeId,
group,
icon,
}: NativeTauriNotification): Promise<void> {
if (!(await ensureTauriNotificationPermission())) return;
const api = await getTauriNotificationsApi();
Expand All @@ -102,5 +178,8 @@ export async function sendNativeTauriNotification({
body,
silent: silent ?? false,
extra,
...(actionTypeId ? { actionTypeId } : {}),
...(group ? { group } : {}),
...(icon ? { icon } : {}),
});
}
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ const matrixClient = vi.hoisted(() => ({
getPushers: vi
.fn<() => Promise<{ pushers: Array<unknown> }>>()
.mockResolvedValue({ pushers: [] }),
getSafeUserId: vi.fn<() => string>(() => '@user:example.com'),
}));

vi.mock('./UnifiedPushTransport', () => unifiedPushTransport);
Expand Down
Loading
Loading