Add an Android app #48

Merged
squid merged 3 commits from feat/android-app into main 2026-11-17 09:42:27 +00:00
7 changed files with 182 additions and 0 deletions
Showing only changes of commit 995f2e5ae0 - Show all commits

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.
tgiachi 2026-11-17 10:41:39 +01:00

View file

@ -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",

View file

@ -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",

View file

@ -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)
})

View file

@ -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() {
</Section>
)}
{inAndroidApp() && (
<Section title={t('settings.app')}>
<p className="max-w-xl text-muted-foreground">{t('settings.changeServerHelp')}</p>
<a
href={CHANGE_SERVER_URL}
className="self-start font-semibold underline underline-offset-4 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring"
>
{t('settings.changeServer')}
</a>
</Section>
)}
<Section title={t('discover.title')}>
<ListeningSwitch />
</Section>

View file

@ -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<void>((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()
})

View file

@ -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 {

View file

@ -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'