feat(presence): "Listening to" from Navidrome / Dropped Needle (#491) #492
@@ -24,5 +24,8 @@
|
|||||||
"login": "Login"
|
"login": "Login"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
},
|
||||||
|
"nowPlaying": {
|
||||||
|
"matrix.lotusguild.org": { "url": "https://matrix.lotusguild.org/now-playing" }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -33,6 +33,8 @@ import { CreatorChip } from './CreatorChip';
|
|||||||
import { getDirectCreatePath, withSearchParam } from '../../pages/pathUtils';
|
import { getDirectCreatePath, withSearchParam } from '../../pages/pathUtils';
|
||||||
import { DirectCreateSearchParams } from '../../pages/paths';
|
import { DirectCreateSearchParams } from '../../pages/paths';
|
||||||
import { useExtendedProfile } from '../../hooks/useExtendedProfile';
|
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';
|
import { useUserNotes, USER_NOTE_MAX_LENGTH } from '../../hooks/useUserNotes';
|
||||||
|
|
||||||
type VerifyDeviceButtonProps = {
|
type VerifyDeviceButtonProps = {
|
||||||
@@ -376,7 +378,8 @@ export function UserRoomProfile({ userId }: UserRoomProfileProps) {
|
|||||||
<UserHeroName
|
<UserHeroName
|
||||||
displayName={displayName}
|
displayName={displayName}
|
||||||
userId={userId}
|
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}
|
presence={presence && presence.lastActiveTs !== 0 ? presence : undefined}
|
||||||
pronouns={extProfile.pronouns}
|
pronouns={extProfile.pronouns}
|
||||||
timezone={extProfile.timezone}
|
timezone={extProfile.timezone}
|
||||||
@@ -404,6 +407,7 @@ export function UserRoomProfile({ userId }: UserRoomProfileProps) {
|
|||||||
{userId !== myUserId && <MutualRoomsChip userId={userId} />}
|
{userId !== myUserId && <MutualRoomsChip userId={userId} />}
|
||||||
{userId !== myUserId && <OptionsChip userId={userId} />}
|
{userId !== myUserId && <OptionsChip userId={userId} />}
|
||||||
</Box>
|
</Box>
|
||||||
|
<NowPlayingCard userId={userId} />
|
||||||
</Box>
|
</Box>
|
||||||
{ignored && <IgnoredUserAlert />}
|
{ignored && <IgnoredUserAlert />}
|
||||||
{member && membership === Membership.Ban && (
|
{member && membership === Membership.Ban && (
|
||||||
|
|||||||
@@ -38,6 +38,9 @@ import { Membership } from '../../../types/matrix/room';
|
|||||||
|
|
||||||
import * as css from './MembersDrawer.css';
|
import * as css from './MembersDrawer.css';
|
||||||
import { useMatrixClient } from '../../hooks/useMatrixClient';
|
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 { UseStateProvider } from '../../components/UseStateProvider';
|
||||||
import {
|
import {
|
||||||
SearchItemStrGetter,
|
SearchItemStrGetter,
|
||||||
@@ -151,6 +154,9 @@ function MemberItem({
|
|||||||
? mx.mxcUrlToHttp(avatarMxcUrl, 100, 100, 'crop', undefined, false, useAuthentication)
|
? mx.mxcUrlToHttp(avatarMxcUrl, 100, 100, 'crop', undefined, false, useAuthentication)
|
||||||
: undefined;
|
: undefined;
|
||||||
const presence = useUserPresence(member.userId);
|
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 (
|
return (
|
||||||
<MenuItem
|
<MenuItem
|
||||||
@@ -193,10 +199,12 @@ function MemberItem({
|
|||||||
<Text size="T400" truncate>
|
<Text size="T400" truncate>
|
||||||
{name}
|
{name}
|
||||||
</Text>
|
</Text>
|
||||||
{presence?.status && (
|
{typedStatus ? (
|
||||||
<Text size="T200" truncate style={{ opacity: 0.65 }}>
|
<Text size="T200" truncate style={{ opacity: 0.65 }}>
|
||||||
{presence.status}
|
{typedStatus}
|
||||||
</Text>
|
</Text>
|
||||||
|
) : (
|
||||||
|
nowPlaying && <NowPlayingLine entry={nowPlaying} />
|
||||||
)}
|
)}
|
||||||
</Box>
|
</Box>
|
||||||
</MenuItem>
|
</MenuItem>
|
||||||
|
|||||||
@@ -28,6 +28,7 @@ import {
|
|||||||
PopOut,
|
PopOut,
|
||||||
RectCords,
|
RectCords,
|
||||||
Chip,
|
Chip,
|
||||||
|
Switch,
|
||||||
} from 'folds';
|
} from 'folds';
|
||||||
import { Method } from 'matrix-js-sdk';
|
import { Method } from 'matrix-js-sdk';
|
||||||
import FocusTrap from 'focus-trap-react';
|
import FocusTrap from 'focus-trap-react';
|
||||||
@@ -69,6 +70,9 @@ import {
|
|||||||
} from '../../../utils/statusPresets';
|
} from '../../../utils/statusPresets';
|
||||||
import { STATUS_EXPIRY_KEY, STATUS_MSG_KEY } from '../../../utils/statusKeys';
|
import { STATUS_EXPIRY_KEY, STATUS_MSG_KEY } from '../../../utils/statusKeys';
|
||||||
import { writeStatusExpiry } from '../../../utils/statusExpiry';
|
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 = {
|
type ProfileProps = {
|
||||||
profile: UserProfile;
|
profile: UserProfile;
|
||||||
@@ -390,6 +394,10 @@ function getMsFromOption(value: string): number {
|
|||||||
return parseInt(value, 10);
|
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() {
|
function ProfileStatus() {
|
||||||
const mx = useMatrixClient();
|
const mx = useMatrixClient();
|
||||||
const userId = mx.getUserId()!;
|
const userId = mx.getUserId()!;
|
||||||
@@ -397,7 +405,9 @@ function ProfileStatus() {
|
|||||||
const [presenceStatus] = useSetting(settingsAtom, 'presenceStatus');
|
const [presenceStatus] = useSetting(settingsAtom, 'presenceStatus');
|
||||||
const [hidePresence] = useSetting(settingsAtom, 'hidePresence');
|
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 initialStatus = serverStatus ?? localStorage.getItem(STATUS_MSG_KEY(userId)) ?? '';
|
||||||
const [statusMsg, setStatusMsg] = useState<string>(initialStatus);
|
const [statusMsg, setStatusMsg] = useState<string>(initialStatus);
|
||||||
// True while the user has unsaved local edits — prevents a server presence
|
// 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
|
// usePresenceUpdater.setOffline), so ignore it — reading it as a clear would
|
||||||
// wipe the saved status on every invisible toggle.
|
// wipe the saved status on every invisible toggle.
|
||||||
if (presence.presence === Presence.Offline) return;
|
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
|
// Only act on an actual remote change. Repeated heartbeats carrying the same
|
||||||
// status are ignored so they can never clobber an unsaved local edit.
|
// status are ignored so they can never clobber an unsaved local edit.
|
||||||
if (remoteStatus === lastSyncedRemoteRef.current) return;
|
if (remoteStatus === lastSyncedRemoteRef.current) return;
|
||||||
@@ -475,7 +485,8 @@ function ProfileStatus() {
|
|||||||
// Derive presence from the user's chosen setting so writing a status
|
// Derive presence from the user's chosen setting so writing a status
|
||||||
// never overrides Invisible/DND/Idle (e.g. outing an Invisible user).
|
// never overrides Invisible/DND/Idle (e.g. outing an Invisible user).
|
||||||
presence: presenceStateFromSetting(presenceStatus, hidePresence),
|
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],
|
[mx, presenceStatus, hidePresence],
|
||||||
),
|
),
|
||||||
@@ -568,7 +579,7 @@ function ProfileStatus() {
|
|||||||
// Preserve the user's chosen presence when clearing the status message.
|
// Preserve the user's chosen presence when clearing the status message.
|
||||||
queuePresenceWrite(mx, {
|
queuePresenceWrite(mx, {
|
||||||
presence: presenceStateFromSetting(presenceStatus, hidePresence),
|
presence: presenceStateFromSetting(presenceStatus, hidePresence),
|
||||||
status_msg: '',
|
status_msg: noTypedStatus(presenceStatus, hidePresence),
|
||||||
}).catch(() => undefined);
|
}).catch(() => undefined);
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -799,6 +810,69 @@ const COMMON_TIMEZONES = [
|
|||||||
'Pacific/Auckland',
|
'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() {
|
function ProfilePronouns() {
|
||||||
const mx = useMatrixClient();
|
const mx = useMatrixClient();
|
||||||
const userId = mx.getUserId()!;
|
const userId = mx.getUserId()!;
|
||||||
@@ -1093,6 +1167,7 @@ export function Profile() {
|
|||||||
<ProfileAvatar userId={userId} profile={profile} />
|
<ProfileAvatar userId={userId} profile={profile} />
|
||||||
<ProfileDisplayName userId={userId} profile={profile} />
|
<ProfileDisplayName userId={userId} profile={profile} />
|
||||||
<ProfileStatus />
|
<ProfileStatus />
|
||||||
|
<ProfileListening />
|
||||||
<ProfilePronouns />
|
<ProfilePronouns />
|
||||||
<ProfileTimezone />
|
<ProfileTimezone />
|
||||||
<ProfileDecoration />
|
<ProfileDecoration />
|
||||||
|
|||||||
@@ -42,6 +42,13 @@ export type ClientConfig = {
|
|||||||
*/
|
*/
|
||||||
statusPages?: Record<string, unknown>;
|
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).
|
* 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.
|
* 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 { PresenceDeduper, PresenceWrite, queuePresenceWrite } from '../utils/presenceWrite';
|
||||||
import { useMatrixClient } from './useMatrixClient';
|
import { useMatrixClient } from './useMatrixClient';
|
||||||
import { getLastLocalStatusWrite, pickHeartbeatStatus } from '../utils/ownStatusSync';
|
import { getLastLocalStatusWrite, pickHeartbeatStatus } from '../utils/ownStatusSync';
|
||||||
|
import { getMusicStatus, subscribeMusicStatus } from '../utils/nowPlayingClient';
|
||||||
import { useSetting } from '../state/hooks/settings';
|
import { useSetting } from '../state/hooks/settings';
|
||||||
import { settingsAtom } from '../state/settings';
|
import { settingsAtom } from '../state/settings';
|
||||||
import {
|
import {
|
||||||
@@ -125,14 +126,19 @@ export function usePresenceUpdater() {
|
|||||||
mx.setSyncPresence(presence).catch(() => undefined);
|
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 () => {
|
const setOnline = async () => {
|
||||||
syncPresence(SetPresence.Online);
|
syncPresence(SetPresence.Online);
|
||||||
const status = await resolveStatus();
|
const status = withMusic(await resolveStatus());
|
||||||
return send({ presence: 'online', ...(status ? { status_msg: status } : {}) }, 'online');
|
return send({ presence: 'online', ...(status ? { status_msg: status } : {}) }, 'online');
|
||||||
};
|
};
|
||||||
const setUnavailable = async (statusMsg?: string) => {
|
const setUnavailable = async (statusMsg?: string) => {
|
||||||
syncPresence(SetPresence.Unavailable);
|
syncPresence(SetPresence.Unavailable);
|
||||||
const status = await resolveStatus();
|
const status = statusMsg ? await resolveStatus() : withMusic(await resolveStatus());
|
||||||
return send(
|
return send(
|
||||||
{
|
{
|
||||||
presence: 'unavailable',
|
presence: 'unavailable',
|
||||||
@@ -151,13 +157,18 @@ export function usePresenceUpdater() {
|
|||||||
setOffline();
|
setOffline();
|
||||||
return undefined;
|
return undefined;
|
||||||
}
|
}
|
||||||
|
// [Gitea #491] A new track (or the music stopping) re-sends the same state.
|
||||||
if (presenceStatus === 'online') {
|
if (presenceStatus === 'online') {
|
||||||
setOnline();
|
setOnline();
|
||||||
return undefined;
|
return subscribeMusicStatus(() => {
|
||||||
|
setOnline();
|
||||||
|
});
|
||||||
}
|
}
|
||||||
if (presenceStatus === 'idle') {
|
if (presenceStatus === 'idle') {
|
||||||
setUnavailable();
|
setUnavailable();
|
||||||
return undefined;
|
return subscribeMusicStatus(() => {
|
||||||
|
setUnavailable();
|
||||||
|
});
|
||||||
}
|
}
|
||||||
if (presenceStatus === 'dnd') {
|
if (presenceStatus === 'dnd') {
|
||||||
// [Gitea #283] Real "busy" presence where supported: the status text
|
// [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 }));
|
activityEvents.forEach((e) => window.addEventListener(e, handleActivity, { passive: true }));
|
||||||
document.addEventListener('visibilitychange', handleVisibilityChange);
|
document.addEventListener('visibilitychange', handleVisibilityChange);
|
||||||
window.addEventListener('pagehide', handlePageHide);
|
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 () => {
|
return () => {
|
||||||
|
unsubscribeMusic();
|
||||||
clearTimeout(idleTimerRef.current);
|
clearTimeout(idleTimerRef.current);
|
||||||
activityEvents.forEach((e) => window.removeEventListener(e, handleActivity));
|
activityEvents.forEach((e) => window.removeEventListener(e, handleActivity));
|
||||||
document.removeEventListener('visibilitychange', handleVisibilityChange);
|
document.removeEventListener('visibilitychange', handleVisibilityChange);
|
||||||
|
|||||||
@@ -57,6 +57,9 @@ import { useSelectedRoom } from '../../hooks/router/useSelectedRoom';
|
|||||||
import { useInboxNotificationsSelected } from '../../hooks/router/useInbox';
|
import { useInboxNotificationsSelected } from '../../hooks/router/useInbox';
|
||||||
import { useMediaAuthentication } from '../../hooks/useMediaAuthentication';
|
import { useMediaAuthentication } from '../../hooks/useMediaAuthentication';
|
||||||
import { presenceStateFromSetting, usePresenceUpdater } from '../../hooks/usePresenceUpdater';
|
import { presenceStateFromSetting, usePresenceUpdater } from '../../hooks/usePresenceUpdater';
|
||||||
|
import { useNowPlayingMonitor } from '../../hooks/useNowPlaying';
|
||||||
|
import { effectiveStatus } from '../../utils/nowPlaying';
|
||||||
|
import { getMusicStatus } from '../../utils/nowPlayingClient';
|
||||||
import {
|
import {
|
||||||
MAX_MUTE_TIMEOUT_MS,
|
MAX_MUTE_TIMEOUT_MS,
|
||||||
loadMuteTimers,
|
loadMuteTimers,
|
||||||
@@ -364,6 +367,8 @@ function InviteNotifications() {
|
|||||||
|
|
||||||
function PresenceUpdater() {
|
function PresenceUpdater() {
|
||||||
usePresenceUpdater();
|
usePresenceUpdater();
|
||||||
|
// [Gitea #491] Own "Listening to" state, so the status can follow the music.
|
||||||
|
useNowPlayingMonitor();
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -441,7 +446,13 @@ function StatusExpiryMonitor() {
|
|||||||
clearing = true;
|
clearing = true;
|
||||||
setPresenceWithRetry(mx, {
|
setPresenceWithRetry(mx, {
|
||||||
presence: presenceStateFromSetting(presenceStatusRef.current, hidePresenceRef.current),
|
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(() => {
|
.then(() => {
|
||||||
noteLocalStatusWrite();
|
noteLocalStatusWrite();
|
||||||
|
|||||||
@@ -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 { test } from 'node:test';
|
||||||
import assert from 'node:assert/strict';
|
import assert from 'node:assert/strict';
|
||||||
import { LOCAL_WRITE_GRACE_MS, pickHeartbeatStatus } from './ownStatusSync';
|
import { LOCAL_WRITE_GRACE_MS, pickHeartbeatStatus } from './ownStatusSync';
|
||||||
|
import { NOW_PLAYING_PREFIX } from './nowPlaying';
|
||||||
|
|
||||||
const now = 1_000_000;
|
const now = 1_000_000;
|
||||||
const old = { lastLocalWriteAt: 0, now };
|
const old = { lastLocalWriteAt: 0, now };
|
||||||
@@ -79,3 +80,40 @@ test('pickHeartbeatStatus: the "dnd" sentinel is never adopted as the user statu
|
|||||||
'new',
|
'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.
|
* 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). */
|
/** The status_msg Lotus sends for Do Not Disturb (see usePresenceUpdater). */
|
||||||
export const DND_STATUS_SENTINEL = 'dnd';
|
export const DND_STATUS_SENTINEL = 'dnd';
|
||||||
|
|
||||||
@@ -47,5 +49,8 @@ export const pickHeartbeatStatus = ({
|
|||||||
if (!server || server.presence === 'offline') return mine;
|
if (!server || server.presence === 'offline') return mine;
|
||||||
if (now - writtenAt < LOCAL_WRITE_GRACE_MS) return mine;
|
if (now - writtenAt < LOCAL_WRITE_GRACE_MS) return mine;
|
||||||
if (server.status_msg === DND_STATUS_SENTINEL) 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 ?? '';
|
return server.status_msg ?? '';
|
||||||
};
|
};
|
||||||
|
|||||||
Reference in New Issue
Block a user