Compare commits

..
1 Commits
Author SHA1 Message Date
jaredandClaude Opus 5.5 99b0cf9c47 feat(notifications): Web Push for the web app, client side (#202)
CI / Build & Quality Checks (push) Skipped
CI / Secret scan (gitleaks) (push) Skipped
CI / Playwright smoke (e2e) (push) Skipped
CI / Secret scan (gitleaks) (pull_request) Failing after 25s
CI / Build & Quality Checks (pull_request) Successful in 5m49s
CI / Trigger Desktop Build (pull_request) Skipped
CI / Docker image build & smoke test (pull_request) Skipped
CI / Playwright smoke (e2e) (pull_request) Successful in 24m2s
Background notifications while no Lotus tab is open. Inert until
config.json lists a push gateway for the account's homeserver
(`webPush: { "<server>": { gatewayUrl, appId, vapidPublicKey } }`).

- sw.ts: `push` handler. Shows the notification unless a Lotus tab is
  focused (the in-app toast covers that), silently during pause / quiet
  hours (prefs mirrored from the page into Cache Storage), updates the
  app badge. Clicks forward the room so the page can tell DMs apart; a
  click with no tab open is held until the new window asks for it.
- swPush.ts: pure payload → notification (Sygnal webpush fields). Same
  conventions as the in-app OS notifications: logo icon, room /
  room:thread tag, invites to the invites page, calls with their own
  tag, never any text from encrypted rooms, Reply only where the
  worker can send it.
- useWebPush: subscribes this browser with the gateway's VAPID key and
  registers an HTTP pusher (pushkey = p256dh, endpoint + auth in data,
  events_only, our user_id in default_payload); removes it again when
  turned off. Never in the desktop app.
- Settings → Notifications → "Notify when Lotus is closed" (web, only
  when a gateway is configured; device-local, on by default).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PPmy3tPq869XDW4njjVaKA
2026-11-09 17:47:06 -05:00
33 changed files with 1014 additions and 1312 deletions
-3
View File
@@ -24,8 +24,5 @@
"login": "Login"
}
}
},
"nowPlaying": {
"matrix.lotusguild.org": { "url": "https://matrix.lotusguild.org/now-playing" }
}
}
@@ -7,7 +7,6 @@ import { useTauriNetwork } from '../hooks/useTauriNetwork';
import { useTauriToastActions } from '../hooks/useTauriToastActions';
import { useTauriFocusAssist } from '../hooks/useTauriFocusAssist';
import { useTauriDnd } from '../hooks/useTauriDnd';
import { useTauriOverlay } from '../hooks/useTauriOverlay';
/**
* Mounts the client-scoped native desktop feature hooks (call/room aware). Each
@@ -26,6 +25,5 @@ export function TauriDesktopFeatures(): null {
useTauriToastActions(); // P5-41/35 rich toast click → open room, quick reply → send
useTauriFocusAssist(); // P5-56 Windows Focus Assist → DND suppression atom
useTauriDnd(); // P6-1 tray "Do Not Disturb" → notification suppression atom
useTauriOverlay(); // cinny-desktop #25 in-game voice overlay
return null;
}
@@ -1,151 +0,0 @@
import React, { useEffect, useState } from 'react';
import { Box, Icon, Icons, Text, color, config, toRem } from 'folds';
import { useNowPlaying, useNowPlayingServices } from '../../hooks/useNowPlaying';
import {
NowPlayingEntry,
coverUrl,
currentPositionMs,
formatTrackTime,
} from '../../utils/nowPlaying';
/** Re-render once a second while a track is playing, for the progress bar. */
function useTicking(active: boolean): number {
const [now, setNow] = useState(() => Date.now());
useEffect(() => {
if (!active) return undefined;
const id = setInterval(() => setNow(Date.now()), 1000);
return () => clearInterval(id);
}, [active]);
return now;
}
function Cover({ entry, size }: { entry: NowPlayingEntry; size: number }) {
const services = useNowPlayingServices();
const [failed, setFailed] = useState(false);
const src = services && !failed ? coverUrl(services.api.base, entry, size * 2) : undefined;
useEffect(() => setFailed(false), [entry.cover]);
const box = {
width: toRem(size),
height: toRem(size),
borderRadius: config.radii.R300,
flexShrink: 0,
};
if (!src) {
return (
<Box
alignItems="Center"
justifyContent="Center"
style={{ ...box, background: color.SurfaceVariant.Container }}
>
<Icon size="200" src={Icons.Headphone} />
</Box>
);
}
return (
<img
src={src}
alt=""
width={size}
height={size}
loading="lazy"
referrerPolicy="no-referrer"
onError={() => setFailed(true)}
style={{ ...box, objectFit: 'cover' }}
/>
);
}
/**
* [Gitea #491] Discord-style "Listening to" card for a user profile. Renders
* nothing unless the user shares and is playing something right now.
*/
export function NowPlayingCard({ userId }: { userId: string }) {
const entry = useNowPlaying(userId);
const playing = entry?.state === 'playing';
const now = useTicking(playing);
if (!entry) return null;
const durationMs = entry.durationS * 1000;
const posMs = currentPositionMs(entry, now);
const pct = durationMs > 0 ? Math.min(100, (posMs / durationMs) * 100) : 0;
const subtitle = [entry.artist, entry.album].filter(Boolean).join(' · ');
return (
<Box
direction="Column"
gap="200"
style={{
padding: config.space.S300,
borderRadius: config.radii.R400,
background: color.SurfaceVariant.Container,
}}
aria-label={`Listening to ${entry.title}${entry.artist ? ` by ${entry.artist}` : ''}`}
>
<Text size="L400" style={{ opacity: 0.7 }}>
{playing ? 'Listening to' : 'Paused'}
</Text>
<Box gap="300" alignItems="Center">
<Cover entry={entry} size={56} />
<Box direction="Column" grow="Yes" style={{ minWidth: 0 }}>
<Text size="T300" truncate style={{ fontWeight: 600 }} title={entry.title}>
{entry.title}
</Text>
{subtitle && (
<Text size="T200" truncate style={{ opacity: 0.75 }} title={subtitle}>
{subtitle}
</Text>
)}
{entry.player && (
<Text size="T200" truncate style={{ opacity: 0.55 }}>
{entry.player}
</Text>
)}
</Box>
</Box>
{durationMs > 0 && (
<Box direction="Column" gap="100">
<div
role="progressbar"
aria-valuemin={0}
aria-valuemax={entry.durationS}
aria-valuenow={Math.floor(posMs / 1000)}
style={{
height: toRem(4),
borderRadius: toRem(2),
background: color.SurfaceVariant.ContainerLine,
overflow: 'hidden',
}}
>
<div
style={{
width: `${pct}%`,
height: '100%',
background: color.Primary.Main,
transition: 'width 1s linear',
}}
/>
</div>
<Box justifyContent="SpaceBetween">
<Text size="T200" style={{ opacity: 0.6 }}>
{formatTrackTime(posMs)}
</Text>
<Text size="T200" style={{ opacity: 0.6 }}>
{formatTrackTime(durationMs)}
</Text>
</Box>
</Box>
)}
</Box>
);
}
/** One-line "🎵 Track · Artist" for the member list. */
export function NowPlayingLine({ entry }: { entry: NowPlayingEntry }) {
const text = entry.artist ? `${entry.title} · ${entry.artist}` : entry.title;
return (
<Text size="T200" truncate style={{ opacity: 0.65 }} title={text}>
<span aria-hidden>🎵 </span>
{text}
</Text>
);
}
@@ -33,8 +33,6 @@ import { CreatorChip } from './CreatorChip';
import { getDirectCreatePath, withSearchParam } from '../../pages/pathUtils';
import { DirectCreateSearchParams } from '../../pages/paths';
import { useExtendedProfile } from '../../hooks/useExtendedProfile';
import { NowPlayingCard } from '../now-playing/NowPlaying';
import { typedStatusOf } from '../../utils/nowPlaying';
import { useUserNotes, USER_NOTE_MAX_LENGTH } from '../../hooks/useUserNotes';
type VerifyDeviceButtonProps = {
@@ -378,8 +376,7 @@ export function UserRoomProfile({ userId }: UserRoomProfileProps) {
<UserHeroName
displayName={displayName}
userId={userId}
// [Gitea #491] Automatic music text is shown by the card below.
status={typedStatusOf(presence?.status)}
status={presence?.status}
presence={presence && presence.lastActiveTs !== 0 ? presence : undefined}
pronouns={extProfile.pronouns}
timezone={extProfile.timezone}
@@ -407,7 +404,6 @@ export function UserRoomProfile({ userId }: UserRoomProfileProps) {
{userId !== myUserId && <MutualRoomsChip userId={userId} />}
{userId !== myUserId && <OptionsChip userId={userId} />}
</Box>
<NowPlayingCard userId={userId} />
</Box>
{ignored && <IgnoredUserAlert />}
{member && membership === Membership.Ban && (
+2 -2
View File
@@ -1,7 +1,7 @@
import React, { MouseEvent, ReactNode } from 'react';
import { useAtomValue } from 'jotai';
import { Text } from 'folds';
import { customChromeShownAtom } from '../../state/customWindowChrome';
import { customWindowChromeAtom } from '../../state/customWindowChrome';
import { invokeTauri, isTauri } from '../../hooks/useTauri';
import * as css from './TitleBar.css';
@@ -75,7 +75,7 @@ function ControlButton({ label, glyph, onClick, close }: ControlButtonProps) {
* real traffic lights — are stripped while custom chrome is on.
*/
export function TitleBar() {
const enabled = useAtomValue(customChromeShownAtom);
const enabled = useAtomValue(customWindowChromeAtom);
if (!isTauri() || !enabled) return null;
+2 -10
View File
@@ -38,9 +38,6 @@ import { Membership } from '../../../types/matrix/room';
import * as css from './MembersDrawer.css';
import { useMatrixClient } from '../../hooks/useMatrixClient';
import { useNowPlaying } from '../../hooks/useNowPlaying';
import { NowPlayingLine } from '../../components/now-playing/NowPlaying';
import { typedStatusOf } from '../../utils/nowPlaying';
import { UseStateProvider } from '../../components/UseStateProvider';
import {
SearchItemStrGetter,
@@ -154,9 +151,6 @@ function MemberItem({
? mx.mxcUrlToHttp(avatarMxcUrl, 100, 100, 'crop', undefined, false, useAuthentication)
: undefined;
const presence = useUserPresence(member.userId);
// [Gitea #491] What they're playing, shown when they have no typed status.
const nowPlaying = useNowPlaying(member.userId);
const typedStatus = typedStatusOf(presence?.status);
return (
<MenuItem
@@ -199,12 +193,10 @@ function MemberItem({
<Text size="T400" truncate>
{name}
</Text>
{typedStatus ? (
{presence?.status && (
<Text size="T200" truncate style={{ opacity: 0.65 }}>
{typedStatus}
{presence.status}
</Text>
) : (
nowPlaying && <NowPlayingLine entry={nowPlaying} />
)}
</Box>
</MenuItem>
+4 -79
View File
@@ -28,7 +28,6 @@ import {
PopOut,
RectCords,
Chip,
Switch,
} from 'folds';
import { Method } from 'matrix-js-sdk';
import FocusTrap from 'focus-trap-react';
@@ -70,9 +69,6 @@ import {
} from '../../../utils/statusPresets';
import { STATUS_EXPIRY_KEY, STATUS_MSG_KEY } from '../../../utils/statusKeys';
import { writeStatusExpiry } from '../../../utils/statusExpiry';
import { effectiveStatus, typedStatusOf } from '../../../utils/nowPlaying';
import { getMusicStatus, setOwnNowPlaying } from '../../../utils/nowPlayingClient';
import { useNowPlayingServices, useOwnNowPlaying } from '../../../hooks/useNowPlaying';
type ProfileProps = {
profile: UserProfile;
@@ -394,10 +390,6 @@ function getMsFromOption(value: string): number {
return parseInt(value, 10);
}
/** [Gitea #491] What to publish when the typed status is empty. */
const noTypedStatus = (presence: string, hidePresence: boolean): string =>
effectiveStatus({ typed: '', presence, hidePresence, music: getMusicStatus() });
function ProfileStatus() {
const mx = useMatrixClient();
const userId = mx.getUserId()!;
@@ -405,9 +397,7 @@ function ProfileStatus() {
const [presenceStatus] = useSetting(settingsAtom, 'presenceStatus');
const [hidePresence] = useSetting(settingsAtom, 'hidePresence');
// [Gitea #491] Automatic music text is not a typed status: read it as none.
const serverStatus =
presence?.status === DND_STATUS_SENTINEL ? undefined : typedStatusOf(presence?.status);
const serverStatus = presence?.status === DND_STATUS_SENTINEL ? undefined : presence?.status;
const initialStatus = serverStatus ?? localStorage.getItem(STATUS_MSG_KEY(userId)) ?? '';
const [statusMsg, setStatusMsg] = useState<string>(initialStatus);
// True while the user has unsaved local edits — prevents a server presence
@@ -443,7 +433,7 @@ function ProfileStatus() {
// usePresenceUpdater.setOffline), so ignore it — reading it as a clear would
// wipe the saved status on every invisible toggle.
if (presence.presence === Presence.Offline) return;
const remoteStatus = typedStatusOf(presence.status) ?? '';
const remoteStatus = presence.status ?? '';
// Only act on an actual remote change. Repeated heartbeats carrying the same
// status are ignored so they can never clobber an unsaved local edit.
if (remoteStatus === lastSyncedRemoteRef.current) return;
@@ -485,8 +475,7 @@ function ProfileStatus() {
// Derive presence from the user's chosen setting so writing a status
// never overrides Invisible/DND/Idle (e.g. outing an Invisible user).
presence: presenceStateFromSetting(presenceStatus, hidePresence),
// [Gitea #491] No typed status: the music (if shared) shows instead.
status_msg: msg || noTypedStatus(presenceStatus, hidePresence),
status_msg: msg,
}),
[mx, presenceStatus, hidePresence],
),
@@ -579,7 +568,7 @@ function ProfileStatus() {
// Preserve the user's chosen presence when clearing the status message.
queuePresenceWrite(mx, {
presence: presenceStateFromSetting(presenceStatus, hidePresence),
status_msg: noTypedStatus(presenceStatus, hidePresence),
status_msg: '',
}).catch(() => undefined);
};
@@ -810,69 +799,6 @@ const COMMON_TIMEZONES = [
'Pacific/Auckland',
];
/**
* [Gitea #491] "Share what I'm listening to": off until the user turns it on.
* Stored by the now-playing service (it decides who is shown), not in settings.
*/
function ProfileListening() {
const services = useNowPlayingServices();
const me = useOwnNowPlaying();
const [saveState, save] = useAsyncCallback(
useCallback(
async (share: boolean) => {
if (!services) return;
setOwnNowPlaying(await services.api.setShare(share));
},
[services],
),
);
if (!services) return null;
const saving = saveState.status === AsyncStatus.Loading;
let description = 'Show what you play on Navidrome or Dropped Needle to people in Lotus Chat.';
if (me && !me.linked) {
description =
'No Navidrome account matches your Lotus login, so there is nothing to share yet.';
} else if (me?.share) {
description +=
' While Lotus Chat is open, your status shows the track too, unless you have set a status yourself.';
}
return (
<SettingTile
title={
<Text as="span" size="L400">
Share what I&apos;m listening to
</Text>
}
description={
<>
{description}
{saveState.status === AsyncStatus.Error && (
<Text as="span" size="T200" style={{ color: color.Critical.Main, display: 'block' }}>
Couldn&apos;t save. Try again.
</Text>
)}
</>
}
after={
saving ? (
<Spinner size="200" variant="Secondary" />
) : (
<Switch
variant="Primary"
value={me?.share ?? false}
disabled={!me?.linked}
onChange={(v: boolean) => {
save(v).catch(() => undefined);
}}
/>
)
}
/>
);
}
function ProfilePronouns() {
const mx = useMatrixClient();
const userId = mx.getUserId()!;
@@ -1167,7 +1093,6 @@ export function Profile() {
<ProfileAvatar userId={userId} profile={profile} />
<ProfileDisplayName userId={userId} profile={profile} />
<ProfileStatus />
<ProfileListening />
<ProfilePronouns />
<ProfileTimezone />
<ProfileDecoration />
+1 -29
View File
@@ -134,7 +134,6 @@ import { playCallJoinSound } from '../../../utils/callSounds';
import { previewRingtone, RINGTONE_OPTIONS } from '../../../utils/ringtones';
import { DenoiseTester } from './DenoiseTester';
import { SettingsSelect } from '../../../components/settings-select/SettingsSelect';
import type { OverlayCorner } from '../../../utils/callOverlay';
import { isBindableCallKey } from '../../../utils/callKeybind';
import { StorageUsage } from './StorageUsage';
import { hapticsSupported } from '../../../utils/haptics';
@@ -160,7 +159,7 @@ function DesktopChromeSetting() {
<SequenceCard className={SequenceCardStyle} variant="SurfaceVariant" direction="Column">
<SettingTile
title="Custom window chrome (beta)"
description="Replace the system title bar with a Lotus-styled one. Desktop only — reloads to apply. On Linux (Wayland) it takes effect the next time Lotus Chat starts."
description="Replace the system title bar with a Lotus-styled one. Desktop only — reloads to apply."
after={<Switch variant="Primary" value={customChrome} onChange={handleToggle} />}
/>
</SequenceCard>
@@ -1895,8 +1894,6 @@ export function Calls() {
const [deafenKey, setDeafenKey] = useSetting(settingsAtom, 'deafenKey');
const [deafenHotkey, setDeafenHotkey] = useSetting(settingsAtom, 'deafenHotkey');
const [globalCallHotkeys, setGlobalCallHotkeys] = useSetting(settingsAtom, 'globalCallHotkeys');
const [callOverlay, setCallOverlay] = useSetting(settingsAtom, 'callOverlay');
const [callOverlayCorner, setCallOverlayCorner] = useSetting(settingsAtom, 'callOverlayCorner');
const [afkAutoMute, setAfkAutoMute] = useSetting(settingsAtom, 'afkAutoMute');
const [mutedTalkWarning, setMutedTalkWarning] = useSetting(settingsAtom, 'mutedTalkWarning');
const [afkTimeoutMinutes, setAfkTimeoutMinutes] = useSetting(settingsAtom, 'afkTimeoutMinutes');
@@ -2348,31 +2345,6 @@ export function Calls() {
}
/>
)}
{isTauriEnv() && (
<SettingTile
title="In-game overlay (beta)"
description="While you're in a call and another app or game is in front, show a small list of who's in the call and who's talking, plus your own mute, deafen and push-to-talk state. It never takes focus and clicks pass through it. Uses no game hooks. Windows only; games in exclusive fullscreen draw over it, so use borderless or windowed mode."
after={<Switch variant="Primary" value={callOverlay} onChange={setCallOverlay} />}
/>
)}
{isTauriEnv() && callOverlay && (
<SettingTile
title="Overlay position"
description="Which corner of the screen the overlay sits in."
after={
<SettingsSelect<OverlayCorner>
value={callOverlayCorner}
onChange={setCallOverlayCorner}
options={[
{ value: 'top-left', label: 'Top left' },
{ value: 'top-right', label: 'Top right' },
{ value: 'bottom-left', label: 'Bottom left' },
{ value: 'bottom-right', label: 'Bottom right' },
]}
/>
}
/>
)}
{hapticsSupported() && (
<SettingTile
title="Haptic feedback"
@@ -20,6 +20,8 @@ import { getNotificationState, usePermissionState } from '../../../hooks/usePerm
import { useEmailNotifications } from '../../../hooks/useEmailNotifications';
import { AsyncStatus, useAsyncCallback } from '../../../hooks/useAsyncCallback';
import { useMatrixClient } from '../../../hooks/useMatrixClient';
import { isTauri } from '../../../hooks/useTauri';
import { useWebPushConfig, webPushSupported } from '../../../hooks/useWebPush';
function EmailNotification() {
const mx = useMatrixClient();
@@ -197,6 +199,9 @@ function PauseNotifications() {
export function SystemNotification() {
const notifPermission = usePermissionState('notifications', getNotificationState());
const [showNotifications, setShowNotifications] = useSetting(settingsAtom, 'showNotifications');
const [backgroundPush, setBackgroundPush] = useSetting(settingsAtom, 'backgroundPush');
const webPushConfig = useWebPushConfig();
const showBackgroundPush = !isTauri() && webPushSupported() && webPushConfig !== undefined;
const [isNotificationSounds, setIsNotificationSounds] = useSetting(
settingsAtom,
'isNotificationSounds',
@@ -247,6 +252,19 @@ export function SystemNotification() {
)
}
/>
{showBackgroundPush && (
<SettingTile
title="Notify when Lotus is closed"
description="Keep getting notifications for new messages, mentions and calls when no Lotus tab is open, through your browser's push service. Encrypted messages are never shown in the notification. Pause and quiet hours still apply."
after={
<Switch
disabled={notifPermission !== 'granted' || !showNotifications}
value={backgroundPush}
onChange={setBackgroundPush}
/>
}
/>
)}
</SequenceCard>
<SequenceCard
className={SequenceCardStyle}
+7 -4
View File
@@ -43,11 +43,14 @@ export type ClientConfig = {
statusPages?: Record<string, unknown>;
/**
* [Gitea #491] Lotus now-playing service per homeserver, for "Listening to":
* { "<server name>": { url } } (https only). Homeservers not listed never
* contact it and show no music.
* [Gitea #202] Web Push gateway per homeserver:
* { "<server name>": { gatewayUrl, appId, vapidPublicKey } }. `gatewayUrl` is
* the push gateway's `/_matrix/push/v1/notify` URL, `appId` the Sygnal app
* id, `vapidPublicKey` that app's VAPID public key (base64url). Homeservers
* not listed never register a pusher. Web only (the desktop app notifies
* natively while running).
*/
nowPlaying?: Record<string, unknown>;
webPush?: Record<string, unknown>;
/**
* Absolute https URL of the public web app (e.g. https://chat.lotusguild.org).
-79
View File
@@ -1,79 +0,0 @@
import { useCallback, useEffect, useMemo, useSyncExternalStore } from 'react';
import { useMatrixClient } from './useMatrixClient';
import { useClientConfig } from './useClientConfig';
import { NowPlayingEntry, NowPlayingMe, nowPlayingBaseUrl } from '../utils/nowPlaying';
import {
NowPlayingApi,
getNowPlayingServices,
getOwnNowPlaying,
setOwnNowPlaying,
subscribeOwnNowPlaying,
} from '../utils/nowPlayingClient';
import type { NowPlayingStore } from '../utils/nowPlayingStore';
/** [Gitea #491] The now-playing service for this homeserver, if config.json has one. */
export function useNowPlayingServices():
| { api: NowPlayingApi; store: NowPlayingStore }
| undefined {
const mx = useMatrixClient();
const { nowPlaying } = useClientConfig();
const base = nowPlayingBaseUrl(nowPlaying, mx.getDomain() ?? undefined);
return useMemo(() => (base ? getNowPlayingServices(mx, base) : undefined), [mx, base]);
}
const noop = () => () => undefined;
/** What `userId` is playing right now, if they share it. */
export function useNowPlaying(userId: string | undefined): NowPlayingEntry | undefined {
const services = useNowPlayingServices();
const store = services?.store;
const subscribe = useCallback(
(cb: () => void) => (store && userId ? store.subscribe(userId, cb) : noop()),
[store, userId],
);
const get = useCallback(() => (store && userId ? store.get(userId) : undefined), [store, userId]);
return useSyncExternalStore(subscribe, get);
}
/** The signed-in user's own sharing state (kept fresh by NowPlayingMonitor). */
export function useOwnNowPlaying(): NowPlayingMe | undefined {
return useSyncExternalStore(subscribeOwnNowPlaying, getOwnNowPlaying);
}
const OWN_POLL_MS = 20_000;
/**
* Always mounted (ClientNonUIFeatures): polls the user's own entry so their
* status text can follow the music, including while Lotus is in the background.
*/
export function useNowPlayingMonitor(): void {
const services = useNowPlayingServices();
useEffect(() => {
if (!services) {
setOwnNowPlaying(undefined);
return undefined;
}
let stopped = false;
let timer: ReturnType<typeof setTimeout> | undefined;
let delay = OWN_POLL_MS;
const tick = async () => {
try {
const me = await services.api.me();
if (stopped) return;
setOwnNowPlaying(me);
delay = OWN_POLL_MS;
} catch {
// Keep the last state for a while, then drop the music text so a dead
// service can't leave an old track in the status.
delay = Math.min(delay * 2, 5 * 60_000);
if (delay >= 4 * OWN_POLL_MS) setOwnNowPlaying(undefined);
}
if (!stopped) timer = setTimeout(tick, delay);
};
tick();
return () => {
stopped = true;
clearTimeout(timer);
};
}, [services]);
}
+4 -21
View File
@@ -3,7 +3,6 @@ import { SetPresence } from 'matrix-js-sdk';
import { PresenceDeduper, PresenceWrite, queuePresenceWrite } from '../utils/presenceWrite';
import { useMatrixClient } from './useMatrixClient';
import { getLastLocalStatusWrite, pickHeartbeatStatus } from '../utils/ownStatusSync';
import { getMusicStatus, subscribeMusicStatus } from '../utils/nowPlayingClient';
import { useSetting } from '../state/hooks/settings';
import { settingsAtom } from '../state/settings';
import {
@@ -126,19 +125,14 @@ export function usePresenceUpdater() {
mx.setSyncPresence(presence).catch(() => undefined);
};
// [Gitea #491] With no typed status, show what's playing (if shared). Only
// the online / idle / auto paths use this; DND and Invisible never do, and
// the typed status in localStorage is never overwritten with music text.
const withMusic = (status: string) => status || getMusicStatus();
const setOnline = async () => {
syncPresence(SetPresence.Online);
const status = withMusic(await resolveStatus());
const status = await resolveStatus();
return send({ presence: 'online', ...(status ? { status_msg: status } : {}) }, 'online');
};
const setUnavailable = async (statusMsg?: string) => {
syncPresence(SetPresence.Unavailable);
const status = statusMsg ? await resolveStatus() : withMusic(await resolveStatus());
const status = await resolveStatus();
return send(
{
presence: 'unavailable',
@@ -157,18 +151,13 @@ export function usePresenceUpdater() {
setOffline();
return undefined;
}
// [Gitea #491] A new track (or the music stopping) re-sends the same state.
if (presenceStatus === 'online') {
setOnline();
return subscribeMusicStatus(() => {
setOnline();
});
return undefined;
}
if (presenceStatus === 'idle') {
setUnavailable();
return subscribeMusicStatus(() => {
setUnavailable();
});
return undefined;
}
if (presenceStatus === 'dnd') {
// [Gitea #283] Real "busy" presence where supported: the status text
@@ -255,14 +244,8 @@ export function usePresenceUpdater() {
activityEvents.forEach((e) => window.addEventListener(e, handleActivity, { passive: true }));
document.addEventListener('visibilitychange', handleVisibilityChange);
window.addEventListener('pagehide', handlePageHide);
// [Gitea #491] Keep the current auto state (away while hidden or idle).
const unsubscribeMusic = subscribeMusicStatus(() => {
if (isIdleRef.current || document.hidden) setUnavailable();
else setOnline();
});
return () => {
unsubscribeMusic();
clearTimeout(idleTimerRef.current);
activityEvents.forEach((e) => window.removeEventListener(e, handleActivity));
document.removeEventListener('visibilitychange', handleVisibilityChange);
-101
View File
@@ -1,101 +0,0 @@
import { useEffect, useMemo, useRef, useState } from 'react';
import { useAtomValue } from 'jotai';
import { callEmbedAtom } from '../state/callEmbed';
import { useCallControlState } from '../plugins/call';
import type { LotusCallParticipant } from '../plugins/call/CallEmbed';
import { useSetting } from '../state/hooks/settings';
import { settingsAtom } from '../state/settings';
import { useMatrixClient } from './useMatrixClient';
import { useCallJoined } from './useCallEmbed';
import { invokeTauri, isTauri } from './useTauri';
import { getMemberName } from '../utils/room';
import {
buildOverlaySnapshot,
inactiveOverlay,
OverlaySnapshot,
overlaySnapshotKey,
} from '../utils/callOverlay';
/** At most this often (ms) while speaking flips; the last state always lands. */
const SEND_INTERVAL_MS = 100;
/**
* [cinny-desktop #25] Feeds the desktop app's in-game voice overlay: while a
* call is joined and Settings → Calls → In-game overlay is on, sends who's in
* the call, who's speaking and your own mute / deafen / PTT state to the native
* `set_overlay_state` command. The desktop decides when to show it (Lotus not
* focused). No-op in the browser.
*/
export function useTauriOverlay(): void {
const mx = useMatrixClient();
const callEmbed = useAtomValue(callEmbedAtom);
const joined = useCallJoined(callEmbed);
const { microphone, sound } = useCallControlState(callEmbed?.control);
const [enabled] = useSetting(settingsAtom, 'callOverlay');
const [corner] = useSetting(settingsAtom, 'callOverlayCorner');
const [pttMode] = useSetting(settingsAtom, 'pttMode');
// Live per-participant state from the fork's io.lotus.call_state, only
// tracked while the overlay could show.
const [participants, setParticipants] = useState<readonly LotusCallParticipant[]>([]);
const tracking = isTauri() && enabled && joined && callEmbed !== undefined;
useEffect(() => {
if (!tracking || !callEmbed) {
setParticipants([]);
return undefined;
}
const sync = (): void => setParticipants(callEmbed.getLotusParticipants() ?? []);
sync();
return callEmbed.onLotusCallState(sync);
}, [tracking, callEmbed]);
const snapshot: OverlaySnapshot = useMemo(() => {
if (!tracking || !callEmbed) return inactiveOverlay(corner);
const { room } = callEmbed;
return buildOverlaySnapshot({
enabled,
joined,
corner,
myUserId: mx.getUserId(),
participants,
nameOf: (userId) => getMemberName(room, userId),
muted: !microphone,
deafened: !sound,
pttMode,
});
}, [tracking, callEmbed, enabled, joined, corner, mx, participants, microphone, sound, pttMode]);
// Coalesced send: skip unchanged snapshots, send at most every
// SEND_INTERVAL_MS, and always deliver the latest one.
const key = overlaySnapshotKey(snapshot);
const latest = useRef(snapshot);
latest.current = snapshot;
const sentKey = useRef<string | null>(null);
const lastSentAt = useRef(0);
const timer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);
useEffect(() => {
if (!isTauri() || key === sentKey.current) return;
const send = (): void => {
timer.current = undefined;
const s = latest.current;
sentKey.current = overlaySnapshotKey(s);
lastSentAt.current = Date.now();
invokeTauri('set_overlay_state', { state: s });
};
if (timer.current !== undefined) return;
const wait = SEND_INTERVAL_MS - (Date.now() - lastSentAt.current);
if (wait <= 0) send();
else timer.current = setTimeout(send, wait);
}, [key]);
// Hide the overlay when this unmounts (logout, client teardown).
useEffect(
() => () => {
if (timer.current !== undefined) clearTimeout(timer.current);
if (isTauri()) {
invokeTauri('set_overlay_state', { state: inactiveOverlay(latest.current.corner) });
}
},
[],
);
}
+6 -23
View File
@@ -1,7 +1,7 @@
import { useEffect } from 'react';
import { useAtomValue, useSetAtom } from 'jotai';
import { customWindowChromeAtom, nativeChromeActiveAtom } from '../state/customWindowChrome';
import { isTauri, tauriInvoke } from './useTauri';
import { useAtomValue } from 'jotai';
import { customWindowChromeAtom } from '../state/customWindowChrome';
import { invokeTauri, isTauri } from './useTauri';
/**
* P5-47 — drive the native window frame from the `customWindowChromeAtom`.
@@ -11,29 +11,12 @@ import { isTauri, tauriInvoke } from './useTauri';
* web `<TitleBar/>` can take over, `enabled = false` restores the native frame.
* No-op in the browser (`isTauri()` guard), so it's safe to call unconditionally
* from the app shell.
*
* The command answers whether the native frame is stripped *now* (on Linux /
* Wayland the frame only changes at the next launch); that drives whether the
* Lotus titlebar is shown. Older desktop builds answer nothing, so the setting
* is used as before.
*/
export function useTauriWindowChrome(): void {
const enabled = useAtomValue(customWindowChromeAtom);
const setNativeActive = useSetAtom(nativeChromeActiveAtom);
useEffect(() => {
const invoke = isTauri() ? tauriInvoke() : undefined;
if (!invoke) return undefined;
let cancelled = false;
invoke('set_custom_chrome', { enabled })
.then((active) => {
if (!cancelled) setNativeActive(typeof active === 'boolean' ? active : enabled);
})
.catch(() => {
if (!cancelled) setNativeActive(enabled);
});
return () => {
cancelled = true;
};
}, [enabled, setNativeActive]);
if (!isTauri()) return;
invokeTauri('set_custom_chrome', { enabled });
}, [enabled]);
}
+154
View File
@@ -0,0 +1,154 @@
import { useEffect, useMemo } from 'react';
import { useAtomValue } from 'jotai';
import { IPusherRequest, MatrixClient } from 'matrix-js-sdk';
import { useMatrixClient } from './useMatrixClient';
import { useClientConfig } from './useClientConfig';
import { getNotificationState, usePermissionState } from './usePermission';
import { isTauri } from './useTauri';
import { useSetting } from '../state/hooks/settings';
import { settingsAtom } from '../state/settings';
import { notificationSnoozeUntilAtom } from '../state/notificationSnooze';
import {
base64UrlToBytes,
buildHttpPusher,
parseStoredPusher,
pusherDeviceName,
sameServerKey,
subscriptionKeys,
WEB_PUSH_STORAGE_KEY,
WebPushConfig,
webPushConfigFor,
} from '../utils/webPush';
/** Browser support for Web Push (iOS: only in the installed PWA). */
export const webPushSupported = (): boolean =>
typeof window !== 'undefined' &&
'serviceWorker' in navigator &&
'PushManager' in window &&
'Notification' in window;
/** The gateway configured for the signed-in account's homeserver, if any. */
export function useWebPushConfig(): WebPushConfig | undefined {
const mx = useMatrixClient();
const { webPush } = useClientConfig();
return useMemo(() => webPushConfigFor(webPush, mx.getDomain()), [webPush, mx]);
}
const readStored = () => {
try {
return parseStoredPusher(localStorage.getItem(WEB_PUSH_STORAGE_KEY));
} catch {
return undefined;
}
};
const removePusher = (mx: MatrixClient, appId: string, pushkey: string): Promise<unknown> =>
mx
.setPusher({ kind: null, app_id: appId, pushkey } as unknown as IPusherRequest)
.catch(() => undefined);
async function register(mx: MatrixClient, config: WebPushConfig): Promise<void> {
const userId = mx.getUserId();
if (!userId) return;
const registration = await navigator.serviceWorker.ready;
let sub = await registration.pushManager.getSubscription();
if (sub && !sameServerKey(sub.options.applicationServerKey, config.vapidPublicKey)) {
await sub.unsubscribe();
sub = null;
}
if (!sub) {
sub = await registration.pushManager.subscribe({
userVisibleOnly: true,
applicationServerKey: base64UrlToBytes(config.vapidPublicKey),
});
}
const keys = subscriptionKeys(sub.toJSON());
if (!keys) return;
// A previous registration of this browser for the same account with another
// key or app id would otherwise keep receiving (and failing) pushes.
const stored = readStored();
if (
stored &&
stored.userId === userId &&
(stored.pushkey !== keys.p256dh || stored.appId !== config.appId)
) {
await removePusher(mx, stored.appId, stored.pushkey);
}
const lang = (navigator.language || 'en').split('-')[0] || 'en';
await mx.setPusher(
buildHttpPusher(
config,
keys,
userId,
pusherDeviceName(navigator.userAgent),
lang,
) as unknown as IPusherRequest,
);
localStorage.setItem(
WEB_PUSH_STORAGE_KEY,
JSON.stringify({ appId: config.appId, pushkey: keys.p256dh, userId }),
);
}
async function unregister(mx: MatrixClient): Promise<void> {
const stored = readStored();
if (!stored) return;
if (stored.userId === mx.getUserId()) await removePusher(mx, stored.appId, stored.pushkey);
localStorage.removeItem(WEB_PUSH_STORAGE_KEY);
const registration = await navigator.serviceWorker.getRegistration();
const sub = await registration?.pushManager.getSubscription();
await sub?.unsubscribe();
}
/**
* [Gitea #202] Background notifications for the web app.
*
* - Mirrors the notification prefs (desktop notifications, background push,
* pause, quiet hours) into the service worker, which shows pushes while no
* Lotus tab is open.
* - While the homeserver has a gateway configured (config.json `webPush`), push
* is supported, permission is granted and both settings are on: subscribes
* this browser and registers it as an HTTP pusher. Otherwise removes
* whatever this browser registered before.
*
* Not used in the desktop app, which notifies natively while running.
*/
export function useWebPush(): void {
const mx = useMatrixClient();
const config = useWebPushConfig();
const permission = usePermissionState('notifications', getNotificationState());
const [showNotifications] = useSetting(settingsAtom, 'showNotifications');
const [backgroundPush] = useSetting(settingsAtom, 'backgroundPush');
const [quietHoursEnabled] = useSetting(settingsAtom, 'quietHoursEnabled');
const [quietHoursStart] = useSetting(settingsAtom, 'quietHoursStart');
const [quietHoursEnd] = useSetting(settingsAtom, 'quietHoursEnd');
const snoozeUntil = useAtomValue(notificationSnoozeUntilAtom);
const active = !isTauri() && webPushSupported();
const enabled = showNotifications && backgroundPush;
useEffect(() => {
if (!active) return;
navigator.serviceWorker.ready
.then((registration) =>
registration.active?.postMessage({
type: 'setPushPrefs',
prefs: { enabled, snoozeUntil, quietHoursEnabled, quietHoursStart, quietHoursEnd },
}),
)
.catch(() => undefined);
}, [active, enabled, snoozeUntil, quietHoursEnabled, quietHoursStart, quietHoursEnd]);
const wanted = active && !!config && permission === 'granted' && enabled;
useEffect(() => {
if (!active) return;
const run = wanted && config ? register(mx, config) : unregister(mx);
run.catch((e) => {
// Push service unreachable, permission revoked meanwhile, etc. The app
// still notifies while open; nothing to surface beyond the console.
console.warn('[web push]', e);
});
}, [active, wanted, config, mx]);
}
+2 -2
View File
@@ -31,7 +31,7 @@ import { useSessionAppeared } from '../hooks/useSessionAppeared';
import { useTauriWindowChrome } from '../hooks/useTauriWindowChrome';
import { isTauri } from '../hooks/useTauri';
import { TitleBar } from '../features/desktop/TitleBar';
import { customChromeShownAtom } from '../state/customWindowChrome';
import { customWindowChromeAtom } from '../state/customWindowChrome';
import { SeasonalEffect } from '../components/seasonal/SeasonalEffect';
import { applyCustomAccent, removeCustomAccent } from '../utils/accentColor';
import { zIndices } from '../styles/zIndex';
@@ -110,7 +110,7 @@ function TauriEffects() {
// default, and always in the browser) this returns children unchanged, so there
// is zero layout impact for everyone else.
function DesktopChrome({ children }: { children: ReactNode }) {
const customChrome = useAtomValue(customChromeShownAtom);
const customChrome = useAtomValue(customWindowChromeAtom);
useTauriWindowChrome();
const useChrome = isTauri() && customChrome;
// Keep the wrapper element structure STABLE across the toggle so flipping the
+35 -19
View File
@@ -57,9 +57,6 @@ import { useSelectedRoom } from '../../hooks/router/useSelectedRoom';
import { useInboxNotificationsSelected } from '../../hooks/router/useInbox';
import { useMediaAuthentication } from '../../hooks/useMediaAuthentication';
import { presenceStateFromSetting, usePresenceUpdater } from '../../hooks/usePresenceUpdater';
import { useNowPlayingMonitor } from '../../hooks/useNowPlaying';
import { effectiveStatus } from '../../utils/nowPlaying';
import { getMusicStatus } from '../../utils/nowPlayingClient';
import {
MAX_MUTE_TIMEOUT_MS,
loadMuteTimers,
@@ -82,6 +79,7 @@ import { useTauriUpdateProgress, useTauriUpdater } from '../../hooks/useTauriUpd
import { settingsRequestAtom } from '../../state/settingsRequest';
import { isNetworkUpdateError } from '../../utils/updateErrors';
import { invokeTauri, isTauri as isTauriApp, useTauriEvent } from '../../hooks/useTauri';
import { useWebPush } from '../../hooks/useWebPush';
import { CloseBehaviorPrompt } from '../../components/CloseBehaviorPrompt';
import { ConsentRequiredPrompt } from '../../components/ConsentRequiredPrompt';
import { TauriDesktopFeatures } from '../../components/TauriDesktopFeatures';
@@ -367,8 +365,6 @@ function InviteNotifications() {
function PresenceUpdater() {
usePresenceUpdater();
// [Gitea #491] Own "Listening to" state, so the status can follow the music.
useNowPlayingMonitor();
return null;
}
@@ -446,13 +442,7 @@ function StatusExpiryMonitor() {
clearing = true;
setPresenceWithRetry(mx, {
presence: presenceStateFromSetting(presenceStatusRef.current, hidePresenceRef.current),
// [Gitea #491] With the typed status gone, the music (if any) shows.
status_msg: effectiveStatus({
typed: '',
presence: presenceStatusRef.current,
hidePresence: hidePresenceRef.current,
music: getMusicStatus(),
}),
status_msg: '',
})
.then(() => {
noteLocalStatusWrite();
@@ -625,17 +615,36 @@ function MessageNotifications() {
if (!('serviceWorker' in navigator)) return undefined;
const onMessage = (event: MessageEvent) => {
const data = event.data ?? {};
if (data.type === 'notificationClick' && typeof data.path === 'string') {
// On desktop, raise the native window — a service-worker/WebView2
// `client.focus()` only focuses the document, not the OS window. No-op
// outside Tauri.
invokeTauri('focus_main_window');
navigate(data.path);
if (data.type !== 'notificationClick') return;
// [Gitea #202] Push notifications name the room, not a path: only the page
// knows whether it's a DM.
let path: string | undefined;
if (typeof data.path === 'string') path = data.path;
else if (typeof data.roomId === 'string') {
const eventId = typeof data.eventId === 'string' ? data.eventId : undefined;
path = mDirects.has(data.roomId)
? getDirectRoomPath(data.roomId, eventId)
: getHomeRoomPath(data.roomId, eventId);
}
if (!path) return;
// On desktop, raise the native window — a service-worker/WebView2
// `client.focus()` only focuses the document, not the OS window. No-op
// outside Tauri.
invokeTauri('focus_main_window');
navigate(path);
};
navigator.serviceWorker.addEventListener('message', onMessage);
return () => navigator.serviceWorker.removeEventListener('message', onMessage);
}, [navigate]);
}, [navigate, mDirects]);
// [Gitea #202] A notification clicked while no tab was open opened this one;
// ask the worker where it was meant to go (it holds the target for a minute).
useEffect(() => {
if (!('serviceWorker' in navigator)) return;
navigator.serviceWorker.ready
.then((registration) => registration.active?.postMessage({ type: 'getPendingClick' }))
.catch(() => undefined);
}, []);
const playSound = useCallback(() => {
const audioElement = audioRef.current;
@@ -821,6 +830,12 @@ type ClientNonUIFeaturesProps = {
children: ReactNode;
};
// [Gitea #202] Web Push registration + prefs for the service worker (web only).
function WebPushFeature() {
useWebPush();
return null;
}
function DeepLinkNavigator() {
useDeepLinkNavigate();
return null;
@@ -1176,6 +1191,7 @@ export function ClientNonUIFeatures({ children }: ClientNonUIFeaturesProps) {
<StatusExpiryMonitor />
<InviteNotifications />
<MessageNotifications />
<WebPushFeature />
<ReminderMonitor />
<RetentionSweeper />
<TauriUpdateFeature />
-18
View File
@@ -1,4 +1,3 @@
import { atom } from 'jotai';
import {
atomWithLocalStorage,
getLocalStorageItem,
@@ -21,20 +20,3 @@ export const customWindowChromeAtom = atomWithLocalStorage<boolean>(
(key) => getLocalStorageItem<boolean>(key, false),
(key, value) => setLocalStorageItem(key, value),
);
/**
* [cinny-desktop: Linux custom chrome] Whether the native frame is **actually**
* stripped right now, as reported by the desktop's `set_custom_chrome`. It can
* differ from the setting: on Linux / Wayland the frame only changes when the
* app restarts. `null` until the desktop has answered (or on desktop builds
* that don't report it).
*/
export const nativeChromeActiveAtom = atom<boolean | null>(null);
/**
* Show the Lotus titlebar only when the native frame is really gone (never two
* titlebars, never none): the desktop's report, else the setting.
*/
export const customChromeShownAtom = atom<boolean>(
(get) => get(nativeChromeActiveAtom) ?? get(customWindowChromeAtom),
);
+4 -10
View File
@@ -1,6 +1,5 @@
import { atom } from 'jotai';
import { isSupportedTargetLang } from '../utils/translation/langUtils';
import type { OverlayCorner } from '../utils/callOverlay';
const STORAGE_KEY = 'settings';
export type DateFormat =
@@ -224,6 +223,9 @@ export interface Settings {
legacyUsernameColor: boolean;
showNotifications: boolean;
// [Gitea #202] Web only: notifications while no Lotus tab is open, via Web
// Push and the homeserver's push gateway. Device-local (per browser).
backgroundPush: boolean;
isNotificationSounds: boolean;
messageSoundId: 'notification' | 'invite' | 'call' | 'none';
inviteSoundId: 'notification' | 'invite' | 'call' | 'none';
@@ -288,12 +290,6 @@ export interface Settings {
// (a game) has focus, via a non-consuming key poll. Device-local.
globalCallHotkeys: boolean;
// [cinny-desktop #25] Desktop (Windows) only: the in-game voice overlay, a
// small always-on-top list of who's in the call and who's talking, shown
// while Lotus isn't focused. Off by default while in beta. Device-local.
callOverlay: boolean;
callOverlayCorner: OverlayCorner;
pauseAnimations: boolean;
composerToolbarButtons: ComposerToolbarSettings;
@@ -363,6 +359,7 @@ const defaultSettings: Settings = {
legacyUsernameColor: false,
showNotifications: true,
backgroundPush: true,
isNotificationSounds: true,
messageSoundId: 'notification',
inviteSoundId: 'invite',
@@ -420,9 +417,6 @@ const defaultSettings: Settings = {
globalCallHotkeys: true,
callOverlay: false,
callOverlayCorner: 'top-left',
pauseAnimations: false,
composerToolbarButtons: DEFAULT_COMPOSER_TOOLBAR,
-124
View File
@@ -1,124 +0,0 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { buildOverlaySnapshot, inactiveOverlay, OverlayInput } from './callOverlay';
const names: Record<string, string> = { '@me:x': 'Me', '@a:x': 'Alice', '@b:x': 'Bob' };
const base = (over: Partial<OverlayInput> = {}): OverlayInput => ({
enabled: true,
joined: true,
corner: 'top-left',
myUserId: '@me:x',
participants: [
{ userId: '@me:x', speaking: false, audioEnabled: true },
{ userId: '@a:x', speaking: true, audioEnabled: true },
{ userId: '@b:x', speaking: false, audioEnabled: false },
],
nameOf: (id) => names[id] ?? id,
muted: false,
deafened: false,
pttMode: false,
...over,
});
test('inactive when the setting is off or there is no joined call', () => {
assert.deepEqual(buildOverlaySnapshot(base({ enabled: false })), inactiveOverlay('top-left'));
assert.deepEqual(
buildOverlaySnapshot(base({ joined: false, corner: 'bottom-right' })),
inactiveOverlay('bottom-right'),
);
});
test('everyone is listed, you first, speakers and muted people marked', () => {
const s = buildOverlaySnapshot(base());
assert.equal(s.active, true);
assert.deepEqual(
s.people.map((p) => [p.name, p.speaking, p.muted, p.isSelf]),
[
['Me', false, false, true],
['Alice', true, false, false],
['Bob', false, true, false],
],
);
});
test('you are listed first even when the fork reports you later', () => {
const s = buildOverlaySnapshot(
base({
participants: [
{ userId: '@a:x', speaking: false, audioEnabled: true },
{ userId: '@me:x', speaking: true, audioEnabled: true },
],
}),
);
assert.deepEqual(
s.people.map((p) => p.userId),
['@me:x', '@a:x'],
);
assert.equal(s.people[0].speaking, true);
});
test('several devices of one person become one row', () => {
const s = buildOverlaySnapshot(
base({
participants: [
{ userId: '@a:x', speaking: false, audioEnabled: false },
{ userId: '@a:x', speaking: true, audioEnabled: true },
{ userId: '@b:x', speaking: false, audioEnabled: false },
{ userId: '@b:x', speaking: false, audioEnabled: false },
],
}),
);
const alice = s.people.find((p) => p.userId === '@a:x');
const bob = s.people.find((p) => p.userId === '@b:x');
assert.equal(s.people.filter((p) => p.userId === '@a:x').length, 1);
assert.deepEqual([alice?.speaking, alice?.muted], [true, false]);
assert.deepEqual([bob?.speaking, bob?.muted], [false, true]);
});
test('your own mute and deafen state', () => {
const muted = buildOverlaySnapshot(base({ muted: true }));
assert.equal(muted.muted, true);
assert.equal(muted.people[0].muted, true);
const deaf = buildOverlaySnapshot(
base({
deafened: true,
participants: [{ userId: '@me:x', speaking: true, audioEnabled: true }],
}),
);
assert.equal(deaf.deafened, true);
assert.equal(deaf.people[0].muted, true);
assert.equal(deaf.people[0].speaking, false);
});
test('push-to-talk: not shown as muted while the key is up', () => {
const s = buildOverlaySnapshot(base({ pttMode: true, muted: true }));
assert.equal(s.ptt, true);
assert.equal(s.muted, false);
assert.equal(s.people[0].muted, false);
});
test('you are still listed before the fork reports you', () => {
const s = buildOverlaySnapshot(base({ participants: [] }));
assert.deepEqual(
s.people.map((p) => [p.name, p.isSelf]),
[['Me', true]],
);
});
test('non-user ids from the fork are ignored', () => {
const s = buildOverlaySnapshot(
base({
myUserId: null,
participants: [
{ userId: 'screen:1', speaking: true, audioEnabled: true },
{ userId: '@a:x', speaking: false, audioEnabled: true },
],
}),
);
assert.deepEqual(
s.people.map((p) => p.userId),
['@a:x'],
);
});
-121
View File
@@ -1,121 +0,0 @@
/**
* [cinny-desktop #25] In-game voice overlay: the call snapshot the desktop app
* draws in its always-on-top overlay window. Pure, so it can be tested without
* a call; `useTauriOverlay` feeds it live state and sends the result to the
* native `set_overlay_state` command.
*/
export type OverlayCorner = 'top-left' | 'top-right' | 'bottom-left' | 'bottom-right';
export const OVERLAY_CORNERS: readonly OverlayCorner[] = [
'top-left',
'top-right',
'bottom-left',
'bottom-right',
];
export type OverlayPerson = {
userId: string;
name: string;
speaking: boolean;
muted: boolean;
isSelf: boolean;
};
/** Mirrors `OverlayState` in cinny-desktop `src-tauri/src/native/overlay.rs`. */
export type OverlaySnapshot = {
active: boolean;
corner: OverlayCorner;
muted: boolean;
deafened: boolean;
ptt: boolean;
people: OverlayPerson[];
};
/** The subset of an `io.lotus.call_state` participant the overlay needs. */
export type OverlayParticipant = {
userId: string;
speaking: boolean;
audioEnabled: boolean;
};
export type OverlayInput = {
/** Settings → Calls → In-game overlay. */
enabled: boolean;
/** In a joined call. */
joined: boolean;
corner: OverlayCorner;
myUserId: string | null;
/** Per device, in the fork's order (stable while people stay). */
participants: readonly OverlayParticipant[];
nameOf: (userId: string) => string;
/** Own mic is off (`microphone === false`). */
muted: boolean;
/** Own call audio is off (`sound === false`). */
deafened: boolean;
pttMode: boolean;
};
export const inactiveOverlay = (corner: OverlayCorner): OverlaySnapshot => ({
active: false,
corner,
muted: false,
deafened: false,
ptt: false,
people: [],
});
/**
* Build the snapshot: everyone in the call (you first, then everyone else in
* call order), one row per person even with several devices (speaking if any
* device is, muted only if every device is), and your own mute / deafen / PTT
* state for the header.
*
* In push-to-talk mode the mic is "off" whenever the key isn't held, so you
* are not shown as Muted then: the header says PTT, and your row lights up
* while you transmit.
*/
export function buildOverlaySnapshot(input: OverlayInput): OverlaySnapshot {
const { corner } = input;
if (!input.enabled || !input.joined) return inactiveOverlay(corner);
const byUser = new Map<string, { speaking: boolean; muted: boolean }>();
input.participants.forEach((p) => {
if (!p.userId.startsWith('@')) return;
const prev = byUser.get(p.userId);
byUser.set(p.userId, {
speaking: (prev?.speaking ?? false) || p.speaking,
muted: (prev?.muted ?? true) && !p.audioEnabled,
});
});
const selfMuted = input.pttMode ? false : input.muted;
const people: OverlayPerson[] = [];
const me = input.myUserId;
if (me) {
const mine = byUser.get(me);
people.push({
userId: me,
name: input.nameOf(me),
speaking: (mine?.speaking ?? false) && !selfMuted && !input.deafened,
muted: selfMuted || input.deafened,
isSelf: true,
});
}
byUser.forEach((state, userId) => {
if (userId === me) return;
people.push({ userId, name: input.nameOf(userId), ...state, isSelf: false });
});
return {
active: true,
corner,
muted: selfMuted,
deafened: input.deafened,
ptt: input.pttMode,
people,
};
}
/** Key for skipping sends when nothing visible changed. */
export const overlaySnapshotKey = (s: OverlaySnapshot): string => JSON.stringify(s);
-110
View File
@@ -1,110 +0,0 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import {
NOW_PLAYING_PREFIX,
NOW_PLAYING_STATUS_MAX,
NowPlayingEntry,
coverUrl,
currentPositionMs,
effectiveStatus,
formatNowPlayingStatus,
formatTrackTime,
isNowPlayingStatus,
musicStatusFor,
nowPlayingBaseUrl,
typedStatusOf,
} from './nowPlaying';
const entry = (over: Partial<NowPlayingEntry> = {}): NowPlayingEntry => ({
title: 'Animals',
artist: 'Maroon 5',
album: 'V',
durationS: 230,
positionMs: 10_000,
state: 'playing',
player: 'DN',
cover: '/now-playing/v1/cover/al-1',
updatedAt: 1_000_000,
...over,
});
test('formats artist and title behind the music marker', () => {
assert.equal(formatNowPlayingStatus(entry()), `${NOW_PLAYING_PREFIX}Maroon 5 – Animals`);
assert.equal(formatNowPlayingStatus(entry({ artist: ' ' })), `${NOW_PLAYING_PREFIX}Animals`);
});
test('truncates long text by characters, not UTF-16 units', () => {
const s = formatNowPlayingStatus(entry({ title: '🎸'.repeat(200) }));
assert.equal(Array.from(s).length, NOW_PLAYING_STATUS_MAX);
assert.ok(s.endsWith('…'));
});
test('only the automatic marker counts as music text', () => {
assert.ok(isNowPlayingStatus(formatNowPlayingStatus(entry())));
assert.equal(isNowPlayingStatus('🎵 my vibe'), false); // typed with a normal space
assert.equal(isNowPlayingStatus(''), false);
assert.equal(isNowPlayingStatus(undefined), false);
assert.equal(typedStatusOf(formatNowPlayingStatus(entry())), '');
assert.equal(typedStatusOf('studying'), 'studying');
assert.equal(typedStatusOf(undefined), undefined);
});
test('music status needs sharing, a playing track and a title', () => {
const playing = entry();
assert.equal(musicStatusFor(undefined), '');
assert.equal(musicStatusFor({ share: false, linked: true, playing }), '');
assert.equal(musicStatusFor({ share: true, linked: true, playing: null }), '');
assert.equal(
musicStatusFor({ share: true, linked: true, playing: entry({ state: 'paused' }) }),
'',
);
assert.equal(musicStatusFor({ share: true, linked: true, playing: entry({ title: ' ' }) }), '');
assert.equal(
musicStatusFor({ share: true, linked: true, playing }),
formatNowPlayingStatus(playing),
);
});
test('a typed status, DND and invisible always win over music', () => {
const music = formatNowPlayingStatus(entry());
const base = { typed: '', presence: 'auto', hidePresence: false, music };
assert.equal(effectiveStatus(base), music);
assert.equal(effectiveStatus({ ...base, presence: 'online' }), music);
assert.equal(effectiveStatus({ ...base, presence: 'idle' }), music);
assert.equal(effectiveStatus({ ...base, typed: 'studying' }), 'studying');
assert.equal(effectiveStatus({ ...base, presence: 'dnd' }), '');
assert.equal(effectiveStatus({ ...base, presence: 'dnd', typed: 'busy!' }), 'busy!');
assert.equal(effectiveStatus({ ...base, presence: 'invisible', typed: 'x' }), '');
assert.equal(effectiveStatus({ ...base, hidePresence: true }), '');
assert.equal(effectiveStatus({ ...base, music: '' }), '');
});
test('position extrapolates while playing and is capped at the duration', () => {
assert.equal(currentPositionMs(entry(), 1_005_000), 15_000);
assert.equal(currentPositionMs(entry({ state: 'paused' }), 1_005_000), 10_000);
assert.equal(currentPositionMs(entry(), 9_000_000), 230_000);
assert.equal(currentPositionMs(entry(), 900_000), 10_000);
assert.equal(formatTrackTime(65_400), '1:05');
assert.equal(formatTrackTime(-5), '0:00');
});
test('base URL comes from config, https only', () => {
const cfg = { 'matrix.lotusguild.org': { url: 'https://matrix.lotusguild.org/now-playing/' } };
assert.equal(
nowPlayingBaseUrl(cfg, 'matrix.lotusguild.org'),
'https://matrix.lotusguild.org/now-playing',
);
assert.equal(nowPlayingBaseUrl(cfg, 'other.org'), undefined);
assert.equal(nowPlayingBaseUrl({ x: { url: 'http://insecure' } }, 'x'), undefined);
assert.equal(nowPlayingBaseUrl({ x: { url: 'not a url' } }, 'x'), undefined);
assert.equal(nowPlayingBaseUrl(undefined, 'x'), undefined);
});
test('cover URL resolves the service path against the base origin', () => {
const base = 'https://matrix.lotusguild.org/now-playing';
assert.equal(
coverUrl(base, entry(), 128),
'https://matrix.lotusguild.org/now-playing/v1/cover/al-1?size=128',
);
assert.equal(coverUrl(base, entry({ cover: null }), 128), undefined);
});
-128
View File
@@ -1,128 +0,0 @@
/**
* [Gitea #491] "Listening to": what someone is playing on Navidrome (including
* through Dropped Needle), served by the Lotus now-playing service.
*
* Status text: while a listener's Lotus Chat is open and they share, their
* Matrix status shows the track so other Matrix clients see it too. A status
* they typed always wins, and so do Do Not Disturb and Invisible: the music
* text is only ever written when they have no status of their own. Because of
* that, music text on the server means "no typed status", and every device
* reads it that way.
*/
export type NowPlayingEntry = {
title: string;
artist: string;
album: string;
durationS: number;
positionMs: number;
state: 'playing' | 'paused';
player: string;
/** Path on the service (e.g. "/now-playing/v1/cover/al-1"), or null. */
cover: string | null;
/** When the service produced this entry (ms since epoch). */
updatedAt: number;
};
export type NowPlayingMe = {
share: boolean;
/** A Navidrome account matches this Matrix user. */
linked: boolean;
playing: NowPlayingEntry | null;
};
/**
* Music note + THIN SPACE (U+2009). Looks like "🎵 " but nobody types a thin
* space, so a status someone wrote themselves that starts with 🎵 is never
* mistaken for the automatic one.
*/
export const NOW_PLAYING_PREFIX = `${String.fromCodePoint(0x1f3b5)}${String.fromCharCode(0x2009)}`;
export const NOW_PLAYING_STATUS_MAX = 120;
const truncate = (text: string, max: number): string => {
const chars = Array.from(text);
return chars.length <= max ? text : `${chars.slice(0, max - 1).join('')}…`;
};
/** "🎵 Artist – Track" (or just the track), at most NOW_PLAYING_STATUS_MAX characters. */
export function formatNowPlayingStatus(entry: Pick<NowPlayingEntry, 'title' | 'artist'>): string {
const title = entry.title.trim();
const artist = entry.artist.trim();
const body = artist ? `${artist} – ${title}` : title;
return truncate(`${NOW_PLAYING_PREFIX}${body}`, NOW_PLAYING_STATUS_MAX);
}
export const isNowPlayingStatus = (status: string | undefined | null): boolean =>
!!status && status.startsWith(NOW_PLAYING_PREFIX);
/** The user's own typed status, with automatic music text read as "none". */
export const typedStatusOf = (status: string | undefined): string | undefined =>
isNowPlayingStatus(status) ? '' : status;
/** The music text this user's own Lotus Chat may put in their status, or ''. */
export function musicStatusFor(me: NowPlayingMe | undefined): string {
const playing = me?.share ? me.playing : null;
if (!playing || playing.state !== 'playing' || !playing.title.trim()) return '';
return formatNowPlayingStatus(playing);
}
/**
* Status text to publish. A typed status wins; DND and Invisible never show
* music. `presence` is the user's presence setting
* ('auto' | 'online' | 'idle' | 'dnd' | 'invisible').
*/
export function effectiveStatus({
typed,
presence,
hidePresence,
music,
}: {
typed: string;
presence: string;
hidePresence: boolean;
music: string;
}): string {
if (hidePresence || presence === 'invisible') return '';
if (typed) return typed;
if (presence === 'dnd') return '';
return music;
}
/** Playback position now, extrapolated from the last report while playing. */
export function currentPositionMs(entry: NowPlayingEntry, now: number = Date.now()): number {
const durationMs = entry.durationS * 1000;
const elapsed = entry.state === 'playing' ? Math.max(0, now - entry.updatedAt) : 0;
const pos = entry.positionMs + elapsed;
return durationMs > 0 ? Math.min(pos, durationMs) : pos;
}
export const formatTrackTime = (ms: number): string => {
const total = Math.max(0, Math.floor(ms / 1000));
return `${Math.floor(total / 60)}:${String(total % 60).padStart(2, '0')}`;
};
/** The service base URL for this homeserver from config.json, if any (https only). */
export function nowPlayingBaseUrl(
config: unknown,
serverName: string | undefined,
): string | undefined {
if (!serverName || !config || typeof config !== 'object') return undefined;
const entry = (config as Record<string, unknown>)[serverName];
const url = entry && typeof entry === 'object' ? (entry as { url?: unknown }).url : undefined;
if (typeof url !== 'string') return undefined;
try {
const parsed = new URL(url);
if (parsed.protocol !== 'https:') return undefined;
return parsed.toString().replace(/\/+$/, '');
} catch {
return undefined;
}
}
/** Absolute cover URL for an entry, or undefined. */
export function coverUrl(base: string, entry: NowPlayingEntry, size: number): string | undefined {
if (!entry.cover) return undefined;
const url = new URL(entry.cover, `${base}/`);
url.searchParams.set('size', String(size));
return url.toString();
}
-125
View File
@@ -1,125 +0,0 @@
import { MatrixClient } from 'matrix-js-sdk';
import { NowPlayingEntry, NowPlayingMe, musicStatusFor } from './nowPlaying';
import { NowPlayingStore } from './nowPlayingStore';
/**
* [Gitea #491] Talks to the Lotus now-playing service. Auth is a Matrix OpenID
* token (the same kind Element Call uses), cached until shortly before it
* expires; no Matrix access token ever leaves the homeserver.
*/
export class NowPlayingApi {
private token?: { value: string; expiresAt: number };
private pendingToken?: Promise<string>;
constructor(
private readonly mx: MatrixClient,
readonly base: string,
) {}
private async getToken(force: boolean): Promise<string> {
if (!force && this.token && Date.now() < this.token.expiresAt) return this.token.value;
if (!this.pendingToken) {
this.pendingToken = this.mx
.getOpenIdToken()
.then((t) => {
const lifeMs = Math.max(60, (t.expires_in ?? 3600) - 60) * 1000;
this.token = { value: t.access_token, expiresAt: Date.now() + lifeMs };
return t.access_token;
})
.finally(() => {
this.pendingToken = undefined;
});
}
return this.pendingToken;
}
private async request<T>(path: string, init: RequestInit = {}, retried = false): Promise<T> {
const token = await this.getToken(retried);
const res = await fetch(`${this.base}${path}`, {
...init,
credentials: 'omit',
headers: {
...(init.body ? { 'Content-Type': 'application/json' } : {}),
Authorization: `Bearer ${token}`,
},
signal: init.signal ?? AbortSignal.timeout(10_000),
});
if (res.status === 401 && !retried) return this.request<T>(path, init, true);
if (!res.ok) throw new Error(`now-playing HTTP ${res.status}`);
return res.json() as Promise<T>;
}
me(): Promise<NowPlayingMe> {
return this.request<NowPlayingMe>('/v1/me');
}
setShare(share: boolean): Promise<NowPlayingMe> {
return this.request<NowPlayingMe>('/v1/me', { method: 'PUT', body: JSON.stringify({ share }) });
}
async users(ids: string[]): Promise<Record<string, NowPlayingEntry>> {
const q = encodeURIComponent(ids.join(','));
const res = await this.request<{ users?: Record<string, NowPlayingEntry> }>(
`/v1/users?ids=${q}`,
);
return res.users ?? {};
}
}
type Listener = () => void;
// --- the user's own sharing state and music status text -------------------
let ownMe: NowPlayingMe | undefined;
let ownMusicStatus = '';
const ownListeners = new Set<Listener>();
const musicListeners = new Set<Listener>();
export const getOwnNowPlaying = (): NowPlayingMe | undefined => ownMe;
/** The music text the presence heartbeat may publish, or '' (see effectiveStatus). */
export const getMusicStatus = (): string => ownMusicStatus;
export function subscribeOwnNowPlaying(listener: Listener): () => void {
ownListeners.add(listener);
return () => {
ownListeners.delete(listener);
};
}
/** Fires only when the music text changes. */
export function subscribeMusicStatus(listener: Listener): () => void {
musicListeners.add(listener);
return () => {
musicListeners.delete(listener);
};
}
export function setOwnNowPlaying(me: NowPlayingMe | undefined): void {
ownMe = me;
ownListeners.forEach((l) => l());
const music = musicStatusFor(me);
if (music !== ownMusicStatus) {
ownMusicStatus = music;
musicListeners.forEach((l) => l());
}
}
// --- one API + store per (homeserver user, service URL) -------------------
let current: { key: string; api: NowPlayingApi; store: NowPlayingStore } | undefined;
export function getNowPlayingServices(
mx: MatrixClient,
base: string,
): { api: NowPlayingApi; store: NowPlayingStore } {
const key = `${mx.getUserId()}|${base}`;
if (!current || current.key !== key) {
current?.store.dispose();
const api = new NowPlayingApi(mx, base);
current = { key, api, store: new NowPlayingStore(api) };
setOwnNowPlaying(undefined);
}
return current;
}
-99
View File
@@ -1,99 +0,0 @@
import { NowPlayingEntry } from './nowPlaying';
import type { NowPlayingApi } from './nowPlayingClient';
const POLL_MS = 20_000;
const MAX_BACKOFF_MS = 5 * 60_000;
const BATCH = 50;
type Listener = () => void;
/**
* [Gitea #491] Other people's tracks. Components subscribe per user; every poll fetches all
* subscribed users in batched requests. Polls only while the page is visible.
*/
export class NowPlayingStore {
private readonly refs = new Map<string, number>();
private readonly data = new Map<string, NowPlayingEntry>();
private readonly listeners = new Map<string, Set<Listener>>();
private timer?: ReturnType<typeof setTimeout>;
private delay = POLL_MS;
private inFlight = false;
constructor(private readonly api: NowPlayingApi) {
document.addEventListener('visibilitychange', this.onVisibility);
}
get(userId: string): NowPlayingEntry | undefined {
return this.data.get(userId);
}
subscribe(userId: string, listener: Listener): () => void {
const set = this.listeners.get(userId) ?? new Set();
set.add(listener);
this.listeners.set(userId, set);
const isNew = !this.refs.has(userId);
this.refs.set(userId, (this.refs.get(userId) ?? 0) + 1);
if (isNew) this.schedule(150);
return () => {
set.delete(listener);
const n = (this.refs.get(userId) ?? 1) - 1;
if (n <= 0) {
this.refs.delete(userId);
this.listeners.delete(userId);
} else this.refs.set(userId, n);
};
}
private onVisibility = () => {
if (document.visibilityState === 'visible') this.schedule(0);
};
private schedule(ms: number) {
clearTimeout(this.timer);
this.timer = setTimeout(() => {
this.poll();
}, ms);
}
private async poll() {
if (this.inFlight) return;
if (document.visibilityState !== 'visible' || this.refs.size === 0) {
if (this.refs.size > 0) this.schedule(POLL_MS);
return;
}
this.inFlight = true;
const ids = [...this.refs.keys()];
try {
const results: Record<string, NowPlayingEntry> = {};
for (let i = 0; i < ids.length; i += BATCH) {
// eslint-disable-next-line no-await-in-loop
Object.assign(results, await this.api.users(ids.slice(i, i + BATCH)));
}
ids.forEach((id) => {
const next = results[id];
const prev = this.data.get(id);
if (next) this.data.set(id, next);
else this.data.delete(id);
if (JSON.stringify(prev) !== JSON.stringify(next)) {
this.listeners.get(id)?.forEach((l) => l());
}
});
this.delay = POLL_MS;
} catch {
this.delay = Math.min(this.delay * 2, MAX_BACKOFF_MS);
} finally {
this.inFlight = false;
this.schedule(this.delay);
}
}
dispose() {
clearTimeout(this.timer);
document.removeEventListener('visibilitychange', this.onVisibility);
}
}
-38
View File
@@ -1,7 +1,6 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { LOCAL_WRITE_GRACE_MS, pickHeartbeatStatus } from './ownStatusSync';
import { NOW_PLAYING_PREFIX } from './nowPlaying';
const now = 1_000_000;
const old = { lastLocalWriteAt: 0, now };
@@ -80,40 +79,3 @@ test('pickHeartbeatStatus: the "dnd" sentinel is never adopted as the user statu
'new',
);
});
test('[Gitea #491] music text on the server is never adopted as a typed status', () => {
const music = `${NOW_PLAYING_PREFIX}Maroon 5 – Animals`;
// Music is only published with no typed status, so it reads as "none" —
// including when another device has since cleared the typed status.
assert.equal(
pickHeartbeatStatus({ ...old, local: '', server: { presence: 'online', status_msg: music } }),
'',
);
assert.equal(
pickHeartbeatStatus({
...old,
local: 'cleared elsewhere',
server: { presence: 'online', status_msg: music },
}),
'',
);
// A fresh local save still wins over a server read showing the old music.
assert.equal(
pickHeartbeatStatus({
local: 'studying',
server: { presence: 'online', status_msg: music },
lastLocalWriteAt: now - 1000,
now,
}),
'studying',
);
// A status the user typed that merely starts with 🎵 is theirs.
assert.equal(
pickHeartbeatStatus({
...old,
local: '',
server: { presence: 'online', status_msg: '🎵 vibes' },
}),
'🎵 vibes',
);
});
-5
View File
@@ -9,8 +9,6 @@
* overridden by a server read that hasn't caught up yet.
*/
import { isNowPlayingStatus } from './nowPlaying';
/** The status_msg Lotus sends for Do Not Disturb (see usePresenceUpdater). */
export const DND_STATUS_SENTINEL = 'dnd';
@@ -49,8 +47,5 @@ export const pickHeartbeatStatus = ({
if (!server || server.presence === 'offline') return mine;
if (now - writtenAt < LOCAL_WRITE_GRACE_MS) return mine;
if (server.status_msg === DND_STATUS_SENTINEL) return mine;
// [Gitea #491] Music text is only ever published when the user has no typed
// status, so on the server it means "no typed status": never adopt it.
if (isNowPlayingStatus(server.status_msg)) return '';
return server.status_msg ?? '';
};
+1 -2
View File
@@ -28,8 +28,7 @@ export type SyncedSettingsContent = {
export const DEVICE_LOCAL_KEYS: ReadonlySet<keyof Settings> = new Set<keyof Settings>([
'settingsSync',
'globalCallHotkeys',
'callOverlay',
'callOverlayCorner',
'backgroundPush',
'pageZoom',
'mediaAutoLoad',
'pauseAnimations',
+128
View File
@@ -0,0 +1,128 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import {
base64UrlToBytes,
buildHttpPusher,
bytesToBase64Url,
parseStoredPusher,
pusherDeviceName,
sameServerKey,
subscriptionKeys,
webPushConfigFor,
} from './webPush';
// A real-shaped VAPID public key (65-byte uncompressed P-256 point, base64url).
const VAPID =
'BEl62iUYgUivxIkv69yViEuiBIa-Ib9-SkvMeAtA3LFgDzkrxZJjSgSnfckjBJuBkr3qBUYIHBQFLXYp5Nksh8U';
const CONFIG = {
'matrix.example.org': {
gatewayUrl: 'https://push.example.org/_matrix/push/v1/notify',
appId: 'org.example.chat.web',
vapidPublicKey: VAPID,
},
};
test('config is per homeserver and only used when well-formed', () => {
assert.deepEqual(webPushConfigFor(CONFIG, 'matrix.example.org'), CONFIG['matrix.example.org']);
assert.equal(webPushConfigFor(CONFIG, 'matrix.org'), undefined);
assert.equal(webPushConfigFor(undefined, 'matrix.example.org'), undefined);
assert.equal(webPushConfigFor(CONFIG, null), undefined);
const bad = (over: Record<string, unknown>) =>
webPushConfigFor({ s: { ...CONFIG['matrix.example.org'], ...over } }, 's');
assert.equal(bad({ gatewayUrl: 'http://push.example.org/notify' }), undefined);
assert.equal(bad({ gatewayUrl: 'not a url' }), undefined);
assert.equal(bad({ appId: '' }), undefined);
assert.equal(bad({ vapidPublicKey: 'short' }), undefined);
assert.equal(
bad({ vapidPublicKey: 'has spaces and +/= that are not base64url!!!!!!!!!!!!' }),
undefined,
);
});
test('base64url round-trips and decodes the VAPID key to 65 bytes', () => {
const bytes = base64UrlToBytes(VAPID);
assert.equal(bytes.length, 65);
assert.equal(bytes[0], 0x04);
assert.equal(bytesToBase64Url(bytes), VAPID);
assert.equal(bytesToBase64Url(bytes.buffer), VAPID);
});
test('an existing subscription is reused only with the same server key', () => {
const key = base64UrlToBytes(VAPID).buffer;
assert.equal(sameServerKey(key, VAPID), true);
assert.equal(sameServerKey(key, `${VAPID}=`), true);
assert.equal(sameServerKey(new Uint8Array([4, 1, 2]).buffer, VAPID), false);
assert.equal(sameServerKey(null, VAPID), false);
});
test('subscription keys are taken from PushSubscription.toJSON()', () => {
const json = {
endpoint: 'https://fcm.googleapis.com/fcm/send/abc',
keys: { p256dh: 'P256', auth: 'AUTH' },
};
assert.deepEqual(subscriptionKeys(json), {
endpoint: 'https://fcm.googleapis.com/fcm/send/abc',
p256dh: 'P256',
auth: 'AUTH',
});
assert.equal(subscriptionKeys({ ...json, endpoint: 'http://insecure' }), undefined);
assert.equal(subscriptionKeys({ endpoint: json.endpoint, keys: { p256dh: 'P' } }), undefined);
assert.equal(subscriptionKeys(null), undefined);
});
test('the pusher is a Sygnal webpush pusher keyed by p256dh', () => {
const pusher = buildHttpPusher(
CONFIG['matrix.example.org'],
{ endpoint: 'https://push.service/abc', p256dh: 'P256', auth: 'AUTH' },
'@me:example.org',
'Lotus Chat (Firefox on Linux)',
'en',
);
assert.deepEqual(pusher, {
kind: 'http',
app_id: 'org.example.chat.web',
pushkey: 'P256',
app_display_name: 'Lotus Chat',
device_display_name: 'Lotus Chat (Firefox on Linux)',
lang: 'en',
data: {
url: 'https://push.example.org/_matrix/push/v1/notify',
endpoint: 'https://push.service/abc',
auth: 'AUTH',
events_only: true,
default_payload: { user_id: '@me:example.org' },
},
append: true,
});
});
test('device names', () => {
assert.equal(
pusherDeviceName('Mozilla/5.0 (X11; Linux x86_64; rv:140.0) Gecko/20100101 Firefox/140.0'),
'Lotus Chat (Firefox on Linux)',
);
assert.equal(
pusherDeviceName(
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/140.0 Safari/537.36 Edg/140.0',
),
'Lotus Chat (Edge on Windows)',
);
assert.equal(
pusherDeviceName(
'Mozilla/5.0 (Linux; Android 15) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/140.0 Mobile Safari/537.36',
),
'Lotus Chat (Chrome on Android)',
);
assert.equal(pusherDeviceName(''), 'Lotus Chat (Browser)');
});
test('stored pusher parsing', () => {
assert.deepEqual(parseStoredPusher('{"appId":"a","pushkey":"k","userId":"@u:x"}'), {
appId: 'a',
pushkey: 'k',
userId: '@u:x',
});
assert.equal(parseStoredPusher(null), undefined);
assert.equal(parseStoredPusher('nope'), undefined);
assert.equal(parseStoredPusher('{"appId":"a"}'), undefined);
});
+174
View File
@@ -0,0 +1,174 @@
/**
* [Gitea #202] Web Push: pure helpers for registering this browser with the
* homeserver as an HTTP pusher that points at our push gateway (Sygnal,
* webpush kind). `useWebPush` drives them; the service worker's `push`
* handler (src/swPush.ts) shows what arrives.
*/
export type WebPushConfig = {
/** The gateway's notify URL, e.g. https://push.example.org/_matrix/push/v1/notify */
gatewayUrl: string;
/** Sygnal app id for the web client. */
appId: string;
/** That app's VAPID public key, base64url (uncompressed P-256 point). */
vapidPublicKey: string;
};
const isHttpsUrl = (v: unknown): v is string => {
if (typeof v !== 'string') return false;
try {
return new URL(v).protocol === 'https:';
} catch {
return false;
}
};
/**
* The gateway configured for this homeserver, or `undefined` (then nothing is
* registered). Malformed entries are ignored rather than half-used.
*/
export function webPushConfigFor(
webPush: Record<string, unknown> | undefined,
serverName: string | null | undefined,
): WebPushConfig | undefined {
if (!webPush || !serverName) return undefined;
const raw = webPush[serverName];
if (!raw || typeof raw !== 'object') return undefined;
const c = raw as Record<string, unknown>;
if (!isHttpsUrl(c.gatewayUrl)) return undefined;
if (typeof c.appId !== 'string' || c.appId === '') return undefined;
if (typeof c.vapidPublicKey !== 'string' || !/^[A-Za-z0-9_-]{40,}$/.test(c.vapidPublicKey)) {
return undefined;
}
return { gatewayUrl: c.gatewayUrl, appId: c.appId, vapidPublicKey: c.vapidPublicKey };
}
/** base64url (no padding) → bytes, for `applicationServerKey`. */
export function base64UrlToBytes(value: string): Uint8Array<ArrayBuffer> {
const b64 = value.replace(/-/g, '+').replace(/_/g, '/');
const padded = b64 + '='.repeat((4 - (b64.length % 4)) % 4);
const bin = atob(padded);
const out = new Uint8Array(new ArrayBuffer(bin.length));
for (let i = 0; i < bin.length; i += 1) out[i] = bin.charCodeAt(i);
return out;
}
/** bytes → base64url (no padding). */
export function bytesToBase64Url(bytes: ArrayBuffer | Uint8Array): string {
const arr = bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes);
let bin = '';
arr.forEach((b) => {
bin += String.fromCharCode(b);
});
return btoa(bin).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
}
/** Whether an existing subscription was made with this VAPID key. */
export function sameServerKey(
subscriptionKey: ArrayBuffer | null | undefined,
vapidPublicKey: string,
): boolean {
if (!subscriptionKey) return false;
return bytesToBase64Url(subscriptionKey) === vapidPublicKey.replace(/=+$/, '');
}
export type SubscriptionKeys = { endpoint: string; p256dh: string; auth: string };
/** The parts of a `PushSubscription.toJSON()` a pusher needs, or `undefined`. */
export function subscriptionKeys(json: unknown): SubscriptionKeys | undefined {
if (!json || typeof json !== 'object') return undefined;
const j = json as { endpoint?: unknown; keys?: { p256dh?: unknown; auth?: unknown } };
if (!isHttpsUrl(j.endpoint)) return undefined;
const { p256dh, auth } = j.keys ?? {};
if (typeof p256dh !== 'string' || typeof auth !== 'string' || !p256dh || !auth) return undefined;
return { endpoint: j.endpoint, p256dh, auth };
}
export type HttpPusherRequest = {
kind: 'http';
app_id: string;
pushkey: string;
app_display_name: string;
device_display_name: string;
lang: string;
data: {
url: string;
endpoint: string;
auth: string;
/** Sygnal: skip count-only pushes (browsers want a notification per push). */
events_only: boolean;
/** Merged into every push payload: which account it's for. */
default_payload: { user_id: string };
};
append: boolean;
};
/**
* The `/pushers/set` body for a Sygnal webpush pusher: the pushkey is the
* subscription's p256dh key, the endpoint and auth secret go in `data`.
* `append` keeps the same browser registered for another account too.
*/
export function buildHttpPusher(
config: WebPushConfig,
keys: SubscriptionKeys,
userId: string,
deviceName: string,
lang: string,
): HttpPusherRequest {
return {
kind: 'http',
app_id: config.appId,
pushkey: keys.p256dh,
app_display_name: 'Lotus Chat',
device_display_name: deviceName,
lang,
data: {
url: config.gatewayUrl,
endpoint: keys.endpoint,
auth: keys.auth,
events_only: true,
default_payload: { user_id: userId },
},
append: true,
};
}
/** A short "Lotus Chat (Firefox on Linux)" style name for the pusher list. */
export function pusherDeviceName(userAgent: string): string {
const browser =
(/Edg\//.test(userAgent) && 'Edge') ||
(/Firefox\//.test(userAgent) && 'Firefox') ||
(/Chrome\//.test(userAgent) && 'Chrome') ||
(/Safari\//.test(userAgent) && 'Safari') ||
'Browser';
const os =
(/Android/.test(userAgent) && 'Android') ||
(/iPhone|iPad|iPod/.test(userAgent) && 'iOS') ||
(/Windows/.test(userAgent) && 'Windows') ||
(/Mac OS X/.test(userAgent) && 'macOS') ||
(/Linux/.test(userAgent) && 'Linux') ||
'';
return os ? `Lotus Chat (${browser} on ${os})` : `Lotus Chat (${browser})`;
}
/** What this browser registered, so it can be removed again. */
export type StoredPusher = { appId: string; pushkey: string; userId: string };
export const WEB_PUSH_STORAGE_KEY = 'lotus_web_push_pusher_v1';
export function parseStoredPusher(raw: string | null): StoredPusher | undefined {
if (!raw) return undefined;
try {
const v = JSON.parse(raw) as Partial<StoredPusher>;
if (
typeof v.appId === 'string' &&
typeof v.pushkey === 'string' &&
typeof v.userId === 'string'
) {
return { appId: v.appId, pushkey: v.pushkey, userId: v.userId };
}
} catch {
// fall through
}
return undefined;
}
+112 -2
View File
@@ -3,6 +3,16 @@
import { precacheAndRoute, type PrecacheEntry } from 'workbox-precaching';
import { isTrustedShareRequest, SHARE_TARGET_PATH, stashSharedForm } from './swShare';
import { pickReplySession, replyFailureText, sendNotificationReply } from './swReply';
import {
buildPushNotification,
isPushQuiet,
parsePushPrefs,
PENDING_CLICK_MAX_AGE_MS,
PUSH_PREFS_KEY,
PushPayload,
PushPrefs,
SW_STATE_CACHE,
} from './swPush';
export type {};
declare const self: ServiceWorkerGlobalScope & {
@@ -142,6 +152,99 @@ self.addEventListener('message', (event: ExtendableMessageEvent) => {
setSession(client.id, accessToken, baseUrl, userId);
cleanupDeadClients();
}
// [Gitea #202] The page mirrors its notification prefs here so pushes that
// arrive with no tab open still honour pause / quiet hours.
if (type === 'setPushPrefs') {
event.waitUntil(savePushPrefs(parsePushPrefs(event.data.prefs)));
}
// [Gitea #202] A window opened by a notification click asks where to go once
// its router is listening.
if (type === 'getPendingClick') {
const pending = takePendingClick();
if (pending) client.postMessage({ type: 'notificationClick', ...pending });
}
});
// ---------------------------------------------------------------------------
// [Gitea #202] Web Push
// ---------------------------------------------------------------------------
async function savePushPrefs(prefs: PushPrefs): Promise<void> {
try {
const cache = await caches.open(SW_STATE_CACHE);
await cache.put(
PUSH_PREFS_KEY,
new Response(JSON.stringify(prefs), { headers: { 'Content-Type': 'application/json' } }),
);
} catch {
// Storage unavailable: pushes fall back to the defaults.
}
}
async function loadPushPrefs(): Promise<PushPrefs> {
try {
const cache = await caches.open(SW_STATE_CACHE);
const res = await cache.match(PUSH_PREFS_KEY);
return parsePushPrefs(res ? await res.json() : undefined);
} catch {
return parsePushPrefs(undefined);
}
}
type ClickTarget = { path?: string; roomId?: string; eventId?: string };
let pendingClick: (ClickTarget & { at: number }) | undefined;
function takePendingClick(): ClickTarget | undefined {
const pending = pendingClick;
pendingClick = undefined;
if (!pending || Date.now() - pending.at > PENDING_CLICK_MAX_AGE_MS) return undefined;
const { path, roomId, eventId } = pending;
return { path, roomId, eventId };
}
async function setAppBadge(count: number | undefined): Promise<void> {
const nav = self.navigator as WorkerNavigator & {
setAppBadge?: (n?: number) => Promise<void>;
clearAppBadge?: () => Promise<void>;
};
if (typeof count !== 'number') return;
try {
if (count > 0) await nav.setAppBadge?.(count);
else await nav.clearAppBadge?.();
} catch {
// Badging unsupported or not allowed.
}
}
self.addEventListener('push', (event: PushEvent) => {
event.waitUntil(
(async () => {
let payload: PushPayload = {};
try {
payload = (event.data?.json() ?? {}) as PushPayload;
} catch {
return;
}
await setAppBadge(payload.unread);
const built = buildPushNotification(payload, self.registration.scope);
if (!built) return;
// A focused Lotus tab already shows this as an in-app toast.
const windows = await self.clients.matchAll({ type: 'window', includeUncontrolled: true });
if (windows.some((c) => (c as WindowClient).focused)) return;
const prefs = await loadPushPrefs();
if (!prefs.enabled) return;
const quiet = isPushQuiet(prefs, new Date());
await self.registration.showNotification(built.title, {
...built.options,
silent: quiet,
} as NotificationOptions);
})(),
);
});
/**
@@ -154,6 +257,10 @@ self.addEventListener('notificationclick', (event: NotificationEvent) => {
event.notification.close();
const data = event.notification.data ?? {};
const path = typeof data.path === 'string' ? data.path : undefined;
// [Gitea #202] Push notifications carry the room instead of a path: only the
// page knows whether it's a DM.
const roomId = typeof data.roomId === 'string' ? data.roomId : undefined;
const eventId = typeof data.eventId === 'string' ? data.eventId : undefined;
// [Gitea #203] Reply action: send it and stop — no need to raise the app.
if (event.action === 'reply' && typeof data.roomId === 'string') {
@@ -202,12 +309,15 @@ self.addEventListener('notificationclick', (event: NotificationEvent) => {
windowClients[0];
if (client) {
await client.focus();
if (path) client.postMessage({ type: 'notificationClick', path });
if (path || roomId)
client.postMessage({ type: 'notificationClick', path, roomId, eventId });
return;
}
// No app window open — open one at the app root (the client routes from
// there). Router config (hash vs browser) is page-owned, so we don't try
// to deep-link the URL here.
// to deep-link the URL here; the new window asks for the target
// (`getPendingClick`) once it can route.
if (path || roomId) pendingClick = { path, roomId, eventId, at: Date.now() };
if (self.clients.openWindow) {
await self.clients.openWindow(self.registration.scope);
}
+140
View File
@@ -0,0 +1,140 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import {
buildPushNotification,
DEFAULT_PUSH_PREFS,
isPushQuiet,
parsePushPrefs,
PushPayload,
} from './swPush';
const SCOPE = 'https://chat.example.org/';
const msg = (over: Partial<PushPayload> = {}): PushPayload => ({
room_id: '!r:x',
event_id: '$e',
room_name: 'General',
sender: '@a:x',
sender_display_name: 'Alice',
type: 'm.room.message',
content: { msgtype: 'm.text', body: 'hello there' },
user_id: '@me:x',
...over,
});
test('count-only pushes show nothing', () => {
assert.equal(buildPushNotification({ unread: 3 }, SCOPE), null);
assert.equal(buildPushNotification({ room_id: '!r:x', unread: 0 }, SCOPE), null);
});
test('a room message: room title, sender and text, room tag, reply action', () => {
const n = buildPushNotification(msg(), SCOPE)!;
assert.equal(n.title, 'General');
assert.equal(n.options.body, 'Alice: hello there');
assert.equal(n.options.tag, '!r:x');
assert.equal(n.options.icon, 'https://chat.example.org/public/res/lotus.png');
assert.deepEqual(n.options.data, {
roomId: '!r:x',
eventId: '$e',
threadId: undefined,
userId: '@me:x',
});
assert.equal(n.options.actions?.[0]?.action, 'reply');
});
test('a DM (no room name): sender as title, text as body', () => {
const n = buildPushNotification(msg({ room_name: undefined }), SCOPE)!;
assert.equal(n.title, 'Alice');
assert.equal(n.options.body, 'hello there');
});
test('encrypted rooms never show content and offer no reply', () => {
const n = buildPushNotification(
msg({
type: 'm.room.encrypted',
content: { algorithm: 'm.megolm.v1.aes-sha2', ciphertext: 'x' },
}),
SCOPE,
)!;
assert.equal(n.title, 'General');
assert.equal(n.options.body, 'Alice');
assert.equal(n.options.actions, undefined);
const dm = buildPushNotification(
msg({ type: 'm.room.encrypted', room_name: undefined, content: undefined }),
SCOPE,
)!;
assert.equal(dm.title, 'Alice');
assert.equal(dm.options.body, 'New message');
});
test('thread replies coalesce per thread', () => {
const n = buildPushNotification(
msg({
content: {
msgtype: 'm.text',
body: 'in thread',
'm.relates_to': { rel_type: 'm.thread', event_id: '$root' },
},
}),
SCOPE,
)!;
assert.equal(n.options.tag, '!r:x:$root');
assert.equal(n.options.data.threadId, '$root');
});
test('media messages are described, long text is cut', () => {
assert.equal(
buildPushNotification(msg({ content: { msgtype: 'm.image', body: 'cat.png' } }), SCOPE)!.options
.body,
'Alice: sent an image',
);
const long = buildPushNotification(
msg({ content: { msgtype: 'm.text', body: 'x'.repeat(500) } }),
SCOPE,
)!;
assert.equal((long.options.body ?? '').length, 120);
});
test('invites go to the invites page', () => {
const n = buildPushNotification(
msg({ type: 'm.room.member', membership: 'invite', user_is_target: true, content: undefined }),
SCOPE,
)!;
assert.equal(n.title, 'Invitation');
assert.equal(n.options.body, 'Alice invited you to General');
assert.equal(n.options.tag, 'lotus-invites');
assert.equal(n.options.data.path, '/inbox/invites/');
});
test('calls ring with their own tag and stay until handled', () => {
const n = buildPushNotification(msg({ type: 'org.matrix.msc4075.rtc.notification' }), SCOPE)!;
assert.equal(n.options.body, 'Alice started a call');
assert.equal(n.options.tag, '!r:x:call');
assert.equal(n.options.requireInteraction, true);
});
test('unknown event types still show a notification', () => {
const n = buildPushNotification(msg({ type: 'm.reaction', content: undefined }), SCOPE)!;
assert.equal(n.options.body, 'New activity');
});
test('prefs from the page are validated', () => {
assert.deepEqual(parsePushPrefs(null), DEFAULT_PUSH_PREFS);
assert.deepEqual(parsePushPrefs({ enabled: 'yes', snoozeUntil: '5', quietHoursEnabled: 1 }), {
...DEFAULT_PUSH_PREFS,
});
assert.equal(parsePushPrefs({ enabled: false }).enabled, false);
});
test('quiet when paused or inside quiet hours', () => {
const at = (h: number, m = 0): Date => new Date(2026, 10, 9, h, m);
assert.equal(isPushQuiet(DEFAULT_PUSH_PREFS, at(12)), false);
assert.equal(isPushQuiet({ ...DEFAULT_PUSH_PREFS, snoozeUntil: at(13).getTime() }, at(12)), true);
assert.equal(
isPushQuiet({ ...DEFAULT_PUSH_PREFS, snoozeUntil: at(11).getTime() }, at(12)),
false,
);
const quiet = { ...DEFAULT_PUSH_PREFS, quietHoursEnabled: true };
assert.equal(isPushQuiet(quiet, at(23)), true);
assert.equal(isPushQuiet(quiet, at(6, 30)), true);
assert.equal(isPushQuiet(quiet, at(12)), false);
});
+219
View File
@@ -0,0 +1,219 @@
/**
* [Gitea #202] Web Push: pure helpers for the service worker's `push` handler.
*
* The homeserver sends a push to our gateway (Sygnal, webpush kind), which
* relays the Matrix notification to the browser's push service, encrypted to
* this browser's subscription. Sygnal's payload is the notification's fields,
* flattened: room_id, room_name, event_id, sender, sender_display_name, type,
* content (unencrypted rooms only, size-capped), membership, user_is_target,
* unread / missed_calls, plus the pusher's `default_payload` (our user_id).
*
* Kept free of React / jotai so the service worker bundle stays small.
*/
import { isSnoozeActive } from './app/utils/snooze';
import { isWithinTimeWindow } from './app/utils/timeWindow';
export type PushPayload = {
room_id?: string;
room_name?: string;
room_alias?: string;
event_id?: string;
sender?: string;
sender_display_name?: string;
type?: string;
content?: Record<string, unknown>;
membership?: string;
user_is_target?: boolean;
unread?: number;
missed_calls?: number;
/** From the pusher's `default_payload`: the account this push is for. */
user_id?: string;
};
/** Notification preferences the page mirrors into the worker. */
export type PushPrefs = {
/** Settings → Notifications → Desktop notifications. */
enabled: boolean;
/** Pause notifications: epoch ms, `0` = not paused. */
snoozeUntil: number;
quietHoursEnabled: boolean;
quietHoursStart: string;
quietHoursEnd: string;
};
export const DEFAULT_PUSH_PREFS: PushPrefs = {
enabled: true,
snoozeUntil: 0,
quietHoursEnabled: false,
quietHoursStart: '22:00',
quietHoursEnd: '07:00',
};
/** Accept only well-formed prefs from a page message; fill the rest in. */
export function parsePushPrefs(raw: unknown): PushPrefs {
const p = (raw && typeof raw === 'object' ? raw : {}) as Record<string, unknown>;
return {
enabled: typeof p.enabled === 'boolean' ? p.enabled : DEFAULT_PUSH_PREFS.enabled,
snoozeUntil: typeof p.snoozeUntil === 'number' ? p.snoozeUntil : 0,
quietHoursEnabled: p.quietHoursEnabled === true,
quietHoursStart:
typeof p.quietHoursStart === 'string'
? p.quietHoursStart
: DEFAULT_PUSH_PREFS.quietHoursStart,
quietHoursEnd:
typeof p.quietHoursEnd === 'string' ? p.quietHoursEnd : DEFAULT_PUSH_PREFS.quietHoursEnd,
};
}
/**
* Paused or in quiet hours: the notification still has to be shown (browsers
* require a visible notification per push), but silently.
*/
export function isPushQuiet(prefs: PushPrefs, now: Date): boolean {
return (
isSnoozeActive(prefs.snoozeUntil, now.getTime()) ||
(prefs.quietHoursEnabled && isWithinTimeWindow(prefs.quietHoursStart, prefs.quietHoursEnd, now))
);
}
export type PushNotificationData = {
roomId?: string;
eventId?: string;
threadId?: string;
userId?: string;
/** Set when the target is known without the page (invites). */
path?: string;
};
export type BuiltNotification = {
title: string;
options: NotificationOptions & {
data: PushNotificationData;
actions?: { action: string; title: string; type?: 'button' | 'text'; placeholder?: string }[];
};
};
const CALL_TYPES = new Set([
'm.call.invite',
'm.rtc.notification',
'org.matrix.msc4075.rtc.notification',
'org.matrix.msc4075.call.notify',
]);
const BODY_MAX = 120;
const INVITES_PATH = '/inbox/invites/';
const str = (v: unknown): string | undefined =>
typeof v === 'string' && v.trim() !== '' ? v.trim() : undefined;
/** One-line description of a message's content; never for encrypted rooms. */
function messageText(content: Record<string, unknown> | undefined): string | undefined {
if (!content) return undefined;
switch (content.msgtype) {
case 'm.image':
return 'sent an image';
case 'm.video':
return 'sent a video';
case 'm.audio':
return 'sent an audio message';
case 'm.file':
return 'sent a file';
case 'm.location':
return 'shared a location';
default:
return str(content.body);
}
}
function threadOf(content: Record<string, unknown> | undefined): string | undefined {
const rel = content?.['m.relates_to'];
if (!rel || typeof rel !== 'object') return undefined;
const r = rel as Record<string, unknown>;
return r.rel_type === 'm.thread' ? str(r.event_id) : undefined;
}
/**
* The notification to show for a push, or `null` for a count-only push (no
* event). Mirrors the in-app OS notifications (ClientNonUIFeatures): app logo
* as icon, the room as the coalescing tag (`room:thread` for threads), no
* message text from encrypted rooms (it can't be decrypted here anyway), and
* an inline Reply action only for unencrypted rooms.
*/
export function buildPushNotification(p: PushPayload, scope: string): BuiltNotification | null {
const eventId = str(p.event_id);
const roomId = str(p.room_id);
if (!eventId || !roomId) return null;
const logo = `${scope.replace(/\/?$/, '/')}public/res/lotus.png`;
const who = str(p.sender_display_name) ?? str(p.sender) ?? 'Someone';
const room = str(p.room_name) ?? str(p.room_alias);
const userId = str(p.user_id);
const base = { icon: logo, badge: logo };
if (p.membership === 'invite' && p.user_is_target) {
return {
title: 'Invitation',
options: {
...base,
body: room ? `${who} invited you to ${room}` : `${who} invited you`,
tag: 'lotus-invites',
data: { path: INVITES_PATH, userId },
},
};
}
if (p.type && CALL_TYPES.has(p.type)) {
return {
title: room ?? who,
options: {
...base,
body: room ? `${who} started a call` : 'Incoming call',
tag: `${roomId}:call`,
requireInteraction: true,
data: { roomId, eventId, userId },
},
};
}
if (p.type === 'm.room.encrypted') {
return {
title: room ?? who,
options: {
...base,
body: room ? who : 'New message',
tag: roomId,
data: { roomId, eventId, userId },
},
};
}
if (p.type === 'm.room.message' || p.type === 'm.sticker') {
const text = p.type === 'm.sticker' ? 'sent a sticker' : messageText(p.content);
const threadId = threadOf(p.content);
let body = 'New message';
if (text) body = (room ? `${who}: ${text}` : text).slice(0, BODY_MAX);
else if (room) body = who;
return {
title: room ?? who,
options: {
...base,
body,
tag: threadId ? `${roomId}:${threadId}` : roomId,
actions: [{ action: 'reply', title: 'Reply', type: 'text', placeholder: 'Reply…' }],
data: { roomId, eventId, threadId, userId },
},
};
}
return {
title: room ?? who,
options: { ...base, body: 'New activity', tag: roomId, data: { roomId, eventId, userId } },
};
}
/** Cache Storage location where the worker keeps the page's prefs. */
export const SW_STATE_CACHE = 'lotus-sw-state-v1';
export const PUSH_PREFS_KEY = '/__lotus/push-prefs';
/** A notification click waiting for a freshly opened window to ask for it. */
export const PENDING_CLICK_MAX_AGE_MS = 60_000;