Compare commits
28
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4fe9b97eb2 | ||
|
|
2e30f9ec44 | ||
|
|
0cfca75f6f | ||
|
|
7a042cb3e7 | ||
|
|
38871d3e56 | ||
|
|
30b5a7d6af | ||
|
|
01254291e5 | ||
|
|
1b561ca1ca | ||
|
|
53cceaa66e | ||
|
|
8794465034 | ||
|
|
ace084c91c | ||
|
|
c73a3f8b31 | ||
|
|
504899aa14 | ||
|
|
7d31b2b2f7 | ||
|
|
61d2433721 | ||
|
|
78b19f1ced | ||
|
|
2f5bcf2b91 | ||
|
|
d1a9625b1c | ||
|
|
9ab01ff6f6 | ||
|
|
d2c3c56b18 | ||
|
|
e2ce177930 | ||
|
|
1ebc42863e | ||
|
|
58f7b18746 | ||
|
|
43445db5cc | ||
|
|
3c33169297 | ||
|
|
3163829c57 | ||
|
|
2264c79833 | ||
|
|
e8a04fee20 |
+5
-1
@@ -16,12 +16,16 @@
|
||||
"statusPages": {
|
||||
"matrix.lotusguild.org": {
|
||||
"url": "https://isitup.lotusguild.org",
|
||||
"slug": "matrix",
|
||||
"slug": "public",
|
||||
"noticePrefix": "Matrix:",
|
||||
"groups": {
|
||||
"homeserver": "Homeserver",
|
||||
"calls": "Voice calls",
|
||||
"login": "Login"
|
||||
}
|
||||
}
|
||||
},
|
||||
"nowPlaying": {
|
||||
"matrix.lotusguild.org": { "url": "https://matrix.lotusguild.org/now-playing" }
|
||||
}
|
||||
}
|
||||
|
||||
Generated
+4
-4
@@ -81,7 +81,7 @@
|
||||
},
|
||||
"devDependencies": {
|
||||
"@axe-core/playwright": "4.13.0",
|
||||
"@lotusguild/element-call-embedded": "0.28.0-lotus.2",
|
||||
"@lotusguild/element-call-embedded": "0.28.0-lotus.5",
|
||||
"@playwright/test": "1.63.0",
|
||||
"@rollup/plugin-inject": "5.0.5",
|
||||
"@rollup/plugin-wasm": "6.2.2",
|
||||
@@ -2695,9 +2695,9 @@
|
||||
"integrity": "sha512-dfLbk+PwWvFzSxwk3n5ySL0hfBog779o8h68wK/7/APo/7cgyWp5jcXockbxdk5kFRkbeXWm4Fbi9FrdN381sA=="
|
||||
},
|
||||
"node_modules/@lotusguild/element-call-embedded": {
|
||||
"version": "0.28.0-lotus.2",
|
||||
"resolved": "https://code.lotusguild.org/api/packages/LotusGuild/npm/%40lotusguild%2Felement-call-embedded/-/0.28.0-lotus.2/element-call-embedded-0.28.0-lotus.2.tgz",
|
||||
"integrity": "sha512-g3xaZ/i3RQ0mToWmjLi08HjSuKD3BpAllj9aEucPS8wh3Uwmz4HXa0tgF1hEN3dPrZR2BTWLQii5Mtfh4037vg==",
|
||||
"version": "0.28.0-lotus.5",
|
||||
"resolved": "https://code.lotusguild.org/api/packages/LotusGuild/npm/%40lotusguild%2Felement-call-embedded/-/0.28.0-lotus.5/element-call-embedded-0.28.0-lotus.5.tgz",
|
||||
"integrity": "sha512-yW95xjtlUv65B7JCd0dxOv2M8qdjXvMvlk4btDmobr4D+kIFWtfyOCranmzHz9KbaS3vwy3WgTgp73G8mAAO/Q==",
|
||||
"dev": true
|
||||
},
|
||||
"node_modules/@matrix-org/matrix-sdk-crypto-wasm": {
|
||||
|
||||
+1
-1
@@ -108,7 +108,7 @@
|
||||
},
|
||||
"devDependencies": {
|
||||
"@axe-core/playwright": "4.13.0",
|
||||
"@lotusguild/element-call-embedded": "0.28.0-lotus.2",
|
||||
"@lotusguild/element-call-embedded": "0.28.0-lotus.5",
|
||||
"@playwright/test": "1.63.0",
|
||||
"@rollup/plugin-inject": "5.0.5",
|
||||
"@rollup/plugin-wasm": "6.2.2",
|
||||
|
||||
@@ -60,6 +60,7 @@ import { SrOnly } from '../features/call-status/styles.css';
|
||||
import { useCallHotkeys } from '../hooks/useCallHotkeys';
|
||||
import { useAfkAutoMute } from '../hooks/useAfkAutoMute';
|
||||
import { useCallQuality } from '../hooks/useCallQuality';
|
||||
import { useCallDenoise } from '../hooks/useCallDenoise';
|
||||
import { useRemoteAllMuted } from '../hooks/useCallSpeakers';
|
||||
import { useRoomAvatar, useRoomName } from '../hooks/useRoomMeta';
|
||||
import { mDirectAtom } from '../state/mDirectList';
|
||||
@@ -836,6 +837,7 @@ function CallUtils({ embed, joined }: { embed: CallEmbed; joined: boolean }) {
|
||||
useMutedTalkWarning(embed, joined);
|
||||
useCallThemeSync(embed);
|
||||
useCallQuality(embed);
|
||||
useCallDenoise(embed);
|
||||
useCallHangupEvent(
|
||||
embed,
|
||||
useCallback(() => {
|
||||
|
||||
@@ -7,6 +7,7 @@ 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
|
||||
@@ -25,5 +26,6 @@ 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;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,109 @@
|
||||
import React from 'react';
|
||||
import { Room } from 'matrix-js-sdk';
|
||||
import { Chip, Icon, IconSrc, Text, Tooltip, TooltipProvider } from 'folds';
|
||||
import {
|
||||
BRIDGE_NETWORK_NAME,
|
||||
BridgeNetwork,
|
||||
describeRoomBridge,
|
||||
getBridgedUserNetwork,
|
||||
} from '../../utils/bridge';
|
||||
import { useRoomBridges } from '../../hooks/useRoomBridges';
|
||||
|
||||
// Discord glyph (simple-icons, 24x24 viewBox like the folds icons).
|
||||
const DiscordIcon: IconSrc = () => (
|
||||
<path
|
||||
fill="currentColor"
|
||||
d="M20.317 4.3698a19.7913 19.7913 0 00-4.8851-1.5152.0741.0741 0 00-.0785.0371c-.211.3753-.4447.8648-.6083 1.2495-1.8447-.2762-3.68-.2762-5.4868 0-.1636-.3933-.4058-.8742-.6177-1.2495a.077.077 0 00-.0785-.037 19.7363 19.7363 0 00-4.8852 1.515.0699.0699 0 00-.0321.0277C.5334 9.0458-.319 13.5799.0992 18.0578a.0824.0824 0 00.0312.0561c2.0528 1.5076 4.0413 2.4228 5.9929 3.0294a.0777.0777 0 00.0842-.0276c.4616-.6304.8731-1.2952 1.226-1.9942a.076.076 0 00-.0416-.1057c-.6528-.2476-1.2743-.5495-1.8722-.8923a.077.077 0 01-.0076-.1277c.1258-.0943.2517-.1923.3718-.2914a.0743.0743 0 01.0776-.0105c3.9278 1.7933 8.18 1.7933 12.0614 0a.0739.0739 0 01.0785.0095c.1202.099.246.1981.3728.2924a.077.077 0 01-.0066.1276 12.2986 12.2986 0 01-1.873.8914.0766.0766 0 00-.0407.1067c.3604.698.7719 1.3628 1.225 1.9932a.076.076 0 00.0842.0286c1.961-.6067 3.9495-1.5219 6.0023-3.0294a.077.077 0 00.0313-.0552c.5004-5.177-.8382-9.6739-3.5485-13.6604a.061.061 0 00-.0312-.0286zM8.02 15.3312c-1.1825 0-2.1569-1.0857-2.1569-2.419 0-1.3332.9555-2.4189 2.157-2.4189 1.2108 0 2.1757 1.0952 2.1568 2.419 0 1.3332-.9555 2.4189-2.1569 2.4189zm7.9748 0c-1.1825 0-2.1569-1.0857-2.1569-2.419 0-1.3332.9554-2.4189 2.1569-2.4189 1.2108 0 2.1757 1.0952 2.1568 2.419 0 1.3332-.946 2.4189-2.1568 2.4189Z"
|
||||
/>
|
||||
);
|
||||
|
||||
const BRIDGE_ICON: Record<BridgeNetwork, IconSrc> = {
|
||||
discord: DiscordIcon,
|
||||
};
|
||||
|
||||
const BRIDGE_COLOR: Record<BridgeNetwork, string> = {
|
||||
discord: '#5865F2',
|
||||
};
|
||||
|
||||
type UserBridgeBadgeProps = {
|
||||
userId: string;
|
||||
size?: '50' | '100' | '200';
|
||||
};
|
||||
|
||||
/** Network icon for a user who is bridged in from another chat network, else nothing. */
|
||||
export function UserBridgeBadge({ userId, size = '100' }: UserBridgeBadgeProps) {
|
||||
const network = getBridgedUserNetwork(userId);
|
||||
if (!network) return null;
|
||||
const label = `On ${BRIDGE_NETWORK_NAME[network]} (bridged)`;
|
||||
return (
|
||||
<TooltipProvider
|
||||
position="Top"
|
||||
tooltip={
|
||||
<Tooltip>
|
||||
<Text size="T200">{label}</Text>
|
||||
</Tooltip>
|
||||
}
|
||||
>
|
||||
{(ref) => (
|
||||
<span
|
||||
ref={ref}
|
||||
role="img"
|
||||
aria-label={label}
|
||||
style={{ display: 'inline-flex', alignItems: 'center', flexShrink: 0 }}
|
||||
>
|
||||
<Icon size={size} src={BRIDGE_ICON[network]} style={{ color: BRIDGE_COLOR[network] }} />
|
||||
</span>
|
||||
)}
|
||||
</TooltipProvider>
|
||||
);
|
||||
}
|
||||
|
||||
type RoomBridgeChipProps = {
|
||||
room: Room;
|
||||
};
|
||||
|
||||
/** Header chip for a room bridged to another network; links to the channel when known. */
|
||||
export function RoomBridgeChip({ room }: RoomBridgeChipProps) {
|
||||
const bridges = useRoomBridges(room);
|
||||
const bridge = bridges[0];
|
||||
if (!bridge) return null;
|
||||
const description = describeRoomBridge(bridge);
|
||||
const linkProps = bridge.externalUrl
|
||||
? { as: 'a' as const, href: bridge.externalUrl, target: '_blank', rel: 'noreferrer noopener' }
|
||||
: {};
|
||||
return (
|
||||
<TooltipProvider
|
||||
position="Bottom"
|
||||
offset={4}
|
||||
tooltip={
|
||||
<Tooltip>
|
||||
<Text>
|
||||
{bridge.externalUrl
|
||||
? `${description}. Open in ${BRIDGE_NETWORK_NAME[bridge.network]}.`
|
||||
: description}
|
||||
</Text>
|
||||
</Tooltip>
|
||||
}
|
||||
>
|
||||
{(triggerRef) => (
|
||||
<Chip
|
||||
ref={triggerRef}
|
||||
size="400"
|
||||
variant="Secondary"
|
||||
radii="300"
|
||||
aria-label={description}
|
||||
before={
|
||||
<Icon
|
||||
size="50"
|
||||
src={BRIDGE_ICON[bridge.network]}
|
||||
style={{ color: BRIDGE_COLOR[bridge.network] }}
|
||||
/>
|
||||
}
|
||||
{...linkProps}
|
||||
>
|
||||
<Text size="T200">{BRIDGE_NETWORK_NAME[bridge.network]}</Text>
|
||||
</Chip>
|
||||
)}
|
||||
</TooltipProvider>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
export * from './BridgeBadge';
|
||||
@@ -0,0 +1,151 @@
|
||||
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>
|
||||
);
|
||||
}
|
||||
@@ -27,6 +27,7 @@ import { stopPropagation } from '../../utils/keyboard';
|
||||
import { useSetting } from '../../state/hooks/settings';
|
||||
import { settingsAtom } from '../../state/settings';
|
||||
import { useLocalTime } from '../../hooks/useLocalTime';
|
||||
import { UserBridgeBadge } from '../bridge';
|
||||
|
||||
type UserHeroProps = {
|
||||
userId: string;
|
||||
@@ -143,6 +144,7 @@ export function UserHeroName({
|
||||
>
|
||||
{displayName ?? username ?? userId}
|
||||
</Text>
|
||||
<UserBridgeBadge userId={userId} size="200" />
|
||||
</Box>
|
||||
{pronouns && (
|
||||
<Box alignItems="Center" gap="100" style={{ marginTop: '1px', overflow: 'hidden' }}>
|
||||
|
||||
@@ -33,6 +33,8 @@ 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 = {
|
||||
@@ -376,7 +378,8 @@ export function UserRoomProfile({ userId }: UserRoomProfileProps) {
|
||||
<UserHeroName
|
||||
displayName={displayName}
|
||||
userId={userId}
|
||||
status={presence?.status}
|
||||
// [Gitea #491] Automatic music text is shown by the card below.
|
||||
status={typedStatusOf(presence?.status)}
|
||||
presence={presence && presence.lastActiveTs !== 0 ? presence : undefined}
|
||||
pronouns={extProfile.pronouns}
|
||||
timezone={extProfile.timezone}
|
||||
@@ -404,6 +407,7 @@ 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 && (
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import React, { MouseEvent, ReactNode } from 'react';
|
||||
import { useAtomValue } from 'jotai';
|
||||
import { Text } from 'folds';
|
||||
import { customWindowChromeAtom } from '../../state/customWindowChrome';
|
||||
import { customChromeShownAtom } 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(customWindowChromeAtom);
|
||||
const enabled = useAtomValue(customChromeShownAtom);
|
||||
|
||||
if (!isTauri() || !enabled) return null;
|
||||
|
||||
|
||||
@@ -38,6 +38,9 @@ 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,
|
||||
@@ -71,6 +74,7 @@ import { useFlattenPowerTagMembers, useGetMemberPowerTag } from '../../hooks/use
|
||||
import { useRoomCreators } from '../../hooks/useRoomCreators';
|
||||
import { useCrossSigningActive } from '../../hooks/useCrossSigning';
|
||||
import { MemberVerificationBadge } from '../../components/MemberVerificationBadge';
|
||||
import { UserBridgeBadge } from '../../components/bridge';
|
||||
import { useUserPresence } from '../../hooks/useUserPresence';
|
||||
import { PresenceBadge, PresenceRingAvatar } from '../../components/presence';
|
||||
import { AvatarDecoration } from '../../components/avatar-decoration/AvatarDecoration';
|
||||
@@ -150,6 +154,9 @@ 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
|
||||
@@ -178,6 +185,7 @@ function MemberItem({
|
||||
{presence && (
|
||||
<PresenceBadge presence={presence.presence} status={presence.status} size="300" />
|
||||
)}
|
||||
<UserBridgeBadge userId={member.userId} />
|
||||
{showEncryption && <MemberVerificationBadge userId={member.userId} />}
|
||||
{typing && (
|
||||
<Badge size="300" variant="Secondary" fill="Soft" radii="Pill" outlined>
|
||||
@@ -191,10 +199,12 @@ function MemberItem({
|
||||
<Text size="T400" truncate>
|
||||
{name}
|
||||
</Text>
|
||||
{presence?.status && (
|
||||
{typedStatus ? (
|
||||
<Text size="T200" truncate style={{ opacity: 0.65 }}>
|
||||
{presence.status}
|
||||
{typedStatus}
|
||||
</Text>
|
||||
) : (
|
||||
nowPlaying && <NowPlayingLine entry={nowPlaying} />
|
||||
)}
|
||||
</Box>
|
||||
</MenuItem>
|
||||
|
||||
@@ -34,6 +34,7 @@ import { PageHeader } from '../../components/page';
|
||||
import { RoomAvatar, RoomIcon } from '../../components/room-avatar';
|
||||
import { UseStateProvider } from '../../components/UseStateProvider';
|
||||
import { RoomTopicViewer } from '../../components/room-topic-viewer';
|
||||
import { RoomBridgeChip } from '../../components/bridge';
|
||||
import { StateEvent } from '../../../types/matrix/room';
|
||||
import { useMatrixClient } from '../../hooks/useMatrixClient';
|
||||
import { useIsDirectRoom, useRoom } from '../../hooks/useRoom';
|
||||
@@ -690,6 +691,7 @@ export function RoomViewHeader({ callView }: { callView?: boolean }) {
|
||||
)}
|
||||
</TooltipProvider>
|
||||
)}
|
||||
<RoomBridgeChip room={room} />
|
||||
</Box>
|
||||
{topic && (
|
||||
<UseStateProvider initial={false}>
|
||||
|
||||
@@ -90,6 +90,7 @@ import { useMediaAuthentication } from '../../../hooks/useMediaAuthentication';
|
||||
import { useRoomPinnedEvents } from '../../../hooks/useRoomPinnedEvents';
|
||||
import { MemberPowerTag, StateEvent } from '../../../../types/matrix/room';
|
||||
import { PowerIcon } from '../../../components/power';
|
||||
import { UserBridgeBadge } from '../../../components/bridge';
|
||||
import colorMXID from '../../../../util/colorMXID';
|
||||
import { getPowerTagIconSrc } from '../../../hooks/useMemberPowerTag';
|
||||
import { ForwardMessageDialog } from './ForwardMessageDialog';
|
||||
@@ -1084,6 +1085,7 @@ export const Message = React.memo(
|
||||
</Text>
|
||||
</Username>
|
||||
{tagIconSrc && <PowerIcon size="100" iconSrc={tagIconSrc} />}
|
||||
<UserBridgeBadge userId={senderId} />
|
||||
</Box>
|
||||
<Box shrink="No" gap="100">
|
||||
{messageLayout === MessageLayout.Modern && hover && (
|
||||
|
||||
@@ -28,6 +28,7 @@ import {
|
||||
PopOut,
|
||||
RectCords,
|
||||
Chip,
|
||||
Switch,
|
||||
} from 'folds';
|
||||
import { Method } from 'matrix-js-sdk';
|
||||
import FocusTrap from 'focus-trap-react';
|
||||
@@ -69,6 +70,9 @@ 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;
|
||||
@@ -390,6 +394,10 @@ 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()!;
|
||||
@@ -397,7 +405,9 @@ function ProfileStatus() {
|
||||
const [presenceStatus] = useSetting(settingsAtom, 'presenceStatus');
|
||||
const [hidePresence] = useSetting(settingsAtom, 'hidePresence');
|
||||
|
||||
const serverStatus = presence?.status === DND_STATUS_SENTINEL ? undefined : presence?.status;
|
||||
// [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 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
|
||||
@@ -433,7 +443,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 = presence.status ?? '';
|
||||
const remoteStatus = typedStatusOf(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;
|
||||
@@ -475,7 +485,8 @@ 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),
|
||||
status_msg: msg,
|
||||
// [Gitea #491] No typed status: the music (if shared) shows instead.
|
||||
status_msg: msg || noTypedStatus(presenceStatus, hidePresence),
|
||||
}),
|
||||
[mx, presenceStatus, hidePresence],
|
||||
),
|
||||
@@ -568,7 +579,7 @@ function ProfileStatus() {
|
||||
// Preserve the user's chosen presence when clearing the status message.
|
||||
queuePresenceWrite(mx, {
|
||||
presence: presenceStateFromSetting(presenceStatus, hidePresence),
|
||||
status_msg: '',
|
||||
status_msg: noTypedStatus(presenceStatus, hidePresence),
|
||||
}).catch(() => undefined);
|
||||
};
|
||||
|
||||
@@ -799,6 +810,69 @@ 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'm listening to
|
||||
</Text>
|
||||
}
|
||||
description={
|
||||
<>
|
||||
{description}
|
||||
{saveState.status === AsyncStatus.Error && (
|
||||
<Text as="span" size="T200" style={{ color: color.Critical.Main, display: 'block' }}>
|
||||
Couldn'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()!;
|
||||
@@ -1093,6 +1167,7 @@ export function Profile() {
|
||||
<ProfileAvatar userId={userId} profile={profile} />
|
||||
<ProfileDisplayName userId={userId} profile={profile} />
|
||||
<ProfileStatus />
|
||||
<ProfileListening />
|
||||
<ProfilePronouns />
|
||||
<ProfileTimezone />
|
||||
<ProfileDecoration />
|
||||
|
||||
@@ -6,6 +6,7 @@ import {
|
||||
DenoiseNode,
|
||||
buildGateNode,
|
||||
buildModelNode,
|
||||
monoDownmix,
|
||||
readDb,
|
||||
sampleRateFor,
|
||||
} from '../../../utils/denoisePipeline';
|
||||
@@ -139,7 +140,7 @@ export function DenoiseTester({ model, useGate, gateThreshold, nativeNS }: Denoi
|
||||
inAnalyser.fftSize = 1024;
|
||||
source.connect(inAnalyser);
|
||||
|
||||
let head: AudioNode = source;
|
||||
let head: AudioNode = source.connect(monoDownmix(ctx));
|
||||
let gate: AudioWorkletNode | null = null;
|
||||
if (useGate) {
|
||||
gate = await buildGateNode(ctx, gateThreshold);
|
||||
@@ -308,10 +309,11 @@ export function DenoiseTester({ model, useGate, gateThreshold, nativeNS }: Denoi
|
||||
const ctx = new AudioContext({ sampleRate: sampleRateFor(playModel ?? 'rnnoise') });
|
||||
const source = ctx.createBufferSource();
|
||||
source.buffer = clip;
|
||||
const mono = source.connect(monoDownmix(ctx));
|
||||
let playGate: AudioWorkletNode | null = null;
|
||||
let playModelNode: DenoiseNode | null = null;
|
||||
if (playModel) {
|
||||
let head: AudioNode = source;
|
||||
let head: AudioNode = mono;
|
||||
if (useGate) {
|
||||
playGate = await buildGateNode(ctx, gateThreshold);
|
||||
head.connect(playGate);
|
||||
@@ -321,7 +323,7 @@ export function DenoiseTester({ model, useGate, gateThreshold, nativeNS }: Denoi
|
||||
head.connect(playModelNode.node);
|
||||
playModelNode.node.connect(ctx.destination);
|
||||
} else {
|
||||
source.connect(ctx.destination);
|
||||
mono.connect(ctx.destination);
|
||||
}
|
||||
// Superseded while the WASM/worklet loaded (another Play, a Stop, or the
|
||||
// panel unmounted)? Tear down this now-orphaned graph instead of storing
|
||||
|
||||
@@ -134,6 +134,7 @@ 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';
|
||||
@@ -159,7 +160,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."
|
||||
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."
|
||||
after={<Switch variant="Primary" value={customChrome} onChange={handleToggle} />}
|
||||
/>
|
||||
</SequenceCard>
|
||||
@@ -1894,6 +1895,8 @@ 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');
|
||||
@@ -2037,7 +2040,7 @@ export function Calls() {
|
||||
<Text size="L400">Model</Text>
|
||||
<SettingTile
|
||||
title="ML model"
|
||||
description="Choose the machine learning model used for noise removal. Heavier models clean more aggressively at a higher CPU cost."
|
||||
description="Choose the machine learning model used for noise removal. DTLN is the best all-rounder; DeepFilterNet removes the most noise at a higher CPU cost. None of the models remove other people talking in the background. CPU figures are the share of one processor core during a call on a mid-range desktop; Task Manager shows that divided by your number of cores, and slower computers use more."
|
||||
after={
|
||||
<SettingsSelect<DenoiseModelId>
|
||||
value={callDenoiseModel}
|
||||
@@ -2064,9 +2067,9 @@ export function Calls() {
|
||||
<Box direction="Row" gap="400" wrap="Wrap">
|
||||
{(
|
||||
[
|
||||
{ label: 'CPU', value: selectedDenoiseModel.cpuUsage },
|
||||
{ label: 'CPU (one core)', value: selectedDenoiseModel.cpuUsage },
|
||||
{ label: 'Voice quality', value: selectedDenoiseModel.voiceQuality },
|
||||
{ label: 'Transients', value: selectedDenoiseModel.transients },
|
||||
{ label: 'Typing & clicks', value: selectedDenoiseModel.transients },
|
||||
{ label: 'Download', value: selectedDenoiseModel.binarySize },
|
||||
] as const
|
||||
).map((stat) => (
|
||||
@@ -2113,7 +2116,7 @@ export function Calls() {
|
||||
</Box>
|
||||
<Box grow="Yes">
|
||||
<Text size="T200" priority="300">
|
||||
Transients
|
||||
Typing & clicks
|
||||
</Text>
|
||||
</Box>
|
||||
</Box>
|
||||
@@ -2137,7 +2140,7 @@ export function Calls() {
|
||||
</details>
|
||||
|
||||
<Text size="T200" priority="400">
|
||||
Note: Applying changes requires rejoining the call.
|
||||
Changes apply straight away, even during a call.
|
||||
</Text>
|
||||
</Box>
|
||||
|
||||
@@ -2345,6 +2348,31 @@ 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"
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
import { useEffect } from 'react';
|
||||
import { useAtomValue } from 'jotai';
|
||||
import { CallEmbed } from '../plugins/call';
|
||||
import { settingsAtom } from '../state/settings';
|
||||
import { buildDenoisePayload } from '../utils/callDenoise';
|
||||
|
||||
/**
|
||||
* Apply noise-suppression setting changes to a call that's already running
|
||||
* (the fork's `io.lotus.set_denoise`): switching between off, browser-native
|
||||
* and an ML model, or between models, takes effect without rejoining. The join
|
||||
* itself still carries the settings in the call URL, so the first send is a
|
||||
* no-op fork-side.
|
||||
*/
|
||||
export function useCallDenoise(embed: CallEmbed): void {
|
||||
const {
|
||||
callNoiseSuppression,
|
||||
callDenoiseModel,
|
||||
callDenoiseNativeNS,
|
||||
callDenoiseGate,
|
||||
callDenoiseGateThreshold,
|
||||
} = useAtomValue(settingsAtom);
|
||||
|
||||
useEffect(() => {
|
||||
embed.control.setDenoise(
|
||||
buildDenoisePayload({
|
||||
callNoiseSuppression,
|
||||
callDenoiseModel,
|
||||
callDenoiseNativeNS,
|
||||
callDenoiseGate,
|
||||
callDenoiseGateThreshold,
|
||||
}),
|
||||
);
|
||||
}, [
|
||||
embed,
|
||||
callNoiseSuppression,
|
||||
callDenoiseModel,
|
||||
callDenoiseNativeNS,
|
||||
callDenoiseGate,
|
||||
callDenoiseGateThreshold,
|
||||
]);
|
||||
}
|
||||
@@ -42,6 +42,13 @@ 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.
|
||||
*/
|
||||
nowPlaying?: Record<string, unknown>;
|
||||
|
||||
/**
|
||||
* Absolute https URL of the public web app (e.g. https://chat.lotusguild.org).
|
||||
* The desktop app sets it so it can hand calls it can't make to the browser.
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
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]);
|
||||
}
|
||||
@@ -3,6 +3,7 @@ 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 {
|
||||
@@ -125,14 +126,19 @@ 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 = await resolveStatus();
|
||||
const status = withMusic(await resolveStatus());
|
||||
return send({ presence: 'online', ...(status ? { status_msg: status } : {}) }, 'online');
|
||||
};
|
||||
const setUnavailable = async (statusMsg?: string) => {
|
||||
syncPresence(SetPresence.Unavailable);
|
||||
const status = await resolveStatus();
|
||||
const status = statusMsg ? await resolveStatus() : withMusic(await resolveStatus());
|
||||
return send(
|
||||
{
|
||||
presence: 'unavailable',
|
||||
@@ -151,13 +157,18 @@ 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 undefined;
|
||||
return subscribeMusicStatus(() => {
|
||||
setOnline();
|
||||
});
|
||||
}
|
||||
if (presenceStatus === 'idle') {
|
||||
setUnavailable();
|
||||
return undefined;
|
||||
return subscribeMusicStatus(() => {
|
||||
setUnavailable();
|
||||
});
|
||||
}
|
||||
if (presenceStatus === 'dnd') {
|
||||
// [Gitea #283] Real "busy" presence where supported: the status text
|
||||
@@ -244,8 +255,14 @@ 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);
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
import { Room } from 'matrix-js-sdk';
|
||||
import { useCallback, useMemo } from 'react';
|
||||
import { useStateEventCallback } from './useStateEventCallback';
|
||||
import { useForceUpdate } from './useForceUpdate';
|
||||
import { getRoomBridges, RoomBridgeInfo } from '../utils/bridge';
|
||||
import { StateEvent } from '../../types/matrix/room';
|
||||
|
||||
export const useRoomBridges = (room: Room): RoomBridgeInfo[] => {
|
||||
const [updateCount, forceUpdate] = useForceUpdate();
|
||||
|
||||
useStateEventCallback(
|
||||
room.client,
|
||||
useCallback(
|
||||
(event) => {
|
||||
const type = event.getType();
|
||||
if (
|
||||
event.getRoomId() === room.roomId &&
|
||||
(type === StateEvent.Bridge || type === StateEvent.BridgeUnstable)
|
||||
) {
|
||||
forceUpdate();
|
||||
}
|
||||
},
|
||||
[room, forceUpdate],
|
||||
),
|
||||
);
|
||||
|
||||
return useMemo(
|
||||
() => getRoomBridges(room),
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
[room, updateCount],
|
||||
);
|
||||
};
|
||||
@@ -62,7 +62,7 @@ export const useServerStatus = (
|
||||
]);
|
||||
if (stopped) return;
|
||||
failures = 0;
|
||||
last = parseKumaStatus(pageJson, heartbeatJson, page!.groups);
|
||||
last = parseKumaStatus(pageJson, heartbeatJson, page!.groups, page!.noticePrefix);
|
||||
setStatus(last);
|
||||
// While this client's connection is lost, keep asking every minute: that
|
||||
// is how it learns Kuma has checked the server since the drop.
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
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) });
|
||||
}
|
||||
},
|
||||
[],
|
||||
);
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
import { useEffect } from 'react';
|
||||
import { useAtomValue } from 'jotai';
|
||||
import { customWindowChromeAtom } from '../state/customWindowChrome';
|
||||
import { invokeTauri, isTauri } from './useTauri';
|
||||
import { useAtomValue, useSetAtom } from 'jotai';
|
||||
import { customWindowChromeAtom, nativeChromeActiveAtom } from '../state/customWindowChrome';
|
||||
import { isTauri, tauriInvoke } from './useTauri';
|
||||
|
||||
/**
|
||||
* P5-47 — drive the native window frame from the `customWindowChromeAtom`.
|
||||
@@ -11,12 +11,29 @@ import { invokeTauri, isTauri } 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(() => {
|
||||
if (!isTauri()) return;
|
||||
invokeTauri('set_custom_chrome', { enabled });
|
||||
}, [enabled]);
|
||||
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]);
|
||||
}
|
||||
|
||||
@@ -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 { customWindowChromeAtom } from '../state/customWindowChrome';
|
||||
import { customChromeShownAtom } 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(customWindowChromeAtom);
|
||||
const customChrome = useAtomValue(customChromeShownAtom);
|
||||
useTauriWindowChrome();
|
||||
const useChrome = isTauri() && customChrome;
|
||||
// Keep the wrapper element structure STABLE across the toggle so flipping the
|
||||
|
||||
@@ -57,6 +57,9 @@ 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,
|
||||
@@ -364,6 +367,8 @@ function InviteNotifications() {
|
||||
|
||||
function PresenceUpdater() {
|
||||
usePresenceUpdater();
|
||||
// [Gitea #491] Own "Listening to" state, so the status can follow the music.
|
||||
useNowPlayingMonitor();
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -441,7 +446,13 @@ function StatusExpiryMonitor() {
|
||||
clearing = true;
|
||||
setPresenceWithRetry(mx, {
|
||||
presence: presenceStateFromSetting(presenceStatusRef.current, hidePresenceRef.current),
|
||||
status_msg: '',
|
||||
// [Gitea #491] With the typed status gone, the music (if any) shows.
|
||||
status_msg: effectiveStatus({
|
||||
typed: '',
|
||||
presence: presenceStatusRef.current,
|
||||
hidePresence: hidePresenceRef.current,
|
||||
music: getMusicStatus(),
|
||||
}),
|
||||
})
|
||||
.then(() => {
|
||||
noteLocalStatusWrite();
|
||||
|
||||
@@ -4,6 +4,7 @@ import { CallControlState } from './CallControlState';
|
||||
import { ElementMediaStateDetail, ElementMediaStatePayload, ElementWidgetActions } from './types';
|
||||
import { canDelegateCapability } from './utils';
|
||||
import { CallErrorState, parseCallError } from './callError';
|
||||
import type { LotusDenoisePayload } from '../../utils/callDenoise';
|
||||
|
||||
export enum CallControlEvent {
|
||||
StateUpdate = 'state_update',
|
||||
@@ -106,6 +107,11 @@ export class CallControl extends EventEmitter implements CallControlState {
|
||||
// pre-join send pends to a 10s widget timeout, mirroring the deafen gate).
|
||||
private lastQuality: LotusQualityPayload | null = null;
|
||||
|
||||
// Last noise-suppression choice (io.lotus.set_denoise), held like
|
||||
// lastQuality: sent once joined and re-sent after an EC reconnect, whose
|
||||
// remounted handler starts again from the settings in the join URL.
|
||||
private lastDenoise: LotusDenoisePayload | null = null;
|
||||
|
||||
// C-M5: set true by CallControls while a push-to-talk key is held. A PTT hold
|
||||
// unmutes the mic transiently, and onMediaState() must NOT treat that as a
|
||||
// user-initiated unmute that auto-undeafens the user.
|
||||
@@ -191,6 +197,7 @@ export class CallControl extends EventEmitter implements CallControlState {
|
||||
this.joined = true;
|
||||
this.sendDeafenState();
|
||||
this.sendQuality();
|
||||
this.sendDenoise();
|
||||
this.sendHotkeyCodes();
|
||||
this.sendFrameScreenshareAllowed();
|
||||
}
|
||||
@@ -204,6 +211,7 @@ export class CallControl extends EventEmitter implements CallControlState {
|
||||
public resendForkState(): void {
|
||||
this.sendDeafenState();
|
||||
this.sendQuality();
|
||||
this.sendDenoise();
|
||||
if (this._audioOutputId !== undefined) this.sendAudioOutput(this._audioOutputId);
|
||||
// [Gitea #17] The pin lives fork-side and is dropped on a handler remount.
|
||||
if (this._focusedUserId !== null) this.sendFocus(this._focusedUserId, this._focusedMediaId);
|
||||
@@ -762,6 +770,21 @@ export class CallControl extends EventEmitter implements CallControlState {
|
||||
this.call.transport.send('io.lotus.set_quality', this.lastQuality).catch(() => undefined);
|
||||
}
|
||||
|
||||
/**
|
||||
* Switch noise suppression on the live mic (the fork's `io.lotus.set_denoise`):
|
||||
* browser-native on/off and/or the ML model, without rejoining. Join-gated
|
||||
* like setQuality().
|
||||
*/
|
||||
public setDenoise(payload: LotusDenoisePayload): void {
|
||||
this.lastDenoise = payload;
|
||||
this.sendDenoise();
|
||||
}
|
||||
|
||||
private sendDenoise(): void {
|
||||
if (!this.joined || !this.lastDenoise) return;
|
||||
this.call.transport.send('io.lotus.set_denoise', this.lastDenoise).catch(() => undefined);
|
||||
}
|
||||
|
||||
public dispose() {
|
||||
// [Gitea #56] Don't let a manual focus pin outlive the call.
|
||||
this.clearFocusParticipant();
|
||||
|
||||
@@ -237,10 +237,14 @@ export class CallEmbed {
|
||||
denoiseMode === 'browser' ||
|
||||
(denoiseMode === 'ml' && denoiseNativeNS)
|
||||
).toString(),
|
||||
// Turn the browser's auto gain control OFF for the ML tier only: its
|
||||
// dynamic gain fights the in-source ML denoiser (pumping). Browser/off
|
||||
// tiers keep the browser's normal capture pipeline (AGC on).
|
||||
autoGainControl: (denoiseMode !== 'ml').toString(),
|
||||
// Keep the browser's auto gain control ON in every tier. It used to be
|
||||
// turned off for the ML tier ("pumping"), but AGC is what brings a quiet
|
||||
// mic up to speaking level: without it ML-tier voices went out 10-20 dB
|
||||
// quieter than the browser tier, while the models themselves keep speech
|
||||
// within ~1.5 dB (measured: RNNoise, Speex, DTLN, DeepFilterNet3). Chrome's
|
||||
// AGC2 only adapts during speech, and the model runs after it, so it still
|
||||
// removes the noise AGC leaves in the pauses.
|
||||
autoGainControl: 'true',
|
||||
audio: initialAudio.toString(),
|
||||
video: initialVideo.toString(),
|
||||
header: 'none',
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { atom } from 'jotai';
|
||||
import {
|
||||
atomWithLocalStorage,
|
||||
getLocalStorageItem,
|
||||
@@ -20,3 +21,20 @@ 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),
|
||||
);
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { atom } from 'jotai';
|
||||
import { isSupportedTargetLang } from '../utils/translation/langUtils';
|
||||
import type { OverlayCorner } from '../utils/callOverlay';
|
||||
|
||||
const STORAGE_KEY = 'settings';
|
||||
export type DateFormat =
|
||||
@@ -287,6 +288,12 @@ 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;
|
||||
@@ -377,9 +384,11 @@ const defaultSettings: Settings = {
|
||||
|
||||
cameraOnJoin: false,
|
||||
// Tier default stays browser-native (known-good; best-perceived in testing so
|
||||
// far). If a user opts into the ML tier, default to the highest-quality model.
|
||||
// far). If a user opts into the ML tier, default to DTLN: in our measurements
|
||||
// it keeps voices the most natural, removes fans and typing well, and costs a
|
||||
// third of DeepFilterNet's CPU.
|
||||
callNoiseSuppression: 'browser',
|
||||
callDenoiseModel: 'deepfilternet',
|
||||
callDenoiseModel: 'dtln',
|
||||
// "Series suppression" (stack the browser's native NS before the ML model) is
|
||||
// off by default — best practice is a single NS stage; it's an opt-in test aid.
|
||||
callDenoiseNativeNS: false,
|
||||
@@ -411,6 +420,9 @@ const defaultSettings: Settings = {
|
||||
|
||||
globalCallHotkeys: true,
|
||||
|
||||
callOverlay: false,
|
||||
callOverlayCorner: 'top-left',
|
||||
|
||||
pauseAnimations: false,
|
||||
|
||||
composerToolbarButtons: DEFAULT_COMPOSER_TOOLBAR,
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { MatrixEvent, Room } from 'matrix-js-sdk';
|
||||
import {
|
||||
describeRoomBridge,
|
||||
getBridgedUserNetwork,
|
||||
getRoomBridges,
|
||||
parseBridgeEvent,
|
||||
} from './bridge';
|
||||
|
||||
const bridgeEvent = (type: string, stateKey: string, content: Record<string, unknown>) =>
|
||||
new MatrixEvent({ type, state_key: stateKey, content, room_id: '!r:x', sender: '@discordbot:x' });
|
||||
|
||||
// Shape of what mautrix-discord 0.7.7 sends for a guild channel.
|
||||
const discordContent = {
|
||||
bridgebot: '@discordbot:matrix.lotusguild.org',
|
||||
protocol: { id: 'discordgo', displayname: 'Discord' },
|
||||
channel: {
|
||||
id: '1565159372122882070',
|
||||
displayname: '#general',
|
||||
external_url: 'https://discord.com/channels/1/1565159372122882070',
|
||||
},
|
||||
network: { id: '1', displayname: 'Lotus Guild' },
|
||||
};
|
||||
|
||||
const roomWithState = (events: MatrixEvent[]): Room =>
|
||||
({
|
||||
getLiveTimeline: () => ({
|
||||
getState: () => ({
|
||||
getStateEvents: (type: string) => events.filter((e) => e.getType() === type),
|
||||
}),
|
||||
}),
|
||||
}) as unknown as Room;
|
||||
|
||||
test('Discord ghosts are recognised; the bridge bot and lookalikes are not', () => {
|
||||
assert.equal(
|
||||
getBridgedUserNetwork('@discord_123456789012345678:matrix.lotusguild.org'),
|
||||
'discord',
|
||||
);
|
||||
assert.equal(getBridgedUserNetwork('@discordbot:matrix.lotusguild.org'), undefined);
|
||||
assert.equal(getBridgedUserNetwork('@discord_fan:matrix.lotusguild.org'), undefined);
|
||||
assert.equal(getBridgedUserNetwork('@discord-relay:matrix.lotusguild.org'), undefined);
|
||||
assert.equal(getBridgedUserNetwork('@jared:matrix.lotusguild.org'), undefined);
|
||||
});
|
||||
|
||||
test('parseBridgeEvent reads a mautrix-discord m.bridge event', () => {
|
||||
assert.deepEqual(parseBridgeEvent(bridgeEvent('m.bridge', 'k', discordContent)), {
|
||||
network: 'discord',
|
||||
channelName: '#general',
|
||||
networkName: 'Lotus Guild',
|
||||
externalUrl: 'https://discord.com/channels/1/1565159372122882070',
|
||||
});
|
||||
});
|
||||
|
||||
test('parseBridgeEvent ignores unknown protocols and empty content', () => {
|
||||
assert.equal(
|
||||
parseBridgeEvent(bridgeEvent('m.bridge', 'k', { protocol: { id: 'telegram' } })),
|
||||
undefined,
|
||||
);
|
||||
assert.equal(parseBridgeEvent(bridgeEvent('m.bridge', 'k', {})), undefined);
|
||||
});
|
||||
|
||||
test('only http(s) channel links are kept', () => {
|
||||
const content = {
|
||||
...discordContent,
|
||||
channel: { displayname: '#x', external_url: ['javascript', 'alert(1)'].join(':') },
|
||||
};
|
||||
assert.equal(parseBridgeEvent(bridgeEvent('m.bridge', 'k', content))?.externalUrl, undefined);
|
||||
});
|
||||
|
||||
test('getRoomBridges merges m.bridge with its unstable copy, one entry per channel', () => {
|
||||
const room = roomWithState([
|
||||
bridgeEvent('m.bridge', 'fi.mau.discord://discord/1/2', discordContent),
|
||||
bridgeEvent('uk.half-shot.bridge', 'fi.mau.discord://discord/1/2', discordContent),
|
||||
]);
|
||||
assert.equal(getRoomBridges(room).length, 1);
|
||||
assert.equal(getRoomBridges(roomWithState([])).length, 0);
|
||||
});
|
||||
|
||||
test('describeRoomBridge degrades gracefully without names', () => {
|
||||
assert.equal(
|
||||
describeRoomBridge({ network: 'discord', channelName: '#general', networkName: 'Lotus Guild' }),
|
||||
'Bridged to #general in Lotus Guild on Discord',
|
||||
);
|
||||
assert.equal(describeRoomBridge({ network: 'discord' }), 'Bridged to Discord');
|
||||
});
|
||||
@@ -0,0 +1,80 @@
|
||||
import { MatrixEvent, Room } from 'matrix-js-sdk';
|
||||
import { StateEvent } from '../../types/matrix/room';
|
||||
import { getStateEvents } from './room';
|
||||
|
||||
export type BridgeNetwork = 'discord';
|
||||
|
||||
export const BRIDGE_NETWORK_NAME: Record<BridgeNetwork, string> = {
|
||||
discord: 'Discord',
|
||||
};
|
||||
|
||||
// Ghost (puppet) users a bridge creates for people on the other network.
|
||||
// mautrix-discord's default username_template is discord_{{.}} with a numeric
|
||||
// Discord snowflake; the bridge bot itself (@discordbot) is not a ghost.
|
||||
const GHOST_PATTERNS: [RegExp, BridgeNetwork][] = [[/^@discord_\d+:/, 'discord']];
|
||||
|
||||
export const getBridgedUserNetwork = (userId: string): BridgeNetwork | undefined =>
|
||||
GHOST_PATTERNS.find(([pattern]) => pattern.test(userId))?.[1];
|
||||
|
||||
// m.bridge protocol.id values that mean each network.
|
||||
const PROTOCOL_NETWORKS: Record<string, BridgeNetwork> = {
|
||||
discordgo: 'discord',
|
||||
discord: 'discord',
|
||||
};
|
||||
|
||||
export type RoomBridgeInfo = {
|
||||
network: BridgeNetwork;
|
||||
channelName?: string;
|
||||
networkName?: string;
|
||||
externalUrl?: string;
|
||||
};
|
||||
|
||||
const asString = (value: unknown): string | undefined =>
|
||||
typeof value === 'string' && value.trim() ? value.trim() : undefined;
|
||||
|
||||
// Only http(s) links are made clickable; the bridge (or anyone with state
|
||||
// power in the room) controls this value.
|
||||
const safeExternalUrl = (value: unknown): string | undefined => {
|
||||
const raw = asString(value);
|
||||
if (!raw) return undefined;
|
||||
try {
|
||||
const url = new URL(raw);
|
||||
return url.protocol === 'https:' || url.protocol === 'http:' ? url.href : undefined;
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
};
|
||||
|
||||
export const parseBridgeEvent = (event: MatrixEvent): RoomBridgeInfo | undefined => {
|
||||
const content = event.getContent();
|
||||
const protocolId = asString(content?.protocol?.id)?.toLowerCase();
|
||||
const network = protocolId ? PROTOCOL_NETWORKS[protocolId] : undefined;
|
||||
if (!network) return undefined;
|
||||
return {
|
||||
network,
|
||||
channelName: asString(content.channel?.displayname),
|
||||
networkName: asString(content.network?.displayname),
|
||||
externalUrl: safeExternalUrl(content.channel?.external_url),
|
||||
};
|
||||
};
|
||||
|
||||
/** Known bridges in a room, one per bridged channel (m.bridge preferred over the unstable copy). */
|
||||
export const getRoomBridges = (room: Room): RoomBridgeInfo[] => {
|
||||
const byKey = new Map<string, RoomBridgeInfo>();
|
||||
[StateEvent.BridgeUnstable, StateEvent.Bridge].forEach((type) => {
|
||||
getStateEvents(room, type).forEach((event) => {
|
||||
const info = parseBridgeEvent(event);
|
||||
if (info) byKey.set(event.getStateKey() ?? '', info);
|
||||
});
|
||||
});
|
||||
return Array.from(byKey.values());
|
||||
};
|
||||
|
||||
export const describeRoomBridge = (info: RoomBridgeInfo): string => {
|
||||
const network = BRIDGE_NETWORK_NAME[info.network];
|
||||
if (info.channelName && info.networkName) {
|
||||
return `Bridged to ${info.channelName} in ${info.networkName} on ${network}`;
|
||||
}
|
||||
if (info.channelName) return `Bridged to ${info.channelName} on ${network}`;
|
||||
return `Bridged to ${network}`;
|
||||
};
|
||||
@@ -0,0 +1,27 @@
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
|
||||
import { buildDenoisePayload } from './callDenoise';
|
||||
|
||||
test('buildDenoisePayload passes the settings through', () => {
|
||||
assert.deepEqual(
|
||||
buildDenoisePayload({
|
||||
callNoiseSuppression: 'ml',
|
||||
callDenoiseModel: 'dtln',
|
||||
callDenoiseNativeNS: false,
|
||||
callDenoiseGate: true,
|
||||
callDenoiseGateThreshold: -50,
|
||||
}),
|
||||
{ mode: 'ml', model: 'dtln', nativeNS: false, gate: true, gateThreshold: -50 },
|
||||
);
|
||||
});
|
||||
|
||||
test('buildDenoisePayload uses the same defaults as the join URL', () => {
|
||||
assert.deepEqual(buildDenoisePayload({}), {
|
||||
mode: 'browser',
|
||||
model: 'rnnoise',
|
||||
nativeNS: true,
|
||||
gate: false,
|
||||
gateThreshold: -45,
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,31 @@
|
||||
import { DenoiseModelId, NoiseSuppressionMode } from '../state/settings';
|
||||
|
||||
/**
|
||||
* Payload for the fork's `io.lotus.set_denoise` action, which switches noise
|
||||
* suppression on the live mic mid-call (browser suppressor on/off and/or the
|
||||
* ML model) instead of needing a rejoin.
|
||||
*/
|
||||
export type LotusDenoisePayload = {
|
||||
mode: NoiseSuppressionMode;
|
||||
model: DenoiseModelId;
|
||||
nativeNS: boolean;
|
||||
gate: boolean;
|
||||
gateThreshold: number;
|
||||
};
|
||||
|
||||
export type DenoiseSettings = {
|
||||
callNoiseSuppression?: NoiseSuppressionMode;
|
||||
callDenoiseModel?: DenoiseModelId;
|
||||
callDenoiseNativeNS?: boolean;
|
||||
callDenoiseGate?: boolean;
|
||||
callDenoiseGateThreshold?: number;
|
||||
};
|
||||
|
||||
/** Same defaults as the call URL built at join (useCallStart/createCallEmbed). */
|
||||
export const buildDenoisePayload = (s: DenoiseSettings): LotusDenoisePayload => ({
|
||||
mode: s.callNoiseSuppression ?? 'browser',
|
||||
model: s.callDenoiseModel ?? 'rnnoise',
|
||||
nativeNS: s.callDenoiseNativeNS ?? true,
|
||||
gate: s.callDenoiseGate ?? false,
|
||||
gateThreshold: s.callDenoiseGateThreshold ?? -45,
|
||||
});
|
||||
@@ -0,0 +1,124 @@
|
||||
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'],
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,121 @@
|
||||
/**
|
||||
* [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);
|
||||
@@ -21,6 +21,20 @@ const BASE = `${import.meta.env.BASE_URL.replace(/\/+$/, '')}/public/element-cal
|
||||
*/
|
||||
export const sampleRateFor = (model: DenoiseModelId): number => (model === 'dtln' ? 16000 : 48000);
|
||||
|
||||
/**
|
||||
* A pass-through node that downmixes whatever feeds it to ONE channel. Every
|
||||
* model only processes channel 0, and a recorded clip often decodes as stereo
|
||||
* (Chrome's Opus/WebM), so without this RNNoise/Speex played the cleaned audio
|
||||
* in the left ear only. Lotus Call does the same (#24). A mono output is then
|
||||
* upmixed to both ears by the destination.
|
||||
*/
|
||||
export const monoDownmix = (ctx: BaseAudioContext): GainNode =>
|
||||
new GainNode(ctx, {
|
||||
channelCount: 1,
|
||||
channelCountMode: 'explicit',
|
||||
channelInterpretation: 'speakers',
|
||||
});
|
||||
|
||||
export type DenoiseNode = {
|
||||
node: AudioWorkletNode;
|
||||
dispose: () => void;
|
||||
@@ -85,7 +99,10 @@ export async function buildModelNode(
|
||||
const mod: any = await import(/* @vite-ignore */ `${BASE}deepfilternet/index.esm.js`);
|
||||
const core = new mod.DeepFilterNet3Core({
|
||||
sampleRate: sampleRateFor(model),
|
||||
noiseReductionLevel: 80,
|
||||
// Same attenuation limit as Lotus Call (dB). Higher values mute the
|
||||
// background outright, so words drop into dead silence and sound
|
||||
// clipped at the end.
|
||||
noiseReductionLevel: 25,
|
||||
assetConfig: { cdnUrl: dfnBase },
|
||||
});
|
||||
await core.initialize();
|
||||
@@ -105,6 +122,8 @@ export async function buildModelNode(
|
||||
const [, wasmBinary] = await Promise.all([addModuleOnce(ctx, cfg.script), fetchWasm(cfg.wasm)]);
|
||||
const node = new AudioWorkletNode(ctx, cfg.proc, {
|
||||
channelCount: 1,
|
||||
channelCountMode: 'explicit',
|
||||
channelInterpretation: 'speakers',
|
||||
numberOfInputs: 1,
|
||||
numberOfOutputs: 1,
|
||||
processorOptions: { maxChannels: 1, wasmBinary },
|
||||
@@ -127,6 +146,9 @@ export async function buildGateNode(
|
||||
): Promise<AudioWorkletNode> {
|
||||
await addModuleOnce(ctx, 'noiseGateWorklet.js');
|
||||
return new AudioWorkletNode(ctx, '@sapphi-red/web-noise-suppressor/noise-gate', {
|
||||
channelCount: 1,
|
||||
channelCountMode: 'explicit',
|
||||
channelInterpretation: 'speakers',
|
||||
processorOptions: {
|
||||
openThreshold: thresholdDb,
|
||||
closeThreshold: thresholdDb - 5,
|
||||
|
||||
@@ -285,3 +285,75 @@ test('plain: strips Markdown syntax only, keeps ordinary #, _, > and * (#308)',
|
||||
'Read the guide docs',
|
||||
);
|
||||
});
|
||||
|
||||
test('[noticePrefix] resolveStatusPage keeps it only when set', () => {
|
||||
const base = { url: 'https://kuma.example', slug: 'public' };
|
||||
assert.equal(
|
||||
resolveStatusPage({ hs: { ...base, noticePrefix: ' Matrix: ' } }, 'hs')?.noticePrefix,
|
||||
'Matrix:',
|
||||
);
|
||||
assert.equal(resolveStatusPage({ hs: base }, 'hs')?.noticePrefix, undefined);
|
||||
});
|
||||
|
||||
test('[noticePrefix] on a shared page only prefixed notices reach users, without the prefix', () => {
|
||||
const page = {
|
||||
publicGroupList: [],
|
||||
maintenanceList: [
|
||||
{ id: 1, title: 'Jellyfin upgrade', status: 'under-maintenance' },
|
||||
{ id: 2, title: 'matrix: Synapse upgrade', status: 'under-maintenance' },
|
||||
],
|
||||
incidents: [
|
||||
{ id: 3, title: 'Storage redundancy restored', content: 'x', style: 'info' },
|
||||
{ id: 4, title: 'Matrix: Calls are flaky', content: 'y', style: 'warning' },
|
||||
{ id: 5, title: 'Matrix:', content: 'nothing left after the prefix', style: 'info' },
|
||||
{ id: 6, title: 'Matrixish news', content: 'z', style: 'info' },
|
||||
],
|
||||
};
|
||||
const s = parseKumaStatus(page, {}, DEFAULT_GROUPS, 'Matrix:');
|
||||
assert.deepEqual(
|
||||
s.maintenance.map((m) => [m.id, m.title]),
|
||||
[['2', 'Synapse upgrade']],
|
||||
);
|
||||
assert.deepEqual(
|
||||
s.incidents.map((i) => [i.id, i.title]),
|
||||
[['4', 'Calls are flaky']],
|
||||
);
|
||||
});
|
||||
|
||||
test('[noticePrefix] without one, every notice shows as before', () => {
|
||||
const page = {
|
||||
publicGroupList: [],
|
||||
maintenanceList: [{ id: 1, title: 'Jellyfin upgrade', status: 'under-maintenance' }],
|
||||
incidents: [{ id: 3, title: 'Storage redundancy restored', content: 'x', style: 'info' }],
|
||||
};
|
||||
const s = parseKumaStatus(page, {}, DEFAULT_GROUPS);
|
||||
assert.equal(s.maintenance[0].title, 'Jellyfin upgrade');
|
||||
assert.equal(s.incidents[0].title, 'Storage redundancy restored');
|
||||
});
|
||||
|
||||
test('[split public page] a Discord group going down touches neither homeserver nor calls', () => {
|
||||
const up = [
|
||||
{ status: 1, time: '2026-11-05 01:00:00' },
|
||||
{ status: 1, time: '2026-11-05 01:01:00' },
|
||||
];
|
||||
const down = [
|
||||
{ status: 0, time: '2026-11-05 01:00:00' },
|
||||
{ status: 0, time: '2026-11-05 01:01:00' },
|
||||
];
|
||||
const page = {
|
||||
publicGroupList: [
|
||||
{ name: 'Homeserver', monitorList: [{ id: 30 }] },
|
||||
{ name: 'Voice calls', monitorList: [{ id: 37 }] },
|
||||
{ name: 'Discord', monitorList: [{ id: 49 }] },
|
||||
{ name: 'Services', monitorList: [{ id: 27 }] },
|
||||
],
|
||||
};
|
||||
const s = parseKumaStatus(
|
||||
page,
|
||||
{ heartbeatList: { 30: up, 37: up, 49: down, 27: down } },
|
||||
DEFAULT_GROUPS,
|
||||
);
|
||||
assert.equal(s.homeserver, 'up');
|
||||
assert.equal(s.calls, 'up');
|
||||
assert.equal(s.login, 'unknown');
|
||||
});
|
||||
|
||||
@@ -7,6 +7,11 @@
|
||||
* "login": "Login" } } }
|
||||
* Users of any other homeserver never contact Kuma.
|
||||
*
|
||||
* Optional "noticePrefix": on a status page shared with other services, only
|
||||
* incidents and maintenance titled with this prefix (e.g. "Matrix:") reach
|
||||
* Lotus users, shown without it, so a media server's maintenance doesn't say
|
||||
* messages may be interrupted. Without it, every notice on the page shows.
|
||||
*
|
||||
* Kuma 2.x public JSON:
|
||||
* - GET /api/status-page/<slug>: publicGroupList[{name, monitorList[{id}]}],
|
||||
* maintenanceList (only windows UNDER maintenance right now), incidents
|
||||
@@ -19,7 +24,12 @@
|
||||
*/
|
||||
|
||||
export type StatusGroups = { homeserver?: string; calls?: string; login?: string };
|
||||
export type StatusPageConfig = { url: string; slug: string; groups: StatusGroups };
|
||||
export type StatusPageConfig = {
|
||||
url: string;
|
||||
slug: string;
|
||||
groups: StatusGroups;
|
||||
noticePrefix?: string;
|
||||
};
|
||||
|
||||
export type ServiceState = 'up' | 'down' | 'unknown';
|
||||
export type KumaMaintenance = { id: string; title: string; description: string; end?: number };
|
||||
@@ -69,9 +79,11 @@ export const resolveStatusPage = (
|
||||
const local = url.hostname === 'localhost' || url.hostname === '127.0.0.1';
|
||||
if (url.protocol !== 'https:' && !(url.protocol === 'http:' && local)) return undefined;
|
||||
const g = obj(entry.groups) ?? {};
|
||||
const noticePrefix = str(entry.noticePrefix).trim();
|
||||
return {
|
||||
url: url.origin,
|
||||
slug,
|
||||
...(noticePrefix ? { noticePrefix } : {}),
|
||||
groups: {
|
||||
homeserver: str(g.homeserver) || DEFAULT_GROUPS.homeserver,
|
||||
calls: str(g.calls) || DEFAULT_GROUPS.calls,
|
||||
@@ -133,10 +145,18 @@ const groupState = (
|
||||
return known > 0 ? 'up' : 'unknown';
|
||||
};
|
||||
|
||||
/** The title without the prefix, or undefined when it doesn't carry it. */
|
||||
const noticeTitle = (title: string, prefix: string | undefined): string | undefined => {
|
||||
if (!prefix) return title;
|
||||
if (title.slice(0, prefix.length).toLowerCase() !== prefix.toLowerCase()) return undefined;
|
||||
return title.slice(prefix.length).trim() || undefined;
|
||||
};
|
||||
|
||||
export const parseKumaStatus = (
|
||||
pageJson: unknown,
|
||||
heartbeatJson: unknown,
|
||||
groupNames: StatusGroups,
|
||||
noticePrefix?: string,
|
||||
): ServerStatus => {
|
||||
const page = obj(pageJson) ?? {};
|
||||
const groups = new Map<string, string[]>();
|
||||
@@ -155,14 +175,14 @@ export const parseKumaStatus = (
|
||||
Array.isArray(page.maintenanceList) ? page.maintenanceList : []
|
||||
)
|
||||
.map((m) => obj(m))
|
||||
.filter((m): m is Record<string, unknown> => !!m && str(m.title) !== '')
|
||||
.filter((m): m is Record<string, unknown> => !!m && !!noticeTitle(str(m.title), noticePrefix))
|
||||
.filter((m) => !m.status || m.status === 'under-maintenance')
|
||||
.map((m) => {
|
||||
const slot = obj((Array.isArray(m.timeslotList) ? m.timeslotList : [])[0]);
|
||||
const end = Date.parse(str(slot?.endDate));
|
||||
return {
|
||||
id: String(m.id ?? str(m.title)),
|
||||
title: str(m.title),
|
||||
title: noticeTitle(str(m.title), noticePrefix) ?? '',
|
||||
description: str(m.description),
|
||||
...(Number.isFinite(end) ? { end } : {}),
|
||||
};
|
||||
@@ -170,10 +190,13 @@ export const parseKumaStatus = (
|
||||
|
||||
const incidents: KumaIncident[] = (Array.isArray(page.incidents) ? page.incidents : [])
|
||||
.map((i) => obj(i))
|
||||
.filter((i): i is Record<string, unknown> => !!i && str(i.title) !== '' && i.active !== false)
|
||||
.filter(
|
||||
(i): i is Record<string, unknown> =>
|
||||
!!i && !!noticeTitle(str(i.title), noticePrefix) && i.active !== false,
|
||||
)
|
||||
.map((i) => ({
|
||||
id: String(i.id ?? str(i.title)),
|
||||
title: str(i.title),
|
||||
title: noticeTitle(str(i.title), noticePrefix) ?? '',
|
||||
content: str(i.content),
|
||||
style: str(i.style) || 'info',
|
||||
updated: str(i.lastUpdatedDate) || str(i.createdDate),
|
||||
|
||||
@@ -5,10 +5,10 @@ import { DENOISE_MODELS, ML_DENOISE_REQUIREMENTS, isMLDenoiseSupported } from '.
|
||||
|
||||
// ── Model catalog (data integrity) ──────────────────────────────────────────
|
||||
|
||||
test('DENOISE_MODELS lists the four models ordered best-quality (highest CPU) first', () => {
|
||||
test('DENOISE_MODELS lists the four models most-recommended first', () => {
|
||||
assert.deepEqual(
|
||||
DENOISE_MODELS.map((m) => m.id),
|
||||
['deepfilternet', 'dtln', 'rnnoise', 'speex'],
|
||||
['dtln', 'deepfilternet', 'rnnoise', 'speex'],
|
||||
);
|
||||
});
|
||||
|
||||
|
||||
@@ -1,12 +1,18 @@
|
||||
/**
|
||||
* Detection utilities + model catalog for Lotus ML noise suppression
|
||||
* (DeepFilterNet 3 / DTLN / RNNoise / Speex). The catalog is ordered by
|
||||
* quality (and, correspondingly, CPU cost) — highest first — and drives the
|
||||
* order of the model dropdown in settings.
|
||||
* (DTLN / DeepFilterNet 3 / RNNoise / Speex). The catalog is ordered by
|
||||
* recommendation — most recommended first — and drives the order of the model
|
||||
* dropdown in settings.
|
||||
*/
|
||||
|
||||
import { DenoiseModelId } from '../state/settings';
|
||||
|
||||
// CPU = share of ONE core while in a call, measured with each model running
|
||||
// exactly as Lotus Call runs it (Ryzen 7 PRO 4750GE, Chromium); download = bytes
|
||||
// actually fetched on first use. Re-measure when a model or its settings change.
|
||||
// Ratings come from scoring each model against the clean voice (PESQ/STOI) on
|
||||
// real speech mixed with fan, keyboard, street and babble noise at SNR 5 and
|
||||
// 15 dB; `transients` is how well it removes typing and clicks.
|
||||
export type DenoiseModel = {
|
||||
id: DenoiseModelId;
|
||||
name: string;
|
||||
@@ -17,25 +23,25 @@ export type DenoiseModel = {
|
||||
voiceQuality: 'Moderate' | 'High' | 'Very High';
|
||||
};
|
||||
|
||||
// Ordered best-quality (highest CPU) first — this is the dropdown order.
|
||||
// Ordered most-recommended first — this is the dropdown order.
|
||||
export const DENOISE_MODELS: DenoiseModel[] = [
|
||||
{
|
||||
id: 'deepfilternet',
|
||||
name: 'DeepFilterNet 3 (beta)',
|
||||
id: 'dtln',
|
||||
name: 'DTLN (recommended)',
|
||||
description:
|
||||
'Studio-grade deep-learning model (48 kHz fullband, ONNX). Best quality; highest CPU and a larger one-time download.',
|
||||
cpuUsage: '25-50%',
|
||||
binarySize: '~18 MB',
|
||||
'Keeps voices the most natural of the four. Removes fans and typing well, but not traffic or people talking in the background.',
|
||||
cpuUsage: '~9%',
|
||||
binarySize: '~20 MB',
|
||||
transients: 'Excellent',
|
||||
voiceQuality: 'Very High',
|
||||
},
|
||||
{
|
||||
id: 'dtln',
|
||||
name: 'DTLN (beta)',
|
||||
id: 'deepfilternet',
|
||||
name: 'DeepFilterNet 3 (strongest)',
|
||||
description:
|
||||
'Dual-signal deep-learning model (16 kHz). Strong on transient noise; moderate CPU.',
|
||||
cpuUsage: '10-20%',
|
||||
binarySize: '~4 MB',
|
||||
'Removes the most noise, including loud typing and traffic, but voices can sound slightly muffled. Uses about three times the CPU of DTLN.',
|
||||
cpuUsage: '~30%',
|
||||
binarySize: '~18 MB',
|
||||
transients: 'Excellent',
|
||||
voiceQuality: 'High',
|
||||
},
|
||||
@@ -43,18 +49,18 @@ export const DENOISE_MODELS: DenoiseModel[] = [
|
||||
id: 'rnnoise',
|
||||
name: 'RNNoise',
|
||||
description:
|
||||
'Lightweight hybrid model (48 kHz). Very low CPU; good for steady noise like fans, but can sound processed at full strength.',
|
||||
cpuUsage: '< 5%',
|
||||
'Very light. Handles steady noise like fans and traffic; does little for typing and can sound slightly processed.',
|
||||
cpuUsage: '~3%',
|
||||
binarySize: '< 1 MB',
|
||||
transients: 'Good',
|
||||
transients: 'Poor',
|
||||
voiceQuality: 'Moderate',
|
||||
},
|
||||
{
|
||||
id: 'speex',
|
||||
name: 'Speex (Legacy)',
|
||||
name: 'Speex (legacy)',
|
||||
description:
|
||||
'Classic DSP noise suppressor. Minimal CPU, gentlest on voice; weakest suppression.',
|
||||
cpuUsage: '< 2%',
|
||||
'Classic suppressor kept for very slow computers. Barely reduces noise in our tests; prefer any other option.',
|
||||
cpuUsage: '~2%',
|
||||
binarySize: '< 1 MB',
|
||||
transients: 'Poor',
|
||||
voiceQuality: 'Moderate',
|
||||
|
||||
@@ -0,0 +1,110 @@
|
||||
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);
|
||||
});
|
||||
@@ -0,0 +1,128 @@
|
||||
/**
|
||||
* [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();
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
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;
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
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 };
|
||||
@@ -79,3 +80,40 @@ 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',
|
||||
);
|
||||
});
|
||||
|
||||
@@ -9,6 +9,8 @@
|
||||
* 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';
|
||||
|
||||
@@ -47,5 +49,8 @@ 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 ?? '';
|
||||
};
|
||||
|
||||
@@ -28,6 +28,8 @@ export type SyncedSettingsContent = {
|
||||
export const DEVICE_LOCAL_KEYS: ReadonlySet<keyof Settings> = new Set<keyof Settings>([
|
||||
'settingsSync',
|
||||
'globalCallHotkeys',
|
||||
'callOverlay',
|
||||
'callOverlayCorner',
|
||||
'pageZoom',
|
||||
'mediaAutoLoad',
|
||||
'pauseAnimations',
|
||||
|
||||
@@ -50,6 +50,10 @@ export enum StateEvent {
|
||||
// [P5-15 v2] Room/Space soundboard pack (mirrors PoniesRoomEmotes). Per
|
||||
// state-key, aggregated with parent-space packs like custom emoji.
|
||||
LotusSoundboardRoom = 'io.lotus.soundboard',
|
||||
// MSC2346 bridge info; state_key identifies the bridged channel. Bridges
|
||||
// still send the pre-stable uk.half-shot.bridge copy alongside it.
|
||||
Bridge = 'm.bridge',
|
||||
BridgeUnstable = 'uk.half-shot.bridge',
|
||||
}
|
||||
|
||||
export enum MessageEvent {
|
||||
|
||||
@@ -136,6 +136,36 @@ function denoiseSources() {
|
||||
};
|
||||
}
|
||||
|
||||
// deepfilternet3-noise-filter inlines its AudioWorklet as a string and loads it
|
||||
// from a blob: URL. Audio worklets fall under script-src, and the desktop app's
|
||||
// CSP (rightly) has no blob: there, so DeepFilterNet 3 failed to start ("denoise
|
||||
// setProcessor failed … Failed to load worklet module script: blob:…"). Write
|
||||
// the worklet out as a real file next to the module and load it by URL instead,
|
||||
// which script-src 'self' allows everywhere. Fails the build if the library's
|
||||
// shape changes, rather than shipping a model that cannot start.
|
||||
const DFN_WORKLET_FILE = 'dfn-worklet.js';
|
||||
const DFN_BLOB_LOAD = ` const blob = new Blob([workletCode], { type: 'application/javascript' });
|
||||
const blobUrl = URL.createObjectURL(blob);
|
||||
await audioContext.audioWorklet.addModule(blobUrl);`;
|
||||
function dfnWorkletToFile(esmPath) {
|
||||
const src = fs.readFileSync(esmPath, 'utf8');
|
||||
const literal = src.match(/^var workletCode = (".*");\s*$/m)?.[1];
|
||||
const code = literal ? JSON.parse(literal) : undefined;
|
||||
if (!code?.includes('registerProcessor(') || !src.includes(DFN_BLOB_LOAD)) {
|
||||
throw new Error(
|
||||
`[lotus-denoise] deepfilternet3-noise-filter changed shape (inline worklet / blob loader not found in ${esmPath}) — build aborted; update dfnWorkletToFile in vite.config.js.`,
|
||||
);
|
||||
}
|
||||
fs.writeFileSync(path.join(path.dirname(esmPath), DFN_WORKLET_FILE), code);
|
||||
fs.writeFileSync(
|
||||
esmPath,
|
||||
src.replace(
|
||||
DFN_BLOB_LOAD,
|
||||
` // [lotus] Loaded from a file, not a blob: URL (CSP script-src 'self').\n await audioContext.audioWorklet.addModule(new URL('./${DFN_WORKLET_FILE}', import.meta.url).href);`,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
// Lotus ML noise suppression: ship the denoise worklets/wasm/models alongside
|
||||
// the vendored Element Call bundle. Runs after viteStaticCopy has populated
|
||||
// dist/public/element-call (closeBundle order). [Gitea #293] The dev server
|
||||
@@ -212,6 +242,7 @@ function lotusDenoise() {
|
||||
fs.mkdirSync(path.dirname(d), { recursive: true });
|
||||
fs.copyFileSync(s, d);
|
||||
});
|
||||
dfnWorkletToFile(path.join(denoiseDir, 'deepfilternet/index.esm.js'));
|
||||
|
||||
// [lotus] DENOISE CUTOVER: the getUserMedia shim is no longer injected.
|
||||
// Our forked Element Call now runs ML denoise in-source as a real LiveKit
|
||||
|
||||
Reference in New Issue
Block a user