feat(tauri): Implement media caching and notification enhancements

This commit is contained in:
TastelessVoid authored and hazre committed 2026-03-12 17:10:22 +01:00
1 parent f9f37a157b
commit daeec6035d
56 files changed
+683 -447

No files matched your search

+1 -2
View File
@@ -11,8 +11,7 @@
"pushNotifyUrl": "https://cinny.cc/_matrix/push/v1/notify",
"vapidPublicKey": "BHLwykXs79AbKNiblEtZZRAgnt7o5_ieImhVJD8QZ01MVwAHnXwZzNgQEJJEU3E5CVsihoKtb7yaNe5x3vmkWkI",
"webPushAppID": "cc.cinny.web",
"unifiedPushAppID": "moe.sable.up",
"unifiedPushGatewayUrl": "https://cinny.cc/_matrix/push/v1/notify"
"unifiedPushAppID": "moe.sable.up"
},
"slidingSync": {
Submodule crates/tauri-plugin-notifications added at ea3f3d8d05.
+4 -1
View File
@@ -3,7 +3,10 @@
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0" />
<meta
name="viewport"
content="width=device-width, initial-scale=1.0, maximum-scale=1.0, viewport-fit=cover"
/>
<title>Sable Client</title>
<meta name="name" content="Sable" />
<meta name="author" content="7w1" />
+1
View File
@@ -94,6 +94,7 @@
"slate-history": "^0.113.1",
"slate-react": "^0.123.0",
"tauri-plugin-splashscreen-api": "file:./crates/tauri-plugin-splashscreen",
"@choochmeque/tauri-plugin-notifications-api": "file:./crates/tauri-plugin-notifications",
"ua-parser-js": "^1.0.41",
"workbox-precaching": "^7.4.0"
},
+3 -1
View File
@@ -17,8 +17,10 @@ const ANDROID_ICONS = [
`${dir}/ic_launcher.png`,
`${dir}/ic_launcher_round.png`,
`${dir}/ic_launcher_foreground.png`,
`${dir}/ic_notification.png`,
])
.concat(['mipmap-anydpi-v26/ic_launcher.xml', 'values/ic_launcher_background.xml']);
.concat(['mipmap-anydpi-v26/ic_launcher.xml', 'values/ic_launcher_background.xml'])
.concat(['drawable/ic_notification.xml', 'drawable/notification_icon.xml']);
const IOS_ICONS = [
'[email protected]',
-1
View File
@@ -4243,7 +4243,6 @@ dependencies = [
[[package]]
name = "tauri-plugin-notifications"
version = "0.4.3"
source = "git+https://github.com/TastelessVoid/tauri-plugin-notifications.git?branch=unified-push-support#3d55514246037665192103dc0feeeffafda00557"
dependencies = [
"log",
"notify-rust",
+1 -1
View File
@@ -53,5 +53,5 @@ tauri-plugin-single-instance = { version = "2.4.0", features = ["deep-link"] }
tauri-plugin-window-state = "2.4.1"
[target.'cfg(target_os = "android")'.dependencies]
tauri-plugin-notifications = { git = "https://github.com/TastelessVoid/tauri-plugin-notifications.git", branch = "unified-push-support", features = ["unified-push"] }
tauri-plugin-notifications = { path = "../crates/tauri-plugin-notifications", features = ["unified-push"] }
@@ -7,6 +7,7 @@
<application
android:icon="@mipmap/ic_launcher"
android:roundIcon="@mipmap/ic_launcher_round"
android:label="@string/app_name"
android:theme="@style/Theme.sable"
android:usesCleartextTraffic="${usesCleartextTraffic}">
@@ -1,12 +1,20 @@
package moe.sable.app
import android.graphics.Bitmap
import android.os.Bundle
import android.webkit.WebView
import android.webkit.WebViewClient
import androidx.activity.enableEdgeToEdge
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
class MainActivity : TauriActivity() {
private var lastTop = 0f
private var lastBottom = 0f
private var lastLeft = 0f
private var lastRight = 0f
private var webViewRef: WebView? = null
override fun onCreate(savedInstanceState: Bundle?) {
enableEdgeToEdge()
super.onCreate(savedInstanceState)
@@ -14,10 +22,80 @@ class MainActivity : TauriActivity() {
override fun onWebViewCreate(webView: WebView) {
super.onWebViewCreate(webView)
webViewRef = webView
val originalClient = webView.webViewClient
webView.webViewClient = object : WebViewClient() {
override fun onPageStarted(view: WebView, url: String, favicon: Bitmap?) {
originalClient.onPageStarted(view, url, favicon)
injectCssInsets(view)
}
override fun onPageFinished(view: WebView, url: String) {
originalClient.onPageFinished(view, url)
injectCssInsets(view)
}
override fun onPageCommitVisible(view: WebView, url: String) {
super.onPageCommitVisible(view, url)
injectCssInsets(view)
}
override fun shouldOverrideUrlLoading(
view: WebView,
request: android.webkit.WebResourceRequest
): Boolean = originalClient.shouldOverrideUrlLoading(view, request)
override fun shouldInterceptRequest(
view: WebView,
request: android.webkit.WebResourceRequest
): android.webkit.WebResourceResponse? = originalClient.shouldInterceptRequest(view, request)
override fun onReceivedError(
view: WebView,
request: android.webkit.WebResourceRequest,
error: android.webkit.WebResourceError
) = originalClient.onReceivedError(view, request, error)
}
ViewCompat.setOnApplyWindowInsetsListener(webView) { view, insets ->
val bars = insets.getInsets(WindowInsetsCompat.Type.systemBars() or WindowInsetsCompat.Type.ime())
view.setPadding(bars.left, bars.top, bars.right, bars.bottom)
val bars = insets.getInsets(
WindowInsetsCompat.Type.systemBars() or WindowInsetsCompat.Type.displayCutout()
)
val ime = insets.getInsets(WindowInsetsCompat.Type.ime())
val density = view.resources.displayMetrics.density
lastTop = bars.top / density
lastBottom = maxOf(bars.bottom, ime.bottom) / density
lastLeft = bars.left / density
lastRight = bars.right / density
// Don't use setPadding — it gets clobbered by Wry/Tauri internals.
// Instead, rely solely on CSS custom properties for inset handling.
injectCssInsets(view as WebView)
WindowInsetsCompat.CONSUMED
}
// Wry may reset layout after onWebViewCreate — re-request insets.
webView.post { webView.requestApplyInsets() }
// Also re-request after a short delay to handle Wry's deferred setup.
webView.postDelayed({ webView.requestApplyInsets() }, 500)
}
private fun injectCssInsets(webView: WebView) {
webView.evaluateJavascript(
"""
(function() {
var s = document.documentElement.style;
s.setProperty('--sable-inset-top', '${lastTop}px');
s.setProperty('--sable-inset-bottom', '${lastBottom}px');
s.setProperty('--sable-inset-left', '${lastLeft}px');
s.setProperty('--sable-inset-right', '${lastRight}px');
})();
""".trimIndent(),
null
)
}
}
@@ -1,30 +0,0 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:aapt="http://schemas.android.com/aapt"
android:width="108dp"
android:height="108dp"
android:viewportWidth="108"
android:viewportHeight="108">
<path android:pathData="M31,63.928c0,0 6.4,-11 12.1,-13.1c7.2,-2.6 26,-1.4 26,-1.4l38.1,38.1L107,108.928l-32,-1L31,63.928z">
<aapt:attr name="android:fillColor">
<gradient
android:endX="85.84757"
android:endY="92.4963"
android:startX="42.9492"
android:startY="49.59793"
android:type="linear">
<item
android:color="#44000000"
android:offset="0.0" />
<item
android:color="#00000000"
android:offset="1.0" />
</gradient>
</aapt:attr>
</path>
<path
android:fillColor="#FFFFFF"
android:fillType="nonZero"
android:pathData="M65.3,45.828l3.8,-6.6c0.2,-0.4 0.1,-0.9 -0.3,-1.1c-0.4,-0.2 -0.9,-0.1 -1.1,0.3l-3.9,6.7c-6.3,-2.8 -13.4,-2.8 -19.7,0l-3.9,-6.7c-0.2,-0.4 -0.7,-0.5 -1.1,-0.3C38.8,38.328 38.7,38.828 38.9,39.228l3.8,6.6C36.2,49.428 31.7,56.028 31,63.928h46C76.3,56.028 71.8,49.428 65.3,45.828zM43.4,57.328c-0.8,0 -1.5,-0.5 -1.8,-1.2c-0.3,-0.7 -0.1,-1.5 0.4,-2.1c0.5,-0.5 1.4,-0.7 2.1,-0.4c0.7,0.3 1.2,1 1.2,1.8C45.3,56.528 44.5,57.328 43.4,57.328L43.4,57.328zM64.6,57.328c-0.8,0 -1.5,-0.5 -1.8,-1.2s-0.1,-1.5 0.4,-2.1c0.5,-0.5 1.4,-0.7 2.1,-0.4c0.7,0.3 1.2,1 1.2,1.8C66.5,56.528 65.6,57.328 64.6,57.328L64.6,57.328z"
android:strokeWidth="1"
android:strokeColor="#00000000" />
</vector>
@@ -1,170 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="108dp"
android:height="108dp"
android:viewportWidth="108"
android:viewportHeight="108">
<path
android:fillColor="#3DDC84"
android:pathData="M0,0h108v108h-108z" />
<path
android:fillColor="#00000000"
android:pathData="M9,0L9,108"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M19,0L19,108"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M29,0L29,108"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M39,0L39,108"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M49,0L49,108"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M59,0L59,108"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M69,0L69,108"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M79,0L79,108"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M89,0L89,108"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M99,0L99,108"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M0,9L108,9"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M0,19L108,19"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M0,29L108,29"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M0,39L108,39"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M0,49L108,49"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M0,59L108,59"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M0,69L108,69"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M0,79L108,79"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M0,89L108,89"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M0,99L108,99"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M19,29L89,29"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M19,39L89,39"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M19,49L89,49"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M19,59L89,59"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M19,69L89,69"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M19,79L89,79"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M29,19L29,89"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M39,19L39,89"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M49,19L49,89"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M59,19L59,89"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M69,19L69,89"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M79,19L79,89"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
</vector>
@@ -0,0 +1 @@
../../../../../../../icons/android/drawable/ic_notification.xml
@@ -0,0 +1 @@
../../../../../../../icons/android/drawable/notification_icon.xml
@@ -0,0 +1 @@
../../../../../../../icons/android/mipmap-anydpi-v26/ic_launcher.xml
Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.4 KiB

@@ -0,0 +1 @@
../../../../../../../icons/android/mipmap-hdpi/ic_launcher.png
Binary file not shown.

Before

Width:  |  Height:  |  Size: 14 KiB

@@ -0,0 +1 @@
../../../../../../../icons/android/mipmap-hdpi/ic_launcher_foreground.png
Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.4 KiB

@@ -0,0 +1 @@
../../../../../../../icons/android/mipmap-hdpi/ic_launcher_round.png
@@ -0,0 +1 @@
../../../../../../../icons/android/mipmap-hdpi/ic_notification.png
Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.3 KiB

@@ -0,0 +1 @@
../../../../../../../icons/android/mipmap-mdpi/ic_launcher.png
Binary file not shown.

Before

Width:  |  Height:  |  Size: 8.9 KiB

@@ -0,0 +1 @@
../../../../../../../icons/android/mipmap-mdpi/ic_launcher_foreground.png
Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.3 KiB

@@ -0,0 +1 @@
../../../../../../../icons/android/mipmap-mdpi/ic_launcher_round.png
@@ -0,0 +1 @@
../../../../../../../icons/android/mipmap-mdpi/ic_notification.png
Binary file not shown.

Before

Width:  |  Height:  |  Size: 7.8 KiB

@@ -0,0 +1 @@
../../../../../../../icons/android/mipmap-xhdpi/ic_launcher.png
Binary file not shown.

Before

Width:  |  Height:  |  Size: 18 KiB

@@ -0,0 +1 @@
../../../../../../../icons/android/mipmap-xhdpi/ic_launcher_foreground.png
Binary file not shown.

Before

Width:  |  Height:  |  Size: 7.8 KiB

@@ -0,0 +1 @@
../../../../../../../icons/android/mipmap-xhdpi/ic_launcher_round.png
@@ -0,0 +1 @@
../../../../../../../icons/android/mipmap-xhdpi/ic_notification.png
Binary file not shown.

Before

Width:  |  Height:  |  Size: 12 KiB

@@ -0,0 +1 @@
../../../../../../../icons/android/mipmap-xxhdpi/ic_launcher.png
Binary file not shown.

Before

Width:  |  Height:  |  Size: 29 KiB

@@ -0,0 +1 @@
../../../../../../../icons/android/mipmap-xxhdpi/ic_launcher_foreground.png
Binary file not shown.

Before

Width:  |  Height:  |  Size: 12 KiB

@@ -0,0 +1 @@
../../../../../../../icons/android/mipmap-xxhdpi/ic_launcher_round.png
@@ -0,0 +1 @@
../../../../../../../icons/android/mipmap-xxhdpi/ic_notification.png
Binary file not shown.

Before

Width:  |  Height:  |  Size: 16 KiB

@@ -0,0 +1 @@
../../../../../../../icons/android/mipmap-xxxhdpi/ic_launcher.png
Binary file not shown.

Before

Width:  |  Height:  |  Size: 40 KiB

@@ -0,0 +1 @@
../../../../../../../icons/android/mipmap-xxxhdpi/ic_launcher_foreground.png
Binary file not shown.

Before

Width:  |  Height:  |  Size: 16 KiB

@@ -0,0 +1 @@
../../../../../../../icons/android/mipmap-xxxhdpi/ic_launcher_round.png
@@ -0,0 +1 @@
../../../../../../../icons/android/mipmap-xxxhdpi/ic_notification.png
@@ -0,0 +1 @@
../../../../../../../icons/android/values/ic_launcher_background.xml
@@ -0,0 +1,7 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Notification small icon: monochrome (white-on-transparent) silhouette of
the Sable bird. Android's status bar tints this with the notification
accent colour, so only the bird shape should be opaque. -->
<bitmap xmlns:android="http://schemas.android.com/apk/res/android"
android:src="@mipmap/ic_notification" />
@@ -0,0 +1,7 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Alias so sendNotification({ icon: 'notification_icon' }) resolves correctly.
Points to a monochrome (white-on-transparent) silhouette of the Sable bird so
the status-bar icon renders the bird shape instead of just a filled circle. -->
<bitmap xmlns:android="http://schemas.android.com/apk/res/android"
android:src="@mipmap/ic_notification" />
Binary file not shown.

After

Width:  |  Height:  |  Size: 508 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 442 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 601 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 785 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 969 B

@@ -109,12 +109,26 @@ export const ImageContent = as<'div', ImageContentProps>(
}, [rawMediaUrl, resolvedMediaUrl, url, mimeType, encInfo, mediaToken])
);
// When the source download succeeds, reset image-element error state so the
// Retry button doesn't flash before the <img> has had a chance to load.
useEffect(() => {
if (srcState.status === AsyncStatus.Success) {
setError(false);
}
}, [srcState.status]);
const handleLoad = () => {
setLoad(true);
setError(false);
};
const handleError = () => {
setLoad(false);
setError(true);
// Only show the error if the source download already succeeded — if
// it's still loading the image element may fire a transient error
// before the blob URL is ready.
if (srcState.status === AsyncStatus.Success) {
setLoad(false);
setError(true);
}
};
const handleRetry = () => {
@@ -225,12 +239,13 @@ export const ImageContent = as<'div', ImageContentProps>(
)}
{(srcState.status === AsyncStatus.Loading || srcState.status === AsyncStatus.Success) &&
!load &&
!error &&
!blurred && (
<Box className={css.AbsoluteContainer} alignItems="Center" justifyContent="Center">
<Spinner variant="Secondary" />
</Box>
)}
{(error || srcState.status === AsyncStatus.Error) && (
{!load && (error || srcState.status === AsyncStatus.Error) && (
<Box className={css.AbsoluteContainer} alignItems="Center" justifyContent="Center">
<TooltipProvider
tooltip={
@@ -93,12 +93,26 @@ export const VideoContent = as<'div', VideoContentProps>(
}, [mx, url, useAuthentication, mimeType, encInfo, mediaToken])
);
// When the source download succeeds, reset video-element error state so the
// Retry button doesn't flash before the <video> has had a chance to load.
useEffect(() => {
if (srcState.status === AsyncStatus.Success) {
setError(false);
}
}, [srcState.status]);
const handleLoad = () => {
setLoad(true);
setError(false);
};
const handleError = () => {
setLoad(false);
setError(true);
// Only show the error if the source download already succeeded — if
// it's still loading the video element may fire a transient error
// before the blob URL is ready.
if (srcState.status === AsyncStatus.Success) {
setLoad(false);
setError(true);
}
};
const handleRetry = () => {
@@ -188,12 +202,13 @@ export const VideoContent = as<'div', VideoContentProps>(
)}
{(srcState.status === AsyncStatus.Loading || srcState.status === AsyncStatus.Success) &&
!load &&
!error &&
!blurred && (
<Box className={css.AbsoluteContainer} alignItems="Center" justifyContent="Center">
<Spinner variant="Secondary" />
</Box>
)}
{(error || srcState.status === AsyncStatus.Error) && (
{!load && (error || srcState.status === AsyncStatus.Error) && (
<Box className={css.AbsoluteContainer} alignItems="Center" justifyContent="Center">
<TooltipProvider
tooltip={
@@ -26,6 +26,8 @@ const slideOut = keyframes({
// Positions at the top of the viewport, spanning full width.
// Uses fixed positioning with safe-area-inset to handle iOS keyboard correctly.
// On iOS, the banner stays at the top of the visual viewport even when keyboard is open.
// On Android (Tauri) the insets are injected via JS from Kotlin; the
// env() fallback handles the window between page load and injection.
export const BannerContainer = style({
position: 'fixed',
// Use env(safe-area-inset-top) to respect device-specific safe areas (notches, etc)
@@ -38,6 +40,7 @@ export const BannerContainer = style({
flexDirection: 'column',
gap: config.space.S200,
padding: config.space.S400,
paddingTop: `calc(${config.space.S400} + var(--sable-inset-top, env(safe-area-inset-top, 0px)))`,
pointerEvents: 'none',
alignItems: 'stretch',
@@ -206,23 +206,41 @@ function UnifiedPushNotificationSetting() {
const [useUP, setUseUP] = useSetting(settingsAtom, 'useUnifiedPush');
const [upEndpoint, setUpEndpoint] = useAtom(unifiedPushEndpointAtom);
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const [distributors, setDistributors] = useState<string[]>([]);
const [currentDistributor, setCurrentDistributor] = useState<string>('');
const [menuCords, setMenuCords] = useState<RectCords>();
useEffect(() => {
getUnifiedPushDistributors()
.then((result: { distributors: string[] }) => setDistributors(result.distributors))
.catch(() => {});
getUnifiedPushDistributor()
.then((result: { distributor: string }) => setCurrentDistributor(result.distributor))
.catch(() => {});
Promise.all([
getUnifiedPushDistributors().catch(() => ({ distributors: [] as string[] })),
getUnifiedPushDistributor().catch(() => ({ distributor: '' })),
]).then(async ([distResult, savedResult]) => {
setDistributors(distResult.distributors);
setCurrentDistributor(savedResult.distributor);
// Auto-save the only available distributor when none is saved yet.
// UP connector 3.x requires an explicit selection before register() works.
if (!savedResult.distributor && distResult.distributors.length === 1) {
await saveUnifiedPushDistributor(distResult.distributors[0]);
setCurrentDistributor(distResult.distributors[0]);
}
});
}, []);
const handleToggle = async (wantsUP: boolean) => {
setIsLoading(true);
setError(null);
try {
if (wantsUP) {
// Ensure a distributor is saved before registration.
// UP connector 3.x requires an explicit distributor selection;
// if none is saved, register() silently does nothing.
if (!currentDistributor && distributors.length > 0) {
await saveUnifiedPushDistributor(distributors[0]);
setCurrentDistributor(distributors[0]);
}
const result = await enableUnifiedPush(mx, clientConfig);
setUpEndpoint(result);
setUseUP(true);
@@ -232,7 +250,9 @@ function UnifiedPushNotificationSetting() {
setUseUP(false);
}
} catch (e) {
const msg = e instanceof Error ? e.message : String(e);
console.error('UnifiedPush toggle failed:', e);
setError(msg);
} finally {
setIsLoading(false);
}
@@ -273,7 +293,11 @@ function UnifiedPushNotificationSetting() {
<SettingTile
title="UnifiedPush Notifications"
description={
distributors.length === 0 ? (
error ? (
<Text as="span" style={{ color: color.Critical.Main }} size="T200">
{error}
</Text>
) : distributors.length === 0 ? (
<Text as="span" style={{ color: color.Warning.Main }} size="T200">
No UnifiedPush distributor installed. Install one (e.g. ntfy, NextPush) to use this
feature.
@@ -9,23 +9,27 @@ import {
onUnifiedPushMessage,
onUnifiedPushEndpoint,
sendNotification,
removeActive,
createChannel,
Importance,
} from '$plugins/tauri-notifications';
import type { MessagingStyleMessage, MessagingStylePerson } from '$plugins/tauri-notifications';
import { EventType } from 'matrix-js-sdk/lib/@types/event';
import {
buildRoomMessageNotification,
resolveNotificationPreviewText,
} from '$utils/notificationStyle';
import { mxcUrlToHttp, authenticatedMediaFetch } from '$utils/matrix';
import { resolveNotificationPreviewText } from '$utils/notificationStyle';
import { getMxIdLocalPart } from '$utils/matrix';
import { getStateEvent, getMemberAvatarMxc } from '$utils/room';
import { StateEvent } from '$types/matrix/room';
export { getUnifiedPushDistributors, getUnifiedPushDistributor, saveUnifiedPushDistributor };
const UP_PUBLIC_GATEWAY = 'https://matrix.gateway.unifiedpush.org/_matrix/push/v1/notify';
/**
* Probes the UP endpoint to discover if the distributor exposes a
* Matrix-compatible push gateway (like FluffyChat does). Falls back
* to the well-known public gateway or the configured one.
* Probes the UP endpoint for a Matrix-compatible push gateway.
* Falls back to the configured or public UP gateway.
* Note: pushNotifyUrl (Sygnal) is NOT suitable — only a proper UP gateway works.
*/
async function discoverGateway(upEndpoint: string, configuredGateway?: string): Promise<string> {
const PUBLIC_GATEWAY = 'https://matrix.gateway.unifiedpush.org/_matrix/push/v1/notify';
async function discoverGateway(upEndpoint: string, unifiedPushGateway?: string): Promise<string> {
try {
const probeUrl = new URL(upEndpoint);
probeUrl.pathname = '/_matrix/push/v1/notify';
@@ -41,23 +45,49 @@ async function discoverGateway(upEndpoint: string, configuredGateway?: string):
}
}
} catch {
// Probe failed — fall through to configured or public gateway
// probe failed
}
return configuredGateway ?? PUBLIC_GATEWAY;
return unifiedPushGateway ?? UP_PUBLIC_GATEWAY;
}
const UP_REGISTER_TIMEOUT_MS = 30_000;
export async function enableUnifiedPush(
mx: MatrixClient,
clientConfig: ClientConfig
): Promise<{ endpoint: string; instance: string }> {
const { endpoint, instance } = await registerForUnifiedPush();
await createChannel({
id: 'messages',
name: 'Messages',
description: 'Matrix message and invite notifications',
importance: Importance.Default,
vibration: true,
});
const timeout = new Promise<never>((_, reject) => {
const id = setTimeout(() => {
reject(new Error('UnifiedPush registration timed out'));
clearTimeout(id);
}, UP_REGISTER_TIMEOUT_MS);
});
const { endpoint, instance, pubKeySet } = await Promise.race([registerForUnifiedPush(), timeout]);
const appId = clientConfig.pushNotificationDetails?.unifiedPushAppID ?? 'moe.sable.up';
const configuredGateway =
clientConfig.pushNotificationDetails?.unifiedPushGatewayUrl ??
clientConfig.pushNotificationDetails?.pushNotifyUrl;
const gatewayUrl = await discoverGateway(endpoint, configuredGateway);
// Don't fall back to pushNotifyUrl (Sygnal) — it cannot forward to UP endpoints.
const unifiedPushGateway = clientConfig.pushNotificationDetails?.unifiedPushGatewayUrl;
const gatewayUrl = await discoverGateway(endpoint, unifiedPushGateway);
const pusherData: Record<string, string> = {
url: gatewayUrl,
};
// VAPID-capable distributors (e.g. NextPush) provide keys for RFC 8291 encryption.
if (pubKeySet) {
pusherData.p256dh = pubKeySet.pubKey;
pusherData.auth = pubKeySet.auth;
}
await mx.setPusher({
kind: 'http',
@@ -67,10 +97,7 @@ export async function enableUnifiedPush(
device_display_name:
(await mx.getDevice(mx.getDeviceId() ?? '')).display_name ?? 'Android Device',
lang: navigator.language || 'en',
data: {
url: gatewayUrl,
format: 'event_id_only',
},
data: pusherData,
append: false,
} as any);
@@ -97,62 +124,147 @@ export async function disableUnifiedPush(
type NotificationSettings = {
mx: MatrixClient;
useAuthentication: boolean;
showMessageContent: boolean;
showEncryptedMessageContent: boolean;
notificationSoundEnabled: boolean;
useInAppNotifications: boolean;
};
/**
* Derives a stable 32-bit notification ID from a room ID so
* newer messages in the same room replace the previous notification.
*/
// One MessagingStyle notification per room, accumulated into a single Android group.
const NOTIF_GROUP_KEY = 'matrix_messages';
const MAX_MESSAGES = 10;
function hashCode(str: string): number {
let hash = 0;
for (let i = 0; i < str.length; i += 1) {
// eslint-disable-next-line no-bitwise
hash = (Math.imul(31, hash) + str.charCodeAt(i)) | 0;
}
return hash;
return Math.abs(hash);
}
/**
* Downloads an mxc:// avatar with authentication and returns a data: URL.
* Returns undefined on any failure so the notification just omits the avatar.
*/
async function resolveAvatarDataUrl(
mx: MatrixClient,
useAuthentication: boolean,
mxcUrl?: string
): Promise<string | undefined> {
const roomNotifId = (roomId: string) => hashCode(roomId);
const SUMMARY_NOTIF_ID = hashCode('sable-group-summary');
/** Accumulated messages per room, cleared when unread drops to 0. */
type RoomNotifCache = {
roomName: string;
messages: MessagingStyleMessage[];
seenEventIds: Set<string>;
isGroupConversation: boolean;
latestEventId?: string;
};
const roomNotifCaches = new Map<string, RoomNotifCache>();
function resolveAvatarUrl(mx: MatrixClient, roomId: string, userId: string): string | undefined {
const room = mx.getRoom(roomId);
if (!room) return undefined;
const mxcUrl = getMemberAvatarMxc(room, userId);
if (!mxcUrl) return undefined;
return mx.mxcUrlToHttp(mxcUrl, 96, 96, 'crop', undefined, false, true) ?? undefined;
}
function getOrCreateRoomCache(roomId: string, roomName: string): RoomNotifCache {
let cache = roomNotifCaches.get(roomId);
if (!cache) {
cache = { roomName, messages: [], seenEventIds: new Set(), isGroupConversation: false };
roomNotifCaches.set(roomId, cache);
}
cache.roomName = roomName;
return cache;
}
/** Clears accumulated messages for a room and dismisses its notification. */
export async function clearRoomNotification(roomId: string) {
roomNotifCaches.delete(roomId);
try {
const httpUrl = mxcUrlToHttp(mx, mxcUrl, useAuthentication, 96, 96, 'scale');
if (!httpUrl) return undefined;
const res = await authenticatedMediaFetch(httpUrl, mx.getAccessToken());
if (!res.ok) return undefined;
const blob = await res.blob();
return await new Promise<string>((resolve) => {
const reader = new FileReader();
reader.onloadend = () => resolve(reader.result as string);
reader.readAsDataURL(blob);
});
await removeActive([{ id: roomNotifId(roomId) }]);
} catch {
return undefined;
// already dismissed
}
if (roomNotifCaches.size <= 1) {
try {
await removeActive([{ id: SUMMARY_NOTIF_ID }]);
} catch {
// ignore
}
}
}
async function handleUnifiedPushPayload(
raw: Record<string, unknown>,
getSettings: () => NotificationSettings
/** Posts (or updates) the per-room MessagingStyle notification and the group summary. */
async function postRoomNotification(
roomId: string,
cache: RoomNotifCache,
selfUser: MessagingStylePerson,
isSilent: boolean,
extra: Record<string, unknown>,
authToken?: string | null
) {
// Sygnal wraps the payload in a `notification` field;
// UP may also deliver the object flat.
const pushData = (raw.notification ?? raw) as Record<string, any>;
const eventType = pushData?.type as EventType | undefined;
if (!eventType) return;
const { messages, roomName, isGroupConversation } = cache;
const latestMsg = messages[messages.length - 1];
const latestBody = latestMsg ? `${latestMsg.sender?.name ?? 'You'}: ${latestMsg.text}` : '';
const settings = getSettings();
await sendNotification({
id: roomNotifId(roomId),
title: roomName,
body: latestBody,
channelId: 'messages',
group: NOTIF_GROUP_KEY,
icon: 'notification_icon',
silent: isSilent,
autoCancel: true,
extra,
messagingStyle: {
user: selfUser,
conversationTitle: isGroupConversation ? roomName : undefined,
isGroupConversation,
messages,
authToken: authToken ?? undefined,
},
});
// App-wide group summary — Android uses this when 4+ child notifications
// exist. With only one room there's nothing to summarise, and posting a
// summary can cause the OS to show the summary *instead of* the child
// MessagingStyle notification on some devices.
const roomCount = roomNotifCaches.size;
if (roomCount > 1) {
const totalMessages = Array.from(roomNotifCaches.values()).reduce(
(sum, c) => sum + c.messages.length,
0
);
const summaryText = `${totalMessages} messages in ${roomCount} chats`;
const inboxLines: string[] = [];
Array.from(roomNotifCaches.values()).forEach((c) => {
const latest = c.messages[c.messages.length - 1];
if (latest) {
inboxLines.push(`${c.roomName}: ${latest.sender?.name ?? 'You'}: ${latest.text}`);
}
});
await sendNotification({
id: SUMMARY_NOTIF_ID,
title: summaryText,
body: '',
summary: summaryText,
inboxLines: inboxLines.slice(-5),
channelId: 'messages',
group: NOTIF_GROUP_KEY,
groupSummary: true,
icon: 'notification_icon',
silent: true,
autoCancel: true,
});
}
}
/** Handles a rich push payload containing full event details (type, room_name, content, etc.). */
async function handleRichPushPayload(
pushData: Record<string, any>,
settings: NotificationSettings
) {
const eventType = pushData.type as EventType;
switch (eventType) {
case EventType.RoomMessage:
@@ -160,47 +272,83 @@ async function handleUnifiedPushPayload(
case EventType.RoomMessageEncrypted: {
const isEncrypted = eventType === EventType.RoomMessageEncrypted;
const avatarDataUrl = await resolveAvatarDataUrl(
settings.mx,
settings.useAuthentication,
pushData?.room_avatar_url
);
const payload = buildRoomMessageNotification({
roomName: pushData?.room_name,
username: pushData?.sender_display_name,
roomAvatar: avatarDataUrl ?? pushData?.room_avatar_url,
previewText: resolveNotificationPreviewText({
content: pushData?.content,
eventType: pushData?.type,
isEncryptedRoom: isEncrypted,
showMessageContent: settings.showMessageContent,
showEncryptedMessageContent: settings.showEncryptedMessageContent,
}),
silent: !settings.notificationSoundEnabled,
eventId: pushData?.event_id,
recipientId: typeof pushData?.user_id === 'string' ? pushData.user_id : undefined,
const previewText = resolveNotificationPreviewText({
content: pushData?.content,
eventType: pushData?.type,
isEncryptedRoom: isEncrypted,
showMessageContent: settings.showMessageContent,
showEncryptedMessageContent: settings.showEncryptedMessageContent,
});
const roomId: string | undefined = pushData?.room_id;
const roomName: string = pushData?.room_name ?? 'Unknown Room';
const senderName: string | undefined = pushData?.sender_display_name;
const senderId: string | undefined = pushData?.sender;
const isSilent = !settings.notificationSoundEnabled;
await sendNotification({
// Stable per-room ID so newer messages in the same room
// replace the previous notification instead of stacking.
id: roomId ? Math.abs(hashCode(roomId)) : undefined,
title: payload.title,
body: payload.options.body ?? undefined,
channelId: 'messages',
group: roomId,
icon: 'notification_icon',
silent: payload.options.silent ?? false,
autoCancel: true,
extra: {
const selfUserId = settings.mx.getUserId() ?? undefined;
const selfUser: MessagingStylePerson = {
name: 'You',
key: selfUserId,
iconUrl:
selfUserId && roomId ? resolveAvatarUrl(settings.mx, roomId, selfUserId) : undefined,
};
if (!roomId) {
await sendNotification({
title: roomName,
body: senderName ? `${senderName}: ${previewText}` : previewText,
channelId: 'messages',
icon: 'notification_icon',
silent: isSilent,
autoCancel: true,
});
break;
}
const sender: MessagingStylePerson | undefined = senderName
? {
name: senderName,
key: senderId,
iconUrl: senderId ? resolveAvatarUrl(settings.mx, roomId, senderId) : undefined,
}
: undefined;
const message: MessagingStyleMessage = {
text: previewText,
timestamp: Date.now(),
sender,
};
const cache = getOrCreateRoomCache(roomId, roomName);
const eventId: string | undefined = pushData?.event_id;
if (eventId && cache.seenEventIds.has(eventId)) break;
if (eventId) cache.seenEventIds.add(eventId);
cache.messages.push(message);
if (cache.messages.length > MAX_MESSAGES) {
cache.messages = cache.messages.slice(-MAX_MESSAGES);
}
cache.latestEventId = eventId;
const room = settings.mx.getRoom(roomId);
if (room) {
cache.isGroupConversation = (room.getJoinedMemberCount() ?? 0) > 2;
}
await postRoomNotification(
roomId,
cache,
selfUser,
isSilent,
{
room_id: roomId,
event_id: pushData?.event_id,
user_id: pushData?.user_id,
},
});
settings.mx.getAccessToken()
);
break;
}
case EventType.RoomMember: {
@@ -216,6 +364,7 @@ async function handleUnifiedPushPayload(
title: 'New Invitation',
body,
channelId: 'messages',
group: NOTIF_GROUP_KEY,
icon: 'notification_icon',
autoCancel: true,
extra: {
@@ -231,6 +380,130 @@ async function handleUnifiedPushPayload(
}
}
/**
* Handles a minimal push payload (event_id + room_id + counts) from
* the public UnifiedPush gateway, looking up context from local SDK state.
*/
async function handleMinimalPushPayload(
pushData: Record<string, any>,
settings: NotificationSettings
) {
const roomId: string | undefined = pushData?.room_id;
const eventId: string | undefined = pushData?.event_id;
const unread: number | undefined =
typeof pushData?.counts?.unread === 'number' ? pushData.counts.unread : undefined;
if (!roomId) return;
// Unread count of zero means the room was read — dismiss the notification.
if (unread === 0) {
await clearRoomNotification(roomId);
return;
}
const room = settings.mx.getRoom(roomId);
const roomName = room?.name ?? 'Unknown Room';
const isEncryptedRoom = room ? !!getStateEvent(room, StateEvent.RoomEncryption) : false;
let senderName: string | undefined;
let senderId: string | undefined;
let previewText: string | undefined;
if (room && eventId) {
const timeline = room.getLiveTimeline().getEvents();
const mEvent = timeline.find((e) => e.getId() === eventId);
if (mEvent) {
const sender = mEvent.getSender();
if (sender) {
const member = room.getMember(sender);
senderName = member?.name ?? getMxIdLocalPart(sender) ?? sender;
senderId = sender;
}
previewText = resolveNotificationPreviewText({
content: mEvent.getContent(),
eventType: mEvent.getType(),
isEncryptedRoom,
showMessageContent: settings.showMessageContent,
showEncryptedMessageContent: settings.showEncryptedMessageContent,
});
}
}
if (!previewText) {
previewText = isEncryptedRoom ? 'Encrypted message' : 'New message';
}
const selfUserId = settings.mx.getUserId() ?? undefined;
const selfUser: MessagingStylePerson = {
name: 'You',
key: selfUserId,
iconUrl: selfUserId && roomId ? resolveAvatarUrl(settings.mx, roomId, selfUserId) : undefined,
};
const sender: MessagingStylePerson | undefined = senderName
? {
name: senderName,
key: senderId,
iconUrl: senderId && roomId ? resolveAvatarUrl(settings.mx, roomId, senderId) : undefined,
}
: undefined;
const message: MessagingStyleMessage = {
text: previewText,
timestamp: Date.now(),
sender,
};
const cache = getOrCreateRoomCache(roomId, roomName);
if (eventId && cache.seenEventIds.has(eventId)) return;
if (eventId) cache.seenEventIds.add(eventId);
cache.messages.push(message);
if (cache.messages.length > MAX_MESSAGES) {
cache.messages = cache.messages.slice(-MAX_MESSAGES);
}
cache.latestEventId = eventId;
if (room) {
cache.isGroupConversation = (room.getJoinedMemberCount() ?? 0) > 2;
}
await postRoomNotification(
roomId,
cache,
selfUser,
!settings.notificationSoundEnabled,
{
room_id: roomId,
event_id: eventId,
},
settings.mx.getAccessToken()
);
}
async function handleUnifiedPushPayload(
raw: Record<string, unknown>,
getSettings: () => NotificationSettings
) {
const settings = getSettings();
// Skip system notification when in-app banners are active and visible.
if (document.visibilityState === 'visible' && settings.useInAppNotifications) {
return;
}
// The UP gateway wraps the Matrix push in a `notification` field.
const pushData = (raw.notification ?? raw) as Record<string, any>;
const eventType = pushData?.type as EventType | undefined;
if (eventType) {
await handleRichPushPayload(pushData, settings);
} else {
await handleMinimalPushPayload(pushData, settings);
}
}
export function listenForUnifiedPushMessages(getSettings: () => NotificationSettings) {
return onUnifiedPushMessage((data: Record<string, unknown>) => {
handleUnifiedPushPayload(data, getSettings);
+17 -8
View File
@@ -1,17 +1,15 @@
import { useState, useEffect } from 'react';
import { hasServiceWorker } from '$utils/platform';
import { authenticatedMediaFetch } from '$utils/matrix';
import { getFromMediaCache, putInMediaCache } from '$utils/mediaCache';
const blobCache = new Map<string, string>();
const inflightRequests = new Map<string, Promise<string | undefined>>();
/**
* On platforms without service workers (e.g. Android WebViews), media URLs
* that require authentication cannot be loaded directly by `<img>` tags
* because there is no SW to inject the Authorization header. This hook
* fetches the resource with the token attached and returns a blob URL.
*
* When a service worker IS available it returns the original URL unchanged.
* On platforms without a service worker (e.g. Android WebViews), fetches
* media with the access token and returns a blob: URL.
* When a SW is available the original URL is returned unchanged.
*/
export function useAuthenticatedMediaUrl(
url: string | undefined,
@@ -45,7 +43,15 @@ export function useAuthenticatedMediaUrl(
const fetchBlob = async () => {
let promise = inflightRequests.get(url);
if (!promise) {
promise = authenticatedMediaFetch(url, accessToken).then(async (res) => {
promise = (async () => {
const cachedBlob = await getFromMediaCache(url);
if (cachedBlob) {
const objectUrl = URL.createObjectURL(cachedBlob);
blobCache.set(url, objectUrl);
return objectUrl;
}
const res = await authenticatedMediaFetch(url, accessToken);
if (!res.ok) {
inflightRequests.delete(url);
return undefined;
@@ -53,8 +59,11 @@ export function useAuthenticatedMediaUrl(
const blob = await res.blob();
const objectUrl = URL.createObjectURL(blob);
blobCache.set(url, objectUrl);
putInMediaCache(url, blob);
return objectUrl;
});
})();
inflightRequests.set(url, promise);
}
+14 -9
View File
@@ -1,5 +1,6 @@
import { useState, useEffect } from 'react';
import { authenticatedMediaFetch } from '$utils/matrix';
import { getFromMediaCache, putInMediaCache } from '$utils/mediaCache';
const imageBlobCache = new Map<string, string>();
const inflightRequests = new Map<string, Promise<string>>();
@@ -30,18 +31,22 @@ export function useBlobCache(url?: string, accessToken?: string | null): string
}
const requestPromise = (async () => {
try {
const res = await authenticatedMediaFetch(url, accessToken);
if (!res.ok) throw new Error();
const blob = await res.blob();
const objectUrl = URL.createObjectURL(blob);
const cachedBlob = await getFromMediaCache(url);
if (cachedBlob) {
const objectUrl = URL.createObjectURL(cachedBlob);
imageBlobCache.set(url, objectUrl);
return objectUrl;
} catch (e) {
inflightRequests.delete(url);
throw e;
}
const res = await authenticatedMediaFetch(url, accessToken);
if (!res.ok) throw new Error();
const blob = await res.blob();
const objectUrl = URL.createObjectURL(blob);
imageBlobCache.set(url, objectUrl);
putInMediaCache(url, blob);
return objectUrl;
})();
inflightRequests.set(url, requestPromise);
+2 -12
View File
@@ -2,23 +2,13 @@ import { hasServiceWorker } from '$utils/platform';
import { useMatrixClient } from './useMatrixClient';
import { useAuthenticatedMediaUrl } from './useAuthenticatedMediaUrl';
/**
* Wraps a media URL for use in `<img src>`, `<video src>`, etc.
* On platforms with a service worker the URL is returned unchanged.
* On platforms without one (Android WebView) the resource is fetched with
* the user's access token and a blob: URL is returned instead.
*/
/** Wraps a media URL for `<img>` / `<video>` src. Returns a blob: URL on platforms without a SW. */
export function useMediaSrc(url: string | undefined): string | undefined {
const mx = useMatrixClient();
return useAuthenticatedMediaUrl(url, mx.getAccessToken());
}
/**
* Returns the access token that should be passed to `downloadMedia` /
* `downloadEncryptedMedia` / `authenticatedMediaFetch`. Returns `undefined`
* when a service worker handles authentication so callers don't add a
* redundant header.
*/
/** Returns the access token for media downloads, or `undefined` when a SW handles auth. */
export function useMediaDownloadToken(): string | null | undefined {
const mx = useMatrixClient();
if (hasServiceWorker()) return undefined;
@@ -102,7 +102,6 @@ export function BackgroundNotifications() {
const nicknames = useAtomValue(nicknamesAtom);
const nicknamesRef = useRef(nicknames);
nicknamesRef.current = nicknames;
// Refs so handleTimeline callbacks always read current settings without stale closures
const showNotificationsRef = useRef(showNotifications);
showNotificationsRef.current = showNotifications;
const notificationSoundRef = useRef(notificationSound);
@@ -116,7 +115,6 @@ export function BackgroundNotifications() {
const setPending = useSetAtom(pendingNotificationAtom);
const setBackgroundUnreads = useSetAtom(backgroundUnreadCountsAtom);
const setInAppBanner = useSetAtom(inAppBannerAtom);
// Stable setter refs so async handleTimeline closures never go stale.
const setBackgroundUnreadsRef = useRef(setBackgroundUnreads);
setBackgroundUnreadsRef.current = setBackgroundUnreads;
const setInAppBannerRef = useRef(setInAppBanner);
@@ -127,22 +125,13 @@ export function BackgroundNotifications() {
);
interface NotifyOptions {
/** Title shown in the notification banner. */
title: string;
/** Body text. */
body?: string;
/** URL to an icon (browser) – ignored on native where the app icon is used. */
icon?: string;
/** Badge icon URL shown by supported platforms. */
badge?: string;
/** If `true` the notification plays no sound. */
silent?: boolean;
/** Arbitrary payload attached to the notification.
* Must include { type, room_id, event_id, user_id } so the SW notificationclick
* handler can route the tap through HandleNotificationClick for account switching. */
/** Must include { type, room_id, event_id, user_id } for SW notificationclick routing. */
data?: unknown;
/** Optional callback invoked when the user clicks the notification (window.Notification
* fallback path only; the SW path routes via its own notificationclick handler). */
onClick?: () => void;
}
@@ -155,10 +144,7 @@ export function BackgroundNotifications() {
const activeIds = new Set(inactiveSessions.map((s) => s.userId));
async function sendNotification(opts: NotifyOptions): Promise<void> {
// Prefer ServiceWorkerRegistration.showNotification so that taps are handled
// by the SW notificationclick event. This routes through HandleNotificationClick
// (postMessage path) which does the account switch + deep link reliably on all
// platforms including iOS where window.Notification onclick is not fired.
// Prefer SW showNotification so taps route through the notificationclick handler.
if ('serviceWorker' in navigator && !isTauri()) {
try {
const reg = await navigator.serviceWorker.ready;
@@ -195,7 +181,6 @@ export function BackgroundNotifications() {
if (!activeIds.has(userId)) {
stopClient(mx);
current.delete(userId);
// Clear the background unread badge when this session is no longer a background account.
setBackgroundUnreads((prev) => {
const next = { ...prev };
delete next[userId];
@@ -359,7 +344,6 @@ export function BackgroundNotifications() {
const loudByRule = Boolean(pushActions.tweaks?.sound);
// Track background unread count for every notifiable event (loud or silent).
const isHighlight = Boolean(pushActions.tweaks?.highlight);
setBackgroundUnreadsRef.current((prev) => {
const cur = prev[session.userId] ?? { total: 0, highlight: 0 };
@@ -380,7 +364,6 @@ export function BackgroundNotifications() {
const isEncryptedRoom = !!getStateEvent(room, StateEvent.RoomEncryption);
notifiedEventsRef.current.add(dedupeId);
// Cap the set so it doesn't grow unbounded
if (notifiedEventsRef.current.size > 200) {
const first = notifiedEventsRef.current.values().next().value;
if (first) notifiedEventsRef.current.delete(first);
@@ -398,7 +381,6 @@ export function BackgroundNotifications() {
showMessageContent: showMessageContentRef.current,
showEncryptedMessageContent: showEncryptedMessageContentRef.current,
}),
// Play sound only if the push rule requests it and the user has sounds enabled.
silent: !notificationSoundRef.current || !loudByRule,
eventId,
data: {
@@ -411,7 +393,6 @@ export function BackgroundNotifications() {
const notifOnClick = () => {
window.focus();
// Always switch to the background account – jotai ignores no-op updates
setActiveSessionId(session.userId);
setPending({ roomId: room.roomId, eventId, targetSessionId: session.userId });
};
+3 -3
View File
@@ -637,7 +637,6 @@ function PresenceFeature() {
function UnifiedPushManager() {
const mx = useMatrixClient();
const useAuthentication = useMediaAuthentication();
const [useUP] = useSetting(settingsAtom, 'useUnifiedPush');
const [isNotificationSounds] = useSetting(settingsAtom, 'isNotificationSounds');
const [showMessageContent] = useSetting(settingsAtom, 'showMessageContentInNotifications');
@@ -645,6 +644,7 @@ function UnifiedPushManager() {
settingsAtom,
'showMessageContentInEncryptedNotifications'
);
const [useInAppNotifications] = useSetting(settingsAtom, 'useInAppNotifications');
useEffect(() => {
if (!isTauri() || !useUP) return undefined;
@@ -656,10 +656,10 @@ function UnifiedPushManager() {
await import('$features/settings/notifications/UnifiedPushNotifications');
const listener = await listenForUnifiedPushMessages(() => ({
mx,
useAuthentication,
showMessageContent,
showEncryptedMessageContent,
notificationSoundEnabled: isNotificationSounds,
useInAppNotifications,
}));
cleanup = () => listener.unregister();
})();
@@ -669,11 +669,11 @@ function UnifiedPushManager() {
};
}, [
mx,
useAuthentication,
useUP,
isNotificationSounds,
showMessageContent,
showEncryptedMessageContent,
useInAppNotifications,
]);
return null;
+26 -83
View File
@@ -1,85 +1,28 @@
/**
* Local bindings for the tauri-plugin-notifications Tauri plugin.
*
* Vendored from the guest-js of
* https://github.com/TastelessVoid/tauri-plugin-notifications (unified-push-support branch)
* because the npm package ships without built dist-js artifacts.
*
* Only the subset of APIs used by Sable is included.
*/
// Re-exports from the local tauri-plugin-notifications package (crates/tauri-plugin-notifications/).
import { invoke, type PluginListener, addPluginListener } from '@tauri-apps/api/core';
export {
sendNotification,
removeActive,
createChannel,
Importance,
Visibility,
registerForUnifiedPush,
unregisterFromUnifiedPush,
getUnifiedPushDistributors,
saveUnifiedPushDistributor,
getUnifiedPushDistributor,
onUnifiedPushEndpoint,
onUnifiedPushMessage,
onUnifiedPushUnregistered,
onUnifiedPushError,
onUnifiedPushTempUnavailable,
} from '@choochmeque/tauri-plugin-notifications-api';
export interface UnifiedPushEndpoint {
endpoint: string;
instance: string;
}
interface NotificationOptions {
id?: number;
channelId?: string;
title: string;
body?: string;
largeBody?: string;
summary?: string;
group?: string;
groupSummary?: boolean;
sound?: string;
icon?: string;
largeIcon?: string;
silent?: boolean;
ongoing?: boolean;
autoCancel?: boolean;
extra?: Record<string, unknown>;
number?: number;
}
export async function sendNotification(options: NotificationOptions | string): Promise<void> {
await invoke('plugin:notifications|notify', {
options: typeof options === 'string' ? { title: options } : options,
});
}
export async function registerForUnifiedPush(): Promise<UnifiedPushEndpoint> {
return invoke('plugin:notifications|register_for_unified_push');
}
export async function unregisterFromUnifiedPush(): Promise<void> {
return invoke('plugin:notifications|unregister_from_unified_push');
}
export async function getUnifiedPushDistributors(): Promise<{ distributors: string[] }> {
return invoke('plugin:notifications|get_unified_push_distributors');
}
export async function saveUnifiedPushDistributor(distributor: string): Promise<void> {
return invoke('plugin:notifications|save_unified_push_distributor', { distributor });
}
export async function getUnifiedPushDistributor(): Promise<{ distributor: string }> {
return invoke('plugin:notifications|get_unified_push_distributor');
}
export async function onUnifiedPushEndpoint(
cb: (data: UnifiedPushEndpoint) => void
): Promise<PluginListener> {
return addPluginListener('notifications', 'unifiedpush-endpoint', cb);
}
export async function onUnifiedPushMessage(
cb: (data: Record<string, unknown>) => void
): Promise<PluginListener> {
return addPluginListener('notifications', 'unifiedpush-message', cb);
}
export async function onUnifiedPushUnregistered(
cb: (data: { instance: string }) => void
): Promise<PluginListener> {
return addPluginListener('notifications', 'unifiedpush-unregistered', cb);
}
export async function onUnifiedPushError(
cb: (data: { message: string; instance?: string }) => void
): Promise<PluginListener> {
return addPluginListener('notifications', 'unifiedpush-error', cb);
}
export type {
UnifiedPushEndpoint,
UnifiedPushPublicKeySet,
Channel,
MessagingStylePerson,
MessagingStyleMessage,
MessagingStyleConfig,
} from '@choochmeque/tauri-plugin-notifications-api';
+51
View File
@@ -0,0 +1,51 @@
const CACHE_NAME = 'sable-media-v1';
const MAX_ENTRIES = 500;
async function openCache(): Promise<Cache | undefined> {
if (typeof caches === 'undefined') return undefined;
try {
return await caches.open(CACHE_NAME);
} catch {
return undefined;
}
}
export async function getFromMediaCache(url: string): Promise<Blob | undefined> {
const cache = await openCache();
if (!cache) return undefined;
try {
const response = await cache.match(url);
if (!response) return undefined;
return await response.blob();
} catch {
return undefined;
}
}
async function evictIfNeeded(cache: Cache): Promise<void> {
try {
const keys = await cache.keys();
const overflow = keys.length - MAX_ENTRIES;
if (overflow <= 0) return;
// Delete oldest entries (keys() returns insertion order).
await Promise.all(keys.slice(0, overflow).map((req) => cache.delete(req)));
} catch {
// Best-effort eviction.
}
}
export async function putInMediaCache(url: string, blob: Blob): Promise<void> {
const cache = await openCache();
if (!cache) return;
try {
await cache.put(
url,
new Response(blob, {
headers: { 'Content-Type': blob.type || 'application/octet-stream' },
})
);
await evictIfNeeded(cache);
} catch {
// Storage full or unavailable — silently degrade to in-memory only.
}
}
+14
View File
@@ -1,4 +1,5 @@
import { MatrixClient, ReceiptType } from '$types/matrix-sdk';
import { isTauri } from '@tauri-apps/api/core';
export async function markAsRead(mx: MatrixClient, roomId: string, privateReceipt: boolean) {
const room = mx.getRoom(roomId);
@@ -35,4 +36,17 @@ export async function markAsRead(mx: MatrixClient, roomId: string, privateReceip
latestEvent,
privateReceipt ? ReceiptType.ReadPrivate : ReceiptType.Read
);
// On Android (Tauri), dismiss the room's OS notification immediately so
// it stays in sync with the read state instead of lingering until the
// next push payload with unread: 0 arrives.
if (isTauri()) {
try {
const { clearRoomNotification } =
await import('$features/settings/notifications/UnifiedPushNotifications');
await clearRoomNotification(roomId);
} catch {
// Notification plugin not available (desktop, web) — ignore.
}
}
}
+7 -1
View File
@@ -76,11 +76,17 @@
html {
height: 100%;
overflow: hidden;
--sable-inset-top: env(safe-area-inset-top, 0px);
--sable-inset-bottom: env(safe-area-inset-bottom, 0px);
--sable-inset-left: env(safe-area-inset-left, 0px);
--sable-inset-right: env(safe-area-inset-right, 0px);
}
body {
margin: 0;
padding: 0;
padding: var(--sable-inset-top) var(--sable-inset-right) var(--sable-inset-bottom)
var(--sable-inset-left);
height: 100%;
font-family: var(--font-secondary);
font-size: 16px;