feat(presence): "Listening to" from Navidrome / Dropped Needle (#491)
CI / Build & Quality Checks (push) Skipped
CI / Secret scan (gitleaks) (push) Skipped
CI / Playwright smoke (e2e) (push) Skipped
CI / Build & Quality Checks (push) Skipped
CI / Secret scan (gitleaks) (push) Skipped
CI / Playwright smoke (e2e) (push) Skipped
Discord/Spotify-style now playing, served by the new Lotus now-playing service (matrix repo, now-playing/): - Profile popout: a "Listening to" card (cover, track, artist, album, live progress); member list: a 🎵 line when the member has no typed status. Data comes from GET /now-playing/v1/users, batched across all visible users and polled every 20 s while the page is visible. - Settings → Profile: "Share what I'm listening to", off by default, stored by the service (GET/PUT /v1/me). Auth is a Matrix OpenID token. - Status text: while Lotus is open and sharing, the Matrix status shows "🎵 Artist – Track" so other clients see it, but only when the user has no typed status, and never in DND/Invisible. The typed status and its auto-clear are never touched. The music text uses a thin space after the note, and every device reads it as "no typed status" (pickHeartbeatStatus, Profile sync), so it can't be adopted as the user's status. Clearing or auto-clearing a status falls back to the music; closing the window drops it (pagehide sends the typed status). - config.json: nowPlaying → https://matrix.lotusguild.org/now-playing. Tests: nowPlaying.test.ts (format, marker, priority matrix, position, config/cover URLs) and a heartbeat case in ownStatusSync.test.ts. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01PPmy3tPq869XDW4njjVaKA
This commit is contained in:
@@ -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;
|
||||
}
|
||||
Reference in New Issue
Block a user