From 995f2e5ae013897a56743b60eeedea909fe04db9 Mon Sep 17 00:00:00 2001 From: tgiachi Date: Tue, 17 Nov 2026 10:41:39 +0100 Subject: [PATCH] feat(web): talk to the Android app A WebView has no Media Session API. When the page runs inside the app it tells the app what plays, as one message per change, and the app asks the page back when a button of its notification is pressed. Settings has a Change server link, shown only inside the app. --- web/src/i18n/locales/en.json | 2 + web/src/i18n/locales/it.json | 2 + web/src/pages/SettingsPage.test.tsx | 16 ++++++ web/src/pages/SettingsPage.tsx | 13 +++++ web/src/player/mediaSession.test.ts | 75 +++++++++++++++++++++++++++++ web/src/player/mediaSession.ts | 69 ++++++++++++++++++++++++++ web/src/pwa/androidApp.ts | 5 ++ 7 files changed, 182 insertions(+) create mode 100644 web/src/pwa/androidApp.ts diff --git a/web/src/i18n/locales/en.json b/web/src/i18n/locales/en.json index 89a49b7..ca50a53 100644 --- a/web/src/i18n/locales/en.json +++ b/web/src/i18n/locales/en.json @@ -121,6 +121,8 @@ "admin": "Admin", "signOut": "Sign out", "app": "App", + "changeServer": "Change server", + "changeServerHelp": "Choose another Sonda server for this app. You will be asked for its address.", "appearance": "Appearance", "theme": "Theme", "language": "Language", diff --git a/web/src/i18n/locales/it.json b/web/src/i18n/locales/it.json index e8edf28..e684f77 100644 --- a/web/src/i18n/locales/it.json +++ b/web/src/i18n/locales/it.json @@ -121,6 +121,8 @@ "admin": "Admin", "signOut": "Esci", "app": "App", + "changeServer": "Cambia server", + "changeServerHelp": "Scegli un altro server Sonda per questa app. Ti verrĂ  chiesto il suo indirizzo.", "appearance": "Aspetto", "theme": "Tema", "language": "Lingua", diff --git a/web/src/pages/SettingsPage.test.tsx b/web/src/pages/SettingsPage.test.tsx index f7ed293..1e7548e 100644 --- a/web/src/pages/SettingsPage.test.tsx +++ b/web/src/pages/SettingsPage.test.tsx @@ -252,3 +252,19 @@ test('it has a section for the passwords of other apps', async () => { expect(await screen.findByRole('heading', { name: 'Apps and devices' })).toBeInTheDocument() expect(await screen.findByLabelText('Name of the app or device')).toBeInTheDocument() }) + +test('inside the Android app there is a way to choose another server, and in a browser there is not', async () => { + const agent = vi.spyOn(navigator, 'userAgent', 'get') + agent.mockReturnValue('Mozilla/5.0 (Linux; Android 16) Chrome/140 Mobile') + const { unmount } = renderSettings() + await screen.findByRole('heading', { name: 'Settings' }) + expect(screen.queryByRole('link', { name: 'Change server' })).toBeNull() + unmount() + + agent.mockReturnValue('Mozilla/5.0 (Linux; Android 16) Chrome/140 Mobile SondaApp') + renderSettings() + const link = await screen.findByRole('link', { name: 'Change server' }) + // The page that asks for the address is the one of the app itself. + expect(link).toHaveAttribute('href', 'http://localhost/?change') + expect(screen.getByRole('region', { name: 'App' })).toContainElement(link) +}) diff --git a/web/src/pages/SettingsPage.tsx b/web/src/pages/SettingsPage.tsx index 223e272..ed32a0e 100644 --- a/web/src/pages/SettingsPage.tsx +++ b/web/src/pages/SettingsPage.tsx @@ -10,6 +10,7 @@ import RadioInAppsSwitch from '@/components/RadioInAppsSwitch' import MastodonBlock from '@/components/MastodonBlock' import Section from '@/components/Section' import VersionLabel from '@/components/VersionLabel' +import { CHANGE_SERVER_URL, inAndroidApp } from '@/pwa/androidApp' import { useInstall } from '@/pwa/useInstall' import { Button } from '@/components/ui/button' import { Input } from '@/components/ui/input' @@ -179,6 +180,18 @@ export default function SettingsPage() { )} + {inAndroidApp() && ( +
+

{t('settings.changeServerHelp')}

+ + {t('settings.changeServer')} + +
+ )} +
diff --git a/web/src/player/mediaSession.test.ts b/web/src/player/mediaSession.test.ts index 7c661cb..ff392c7 100644 --- a/web/src/player/mediaSession.test.ts +++ b/web/src/player/mediaSession.test.ts @@ -2,6 +2,13 @@ import { afterEach, expect, test, vi } from 'vitest' import type { Track } from '@/api/catalog' import { setMediaSession, setPlaybackState, setPosition } from './mediaSession' +declare global { + interface Window { + SondaNative?: { update(json: string): void; stop(): void } + sondaNativeAction?: (name: string, ms: number) => void + } +} + class FakeMetadata { title = '' artist = '' @@ -127,3 +134,71 @@ test('the playback state and the position are left alone where the API is missin setPosition(1000, 2000) }).not.toThrow() }) + +// --- The Android app ----------------------------------------------------------------------------- +// A WebView has no Media Session API: the app gives the page a small object of its own, and asks the page back through a function. + +function withNativeApp() { + const native = { update: vi.fn(), stop: vi.fn() } + window.SondaNative = native + return native +} + +afterEach(() => { + delete window.SondaNative + delete window.sondaNativeAction +}) + +const flush = () => new Promise((resolve) => queueMicrotask(resolve)) + +test('the app is told once what plays, whether it plays and where it is, however many calls say it', async () => { + const native = withNativeApp() + setMediaSession(track, handlers) + setPlaybackState(true) + setPosition(60_000, 387_000) + await flush() + expect(native.update).toHaveBeenCalledTimes(1) + const sent = JSON.parse(native.update.mock.calls[0][0]) + expect(sent).toMatchObject({ title: 'Paranoid Android', artist: 'Radiohead, Guest', album: 'OK Computer', playing: true, positionMs: 60_000, durationMs: 387_000 }) + expect(sent.artworkUrl).toMatch(/^https?:\/\/.+\/albums\/3\/cover/) +}) + +test('a pause is told to the app too, with the same song', async () => { + const native = withNativeApp() + setMediaSession(track, handlers) + setPlaybackState(true) + setPosition(1000, 387_000) + await flush() + setPlaybackState(false) + await flush() + expect(native.update).toHaveBeenCalledTimes(2) + expect(JSON.parse(native.update.mock.calls[1][0])).toMatchObject({ title: 'Paranoid Android', playing: false }) +}) + +test('nothing playing tells the app to stop', async () => { + const native = withNativeApp() + setMediaSession(track, handlers) + await flush() + setMediaSession(null, handlers) + await flush() + expect(native.stop).toHaveBeenCalledTimes(1) +}) + +test('the buttons of the notification of the app move the player', () => { + withNativeApp() + setMediaSession(track, handlers) + for (const name of ['play', 'pause', 'next', 'previous']) window.sondaNativeAction!(name, 0) + window.sondaNativeAction!('seekto', 12_500) + expect(handlers.play).toHaveBeenCalled() + expect(handlers.pause).toHaveBeenCalled() + expect(handlers.next).toHaveBeenCalled() + expect(handlers.prev).toHaveBeenCalled() + expect(handlers.seekTo).toHaveBeenCalledWith(12_500) +}) + +test('in a browser the page does not look for the app', async () => { + setMediaSession(track, handlers) + setPlaybackState(true) + await flush() + expect(window.sondaNativeAction).toBeUndefined() +}) diff --git a/web/src/player/mediaSession.ts b/web/src/player/mediaSession.ts index 5a2c714..cebeba9 100644 --- a/web/src/player/mediaSession.ts +++ b/web/src/player/mediaSession.ts @@ -10,8 +10,70 @@ export interface MediaKeyHandlers { seekTo(ms: number): void } +// --- The Android app ----------------------------------------------------------------------------- +// A WebView has no Media Session API. The app (android/ in this repository) gives the page an object of its own, +// SondaNative, which keeps a notification with the controls and the playback alive; the app asks the page back +// through window.sondaNativeAction when one of its buttons is pressed. + +declare global { + interface Window { + SondaNative?: { update(json: string): void; stop(): void } + sondaNativeAction?: (name: string, ms: number) => void + } +} + +interface NativeState { + track: QueuedTrack | null + playing: boolean + positionMs: number + durationMs: number +} + +const nativeState: NativeState = { track: null, playing: false, positionMs: 0, durationMs: 0 } +let nativeScheduled = false + +/** Tells the app what plays. Calls that come together (a new song, its state, its position) make one message. */ +function pushNative(): void { + if (!window.SondaNative || nativeScheduled) return + nativeScheduled = true + queueMicrotask(() => { + nativeScheduled = false + const native = window.SondaNative + if (!native) return + const { track } = nativeState + if (!track) return native.stop() + native.update( + JSON.stringify({ + title: track.title, + artist: track.artists.map((a) => a.name).join(', '), + album: track.album?.title ?? '', + // The app fetches the cover itself, so the address is absolute. + artworkUrl: track.album ? new URL(mediaUrl(coverPath(track.friend, track.album.id)), location.origin).href : '', + playing: nativeState.playing, + positionMs: nativeState.positionMs, + durationMs: nativeState.durationMs, + }), + ) + }) +} + +function listenToNative(handlers: MediaKeyHandlers): void { + if (!window.SondaNative) return + window.sondaNativeAction = (name, ms) => { + if (name === 'play') handlers.play() + else if (name === 'pause') handlers.pause() + else if (name === 'next') handlers.next() + else if (name === 'previous') handlers.prev() + else if (name === 'seekto') handlers.seekTo(Math.round(ms)) + } +} + /** Tells the operating system what is playing (lock screen, media keys). Does nothing where the API is missing. */ export function setMediaSession(track: QueuedTrack | null, handlers: MediaKeyHandlers): void { + listenToNative(handlers) + nativeState.track = track + if (!track) Object.assign(nativeState, { playing: false, positionMs: 0, durationMs: 0 }) + pushNative() const session = navigator.mediaSession as MediaSession | undefined if (!session) return if (!track) { @@ -35,12 +97,19 @@ export function setMediaSession(track: QueuedTrack | null, handlers: MediaKeyHan /** Tells the operating system whether the player plays: the play and pause button of the lock screen follows it. */ export function setPlaybackState(playing: boolean): void { + nativeState.playing = playing + pushNative() const session = navigator.mediaSession as MediaSession | undefined if (session) session.playbackState = playing ? 'playing' : 'paused' } /** Tells the operating system the length of the song and where it is: it draws the seek bar of the lock screen from it. */ export function setPosition(positionMs: number, durationMs: number): void { + if (durationMs > 0) { + nativeState.positionMs = Math.min(Math.max(positionMs, 0), durationMs) + nativeState.durationMs = durationMs + pushNative() + } const session = navigator.mediaSession as MediaSession | undefined if (!session?.setPositionState || durationMs <= 0) return try { diff --git a/web/src/pwa/androidApp.ts b/web/src/pwa/androidApp.ts new file mode 100644 index 0000000..aa2bb0a --- /dev/null +++ b/web/src/pwa/androidApp.ts @@ -0,0 +1,5 @@ +/** The Android app is Sonda in a WebView; it says so in its user agent. */ +export const inAndroidApp = () => navigator.userAgent.includes('SondaApp') + +/** The page of the app that asks for the address of the server. It is the app's own, not the server's. */ +export const CHANGE_SERVER_URL = 'http://localhost/?change'