diff --git a/config.json b/config.json
index 857bfa8f8..9e7746b82 100644
--- a/config.json
+++ b/config.json
@@ -24,5 +24,8 @@
"login": "Login"
}
}
+ },
+ "nowPlaying": {
+ "matrix.lotusguild.org": { "url": "https://matrix.lotusguild.org/now-playing" }
}
}
diff --git a/src/app/components/now-playing/NowPlaying.tsx b/src/app/components/now-playing/NowPlaying.tsx
new file mode 100644
index 000000000..0adb8d234
--- /dev/null
+++ b/src/app/components/now-playing/NowPlaying.tsx
@@ -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 (
+
+
+
+ );
+ }
+ return (
+
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 (
+
+
+ {playing ? 'Listening to' : 'Paused'}
+
+
+
+
+
+ {entry.title}
+
+ {subtitle && (
+
+ {subtitle}
+
+ )}
+ {entry.player && (
+
+ {entry.player}
+
+ )}
+
+
+ {durationMs > 0 && (
+
+
+
+
+ {formatTrackTime(posMs)}
+
+
+ {formatTrackTime(durationMs)}
+
+
+
+ )}
+
+ );
+}
+
+/** 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}
+
+ );
+}
diff --git a/src/app/components/user-profile/UserRoomProfile.tsx b/src/app/components/user-profile/UserRoomProfile.tsx
index 1d3d7e0e5..1275e5b91 100644
--- a/src/app/components/user-profile/UserRoomProfile.tsx
+++ b/src/app/components/user-profile/UserRoomProfile.tsx
@@ -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) {
}
{userId !== myUserId && }
+
{ignored && }
{member && membership === Membership.Ban && (
diff --git a/src/app/features/room/MembersDrawer.tsx b/src/app/features/room/MembersDrawer.tsx
index 783cebc1f..4947e8afc 100644
--- a/src/app/features/room/MembersDrawer.tsx
+++ b/src/app/features/room/MembersDrawer.tsx
@@ -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,
@@ -151,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 (
diff --git a/src/app/features/settings/account/Profile.tsx b/src/app/features/settings/account/Profile.tsx
index ace28ee5c..7890f18b4 100644
--- a/src/app/features/settings/account/Profile.tsx
+++ b/src/app/features/settings/account/Profile.tsx
@@ -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(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 (
+
+ Share what I'm listening to
+
+ }
+ description={
+ <>
+ {description}
+ {saveState.status === AsyncStatus.Error && (
+
+ Couldn't save. Try again.
+
+ )}
+ >
+ }
+ after={
+ saving ? (
+
+ ) : (
+ {
+ save(v).catch(() => undefined);
+ }}
+ />
+ )
+ }
+ />
+ );
+}
+
function ProfilePronouns() {
const mx = useMatrixClient();
const userId = mx.getUserId()!;
@@ -1093,6 +1167,7 @@ export function Profile() {
+
diff --git a/src/app/hooks/useClientConfig.ts b/src/app/hooks/useClientConfig.ts
index 91e68f5ea..132a17316 100644
--- a/src/app/hooks/useClientConfig.ts
+++ b/src/app/hooks/useClientConfig.ts
@@ -42,6 +42,13 @@ export type ClientConfig = {
*/
statusPages?: Record;
+ /**
+ * [Gitea #491] Lotus now-playing service per homeserver, for "Listening to":
+ * { "": { url } } (https only). Homeservers not listed never
+ * contact it and show no music.
+ */
+ nowPlaying?: Record;
+
/**
* 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.
diff --git a/src/app/hooks/useNowPlaying.ts b/src/app/hooks/useNowPlaying.ts
new file mode 100644
index 000000000..fddef7b3c
--- /dev/null
+++ b/src/app/hooks/useNowPlaying.ts
@@ -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 | 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]);
+}
diff --git a/src/app/hooks/usePresenceUpdater.ts b/src/app/hooks/usePresenceUpdater.ts
index 5f2466f0a..025f2a9b0 100644
--- a/src/app/hooks/usePresenceUpdater.ts
+++ b/src/app/hooks/usePresenceUpdater.ts
@@ -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);
diff --git a/src/app/pages/client/ClientNonUIFeatures.tsx b/src/app/pages/client/ClientNonUIFeatures.tsx
index d1f152cc4..299b7ddd4 100644
--- a/src/app/pages/client/ClientNonUIFeatures.tsx
+++ b/src/app/pages/client/ClientNonUIFeatures.tsx
@@ -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();
diff --git a/src/app/utils/nowPlaying.test.ts b/src/app/utils/nowPlaying.test.ts
new file mode 100644
index 000000000..7188ba028
--- /dev/null
+++ b/src/app/utils/nowPlaying.test.ts
@@ -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 => ({
+ 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);
+});
diff --git a/src/app/utils/nowPlaying.ts b/src/app/utils/nowPlaying.ts
new file mode 100644
index 000000000..d319e3ade
--- /dev/null
+++ b/src/app/utils/nowPlaying.ts
@@ -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 = '\u{1F3B5}โ';
+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): 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)[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();
+}
diff --git a/src/app/utils/nowPlayingClient.ts b/src/app/utils/nowPlayingClient.ts
new file mode 100644
index 000000000..c5cf118b3
--- /dev/null
+++ b/src/app/utils/nowPlayingClient.ts
@@ -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;
+
+ constructor(
+ private readonly mx: MatrixClient,
+ readonly base: string,
+ ) {}
+
+ private async getToken(force: boolean): Promise {
+ 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(path: string, init: RequestInit = {}, retried = false): Promise {
+ 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(path, init, true);
+ if (!res.ok) throw new Error(`now-playing HTTP ${res.status}`);
+ return res.json() as Promise;
+ }
+
+ me(): Promise {
+ return this.request('/v1/me');
+ }
+
+ setShare(share: boolean): Promise {
+ return this.request('/v1/me', { method: 'PUT', body: JSON.stringify({ share }) });
+ }
+
+ async users(ids: string[]): Promise> {
+ const q = encodeURIComponent(ids.join(','));
+ const res = await this.request<{ users?: Record }>(
+ `/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();
+const musicListeners = new Set();
+
+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;
+}
diff --git a/src/app/utils/nowPlayingStore.ts b/src/app/utils/nowPlayingStore.ts
new file mode 100644
index 000000000..969e2759f
--- /dev/null
+++ b/src/app/utils/nowPlayingStore.ts
@@ -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();
+
+ private readonly data = new Map();
+
+ private readonly listeners = new Map>();
+
+ private timer?: ReturnType;
+
+ 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 = {};
+ 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);
+ }
+}
diff --git a/src/app/utils/ownStatusSync.test.ts b/src/app/utils/ownStatusSync.test.ts
index e17601622..4c760dae2 100644
--- a/src/app/utils/ownStatusSync.test.ts
+++ b/src/app/utils/ownStatusSync.test.ts
@@ -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',
+ );
+});
diff --git a/src/app/utils/ownStatusSync.ts b/src/app/utils/ownStatusSync.ts
index d56324602..81d08f31f 100644
--- a/src/app/utils/ownStatusSync.ts
+++ b/src/app/utils/ownStatusSync.ts
@@ -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 ?? '';
};