Compare commits

..
Author SHA1 Message Date
e11ce89b21 chore(release): 0.5.0 [skip ci]
## [0.5.0](https://git.kmalloc.org/squid/sonda/compare/v0.4.2...v0.5.0) (2026-11-17)

### Features

* **android:** add an Android app ([ba10b8e](ba10b8ef7b)), closes [#47](#47)
* **web:** talk to the Android app ([995f2e5](995f2e5ae0))

### Bug fixes

* **web:** show a restored queue on the lock screen ([a2d6d2a](a2d6d2a925))
2026-11-17 09:42:59 +00:00
d57fbe3ef1 Merge pull request 'Add an Android app' (#48) from feat/android-app into main
All checks were successful
release / release (push) Successful in 34s
release / base (push) Successful in 2s
release / image (amd64) (push) Successful in 3m21s
release / image (arm64) (push) Successful in 3m20s
release / manifest (push) Successful in 2s
2026-11-17 09:42:26 +00:00
tgiachi
ba10b8ef7b feat(android): add an Android app
A Capacitor shell that opens a Sonda server in a WebView. It asks for the
address of the server the first time and remembers it, trusts the certificate
authorities installed on the phone, and keeps a notification with the
controls so that the music goes on with the screen off.

Fixes #47
2026-11-17 10:41:39 +01:00
tgiachi
995f2e5ae0 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.
2026-11-17 10:41:39 +01:00
tgiachi
a2d6d2a925 fix(web): show a restored queue on the lock screen
A queue that came back after a reload was set before the player started to
follow the state, so the lock screen never heard about its song: no title and
no controls until the song changed, and a press of play told it nothing.
The lock screen is now told about the restored song, paused, where it was.
2026-11-17 10:41:39 +01:00
f6a3cd6b5e chore(release): 0.4.2 [skip ci]
## [0.4.2](https://git.kmalloc.org/squid/sonda/compare/v0.4.1...v0.4.2) (2026-11-17)

### Bug fixes

* **web:** make the seek bar fit the width of a phone ([6220238](6220238068)), closes [#45](#45)
2026-11-17 09:03:27 +00:00
23845391d4 Merge pull request 'Make the seek bar fit the width of a phone' (#46) from fix/seek-bar-fits-phone into main
All checks were successful
release / release (push) Successful in 36s
release / base (push) Successful in 2s
release / image (amd64) (push) Successful in 3m55s
release / image (arm64) (push) Successful in 3m56s
release / manifest (push) Successful in 2s
2026-11-17 09:02:52 +00:00
tgiachi
6220238068 fix(web): make the seek bar fit the width of a phone
The shape of the track has 120 thin bars. With a 2px gap and a 1px minimum
width each they need 358px, so on a phone the bar ran past the right edge of
the full-screen player, the page scrolled sideways and the play button was
off centre.

The bars now have no minimum width and a 1px gap on a phone; wide screens
keep the 2px gap.

Fixes #45
2026-11-17 10:02:30 +01:00
85a1f9dc8a chore(release): 0.4.1 [skip ci]
## [0.4.1](https://git.kmalloc.org/squid/sonda/compare/v0.4.0...v0.4.1) (2026-11-17)

### Bug fixes

* **web:** keep the controls of the full-screen player on screen on a phone ([a757743](a757743161)), closes [#43](#43)
2026-11-17 08:41:25 +00:00
755220d08a Merge pull request 'Keep the controls of the full-screen player on screen on a phone' (#44) from fix/player-controls-on-screen into main
All checks were successful
release / release (push) Successful in 34s
release / base (push) Successful in 2s
release / image (amd64) (push) Successful in 3m23s
release / image (arm64) (push) Successful in 3m21s
release / manifest (push) Successful in 2s
2026-11-17 08:40:52 +00:00
tgiachi
a757743161 fix(web): keep the controls of the full-screen player on screen on a phone
On a short phone screen the play, previous and next buttons were pushed
under the bottom edge and needed a scroll to reach.

- The seek bar and the controls sit in one block that sticks to the bottom
  on a phone, above the safe area; what comes next scrolls beneath it.
- The cover is capped by the height of the screen as well as its width.
- The sound picture is lower on a phone.

Wide screens keep the same layout as before.

Fixes #43
2026-11-17 09:40:38 +01:00
5eff98a639 chore(release): 0.4.0 [skip ci]
## [0.4.0](https://git.kmalloc.org/squid/sonda/compare/v0.3.0...v0.4.0) (2026-11-16)

### Features

* **web:** make Sonda feel like an app on a phone ([75a7898](75a7898c68))

### Documentation

* note that this repo moved to git.kmalloc.org ([ee31e0e](ee31e0ee7c))
2026-11-16 16:39:55 +00:00
95f9be70bd Merge pull request 'Make Sonda feel like an app on a phone' (#42) from fix/phone-app-feel into main
All checks were successful
release / release (push) Successful in 36s
release / base (push) Successful in 2s
release / image (amd64) (push) Successful in 4m7s
release / image (arm64) (push) Successful in 4m5s
release / manifest (push) Successful in 2s
2026-11-16 16:39:21 +00:00
tgiachi
75a7898c68 feat(web): make Sonda feel like an app on a phone
A review of the phone experience (the issue) found a desktop page made
smaller. What changes:

feat:
- The player bar is one row on a phone (cover, title, play and next, a thin
  line of progress) and is not there while nothing plays. A tap or a swipe up
  on it opens the full-screen player.
- The Back gesture closes the full-screen player instead of leaving the page
  under it; a swipe down closes it too. The full queue is listed on a phone.
- The queue is kept in the browser: a reload, or a tab that Android throws
  away, comes back paused on the same song at the same second. It belongs to
  the person signed in and is forgotten on sign-out.
- Tabs have icons; the page starts at its top on a new route and back goes to
  where the list was; a swipe on the page no longer reloads it.

fix:
- The player now knows when the system pauses the audio (another app, a
  headset), so the button and the lock screen no longer say it plays.
- The lock screen has a working seek bar and the right play/pause state.
- The player bar was not hidden by max-sm:hidden: its grid rules were outside
  the Tailwind layers and won. They are in the components layer now.
- Song rows give the title the room on a phone (no number column).
- The album header is centred and the greeting is smaller on a phone; recent
  songs on Home show the artist.
- Thumbnails ask for the small cover (300 px) and not the 1000 px one.
- Pages use dvh, the viewport covers the notch, and the tabs keep clear of
  the gesture bar; the update notice no longer sits on the bar.
- No grey tap flash, no double-tap delay, no image menu on a long press.
2026-11-16 17:38:58 +01:00
tgiachi
ee31e0ee7c docs: note that this repo moved to git.kmalloc.org 2026-11-16 17:20:12 +01:00
96 changed files with 4130 additions and 98 deletions

View file

@ -1,5 +1,38 @@
# Changelog # Changelog
## [0.5.0](https://git.kmalloc.org/squid/sonda/compare/v0.4.2...v0.5.0) (2026-11-17)
### Features
* **android:** add an Android app ([ba10b8e](https://git.kmalloc.org/squid/sonda/commit/ba10b8ef7bbcf4fe3735e7b931d1b687259cc044)), closes [#47](https://git.kmalloc.org/squid/sonda/issues/47)
* **web:** talk to the Android app ([995f2e5](https://git.kmalloc.org/squid/sonda/commit/995f2e5ae013897a56743b60eeedea909fe04db9))
### Bug fixes
* **web:** show a restored queue on the lock screen ([a2d6d2a](https://git.kmalloc.org/squid/sonda/commit/a2d6d2a925edf8de89a7a4df0afbfa82004ccf87))
## [0.4.2](https://git.kmalloc.org/squid/sonda/compare/v0.4.1...v0.4.2) (2026-11-17)
### Bug fixes
* **web:** make the seek bar fit the width of a phone ([6220238](https://git.kmalloc.org/squid/sonda/commit/6220238068c446a97d1726697601f7ba5e126028)), closes [#45](https://git.kmalloc.org/squid/sonda/issues/45)
## [0.4.1](https://git.kmalloc.org/squid/sonda/compare/v0.4.0...v0.4.1) (2026-11-17)
### Bug fixes
* **web:** keep the controls of the full-screen player on screen on a phone ([a757743](https://git.kmalloc.org/squid/sonda/commit/a757743161ac3f7a348884a9f7b2490ab09b99e1)), closes [#43](https://git.kmalloc.org/squid/sonda/issues/43)
## [0.4.0](https://git.kmalloc.org/squid/sonda/compare/v0.3.0...v0.4.0) (2026-11-16)
### Features
* **web:** make Sonda feel like an app on a phone ([75a7898](https://git.kmalloc.org/squid/sonda/commit/75a7898c68ca65c8c4efa0f51b72d62ac9a4db6e))
### Documentation
* note that this repo moved to git.kmalloc.org ([ee31e0e](https://git.kmalloc.org/squid/sonda/commit/ee31e0ee7caf9e7510b7cfde1f4e096721966e90))
## [0.3.0](https://git.kmalloc.org/squid/sonda/compare/v0.2.0...v0.3.0) (2026-11-16) ## [0.3.0](https://git.kmalloc.org/squid/sonda/compare/v0.2.0...v0.3.0) (2026-11-16)
### Features ### Features

View file

@ -1,5 +1,9 @@
# Sonda # Sonda
**This repository has moved.** Development continues at
[git.kmalloc.org/squid/sonda](https://git.kmalloc.org/squid/sonda); this
Codeberg mirror is archived and read-only.
Sonda is a privacy-first, self-hosted music server written in Go. It streams the music you already own, from your own disks, and keeps everything it knows about you on your own machine. Sonda is a privacy-first, self-hosted music server written in Go. It streams the music you already own, from your own disks, and keeps everything it knows about you on your own machine.
It is a single executable, one database (SQLite by default, PostgreSQL if you prefer) and the folders that hold your music. There is no Redis, no message broker and no cloud account. It is a single executable, one database (SQLite by default, PostgreSQL if you prefer) and the folders that hold your music. There is no Redis, no message broker and no cloud account.
@ -390,7 +394,7 @@ Back up the database and `sonda.toml`. Your music stays wherever you keep it.
## Web app ## Web app
A web client lives in `web/` (React, Vite and shadcn/ui). It talks only to the Sonda server: no CDN, no external fonts, no analytics. With the app built into the binary (`make build`, or the Docker image) `sondad` serves it: open the address of the server, for example `http://127.0.0.1:8080`, and sign in. The page carries a strict Content-Security-Policy (only resources of the server itself, no inline scripts), cannot be framed and sends no referrer, and a link inside the app (`/admin/users`) works when you reload it. The player draws a live picture of what is playing, in the browser, from the sound itself (Web Audio). Settings has a choice for it, kept on the device: a spectrogram (the last seconds, low notes at the bottom, the default), the classic bars with falling caps, an oscilloscope, Milkdrop, or nothing. The bars, the oscilloscope and the spectrogram take the colour of this server or, for a friend's song, the colour of the friend. Milkdrop fills the background of the full-screen player with the pictures Winamp made famous, drawn on the device with [butterchurn](https://github.com/jberg/butterchurn) (MIT) and its presets, which are part of the app: nothing is fetched from outside. It is loaded only when chosen, and anyone who asked the system for less motion gets the spectrogram instead, because the pictures flash. The player listens to the sound and changes nothing of it, and draws only while something plays. A web client lives in `web/` (React, Vite and shadcn/ui). It talks only to the Sonda server: no CDN, no external fonts, no analytics. With the app built into the binary (`make build`, or the Docker image) `sondad` serves it: open the address of the server, for example `http://127.0.0.1:8080`, and sign in. The page carries a strict Content-Security-Policy (only resources of the server itself, no inline scripts), cannot be framed and sends no referrer, and a link inside the app (`/admin/users`) works when you reload it. The player draws a live picture of what is playing, in the browser, from the sound itself (Web Audio). Settings has a choice for it, kept on the device: a spectrogram (the last seconds, low notes at the bottom, the default), the classic bars with falling caps, an oscilloscope, Milkdrop, or nothing. The bars, the oscilloscope and the spectrogram take the colour of this server or, for a friend's song, the colour of the friend. Milkdrop fills the background of the full-screen player with the pictures Winamp made famous, drawn on the device with [butterchurn](https://github.com/jberg/butterchurn) (MIT) and its presets, which are part of the app: nothing is fetched from outside. It is loaded only when chosen, and anyone who asked the system for less motion gets the spectrogram instead, because the pictures flash. The player listens to the sound and changes nothing of it, and draws only while something plays. On a phone the player is one row at the foot of the page (and is not there while nothing plays); a tap or a swipe up opens the full-screen player, a swipe down or the Back gesture closes it, and the lock screen shows the song with its seek bar and follows play and pause. The queue is kept in the browser, so a page that is reloaded, or a tab that Android throws away, comes back paused on the same song at the same second.
To work on the interface itself, run the Vite dev server next to a running `sondad` (set `SONDA_URL` to where it listens: the default is `http://127.0.0.1:8080`): To work on the interface itself, run the Vite dev server next to a running `sondad` (set `SONDA_URL` to where it listens: the default is `http://127.0.0.1:8080`):
@ -404,6 +408,25 @@ What it does today: sign in (and create the first account of a new server), brow
More commands, all run in `web/`: `npm test`, `npm run build`, and `npm run gen:api`, which rebuilds `src/api/schema.d.ts` from the OpenAPI spec (it fetches the generator with `npx`, so it needs the network once). `npm run build` writes to `internal/webui/dist` (git-ignored), not to `web/dist`. More commands, all run in `web/`: `npm test`, `npm run build`, and `npm run gen:api`, which rebuilds `src/api/schema.d.ts` from the OpenAPI spec (it fetches the generator with `npx`, so it needs the network once). `npm run build` writes to `internal/webui/dist` (git-ignored), not to `web/dist`.
## Android app
`android/` holds a small Android app: a Capacitor shell that opens a Sonda server in a WebView, with its own icon and no browser bars. It is for a phone whose browser cannot install a PWA. It has no copy of the web app: it shows the one of your server, so a new version of the server is a new version of the app.
- The first time it asks for the address of the server (`music.example.org`, or `http://192.168.1.5:8080`) and remembers it. Settings has Change server, shown only inside the app.
- It trusts the certificate authorities installed on the phone, so a server behind a private CA opens once the CA is installed (Settings, Security, Install a certificate). It also opens a server on plain `http`.
- A WebView has no Media Session API, so the app keeps its own: a notification with the song, its cover and the buttons, and the lock screen and headset buttons work. The music goes on with the screen off. From Android 13 it asks to show notifications; without a yes the music still plays and only the notification is hidden.
To build it you need Node, a JDK 21 and the Android SDK (platform 36 and its build tools; set `ANDROID_HOME`):
```bash
cd android
npm ci
npm run apk # android/android/app/build/outputs/apk/debug/app-debug.apk
adb install -r android/app/build/outputs/apk/debug/app-debug.apk
```
The APK is signed with the debug key, which is fine for your own phone. It is not part of the release pipeline, because the runner has no Android SDK. `npm test` checks how an address typed by hand is read.
## Releases ## Releases
Every merge into `main` can make a release, by itself (`.forgejo/workflows/release.yml`, [semantic-release](https://semantic-release.gitbook.io)). The next version comes from the messages of the commits since the last one, written as [Conventional Commits](https://www.conventionalcommits.org): Every merge into `main` can make a release, by itself (`.forgejo/workflows/release.yml`, [semantic-release](https://semantic-release.gitbook.io)). The next version comes from the messages of the commits since the last one, written as [Conventional Commits](https://www.conventionalcommits.org):

14
android/.gitignore vendored Normal file
View file

@ -0,0 +1,14 @@
node_modules/
# Build output and local settings of the Android project
android/.gradle/
android/build/
android/app/build/
android/local.properties
android/.idea/
android/captures/
android/app/src/main/assets/public/
android/app/src/main/assets/capacitor.config.json
android/app/src/main/assets/capacitor.plugins.json
android/capacitor-cordova-android-plugins/
*.keystore
*.jks

101
android/android/.gitignore vendored Normal file
View file

@ -0,0 +1,101 @@
# Using Android gitignore template: https://github.com/github/gitignore/blob/HEAD/Android.gitignore
# Built application files
*.apk
*.aar
*.ap_
*.aab
# Files for the ART/Dalvik VM
*.dex
# Java class files
*.class
# Generated files
bin/
gen/
out/
# Uncomment the following line in case you need and you don't have the release build type files in your app
# release/
# Gradle files
.gradle/
build/
# Local configuration file (sdk path, etc)
local.properties
# Proguard folder generated by Eclipse
proguard/
# Log Files
*.log
# Android Studio Navigation editor temp files
.navigation/
# Android Studio captures folder
captures/
# IntelliJ
*.iml
.idea/workspace.xml
.idea/tasks.xml
.idea/gradle.xml
.idea/assetWizardSettings.xml
.idea/dictionaries
.idea/libraries
# Android Studio 3 in .gitignore file.
.idea/caches
.idea/modules.xml
# Comment next line if keeping position of elements in Navigation Editor is relevant for you
.idea/navEditor.xml
# Keystore files
# Uncomment the following lines if you do not want to check your keystore files in.
#*.jks
#*.keystore
# External native build folder generated in Android Studio 2.2 and later
.externalNativeBuild
.cxx/
# Google Services (e.g. APIs or Firebase)
# google-services.json
# Freeline
freeline.py
freeline/
freeline_project_description.json
# fastlane
fastlane/report.xml
fastlane/Preview.html
fastlane/screenshots
fastlane/test_output
fastlane/readme.md
# Version control
vcs.xml
# lint
lint/intermediates/
lint/generated/
lint/outputs/
lint/tmp/
# lint/reports/
# Android Profiling
*.hprof
# Cordova plugins for Capacitor
capacitor-cordova-android-plugins
# Copied web assets
app/src/main/assets/public
# Generated Config files
app/src/main/assets/capacitor.config.json
app/src/main/assets/capacitor.plugins.json
app/src/main/res/xml/config.xml

2
android/android/app/.gitignore vendored Normal file
View file

@ -0,0 +1,2 @@
/build/*
!/build/.npmkeep

View file

@ -0,0 +1,55 @@
apply plugin: 'com.android.application'
android {
namespace = "app.sonda"
compileSdk = rootProject.ext.compileSdkVersion
defaultConfig {
applicationId "app.sonda"
minSdkVersion rootProject.ext.minSdkVersion
targetSdkVersion rootProject.ext.targetSdkVersion
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
aaptOptions {
// Files and dirs to omit from the packaged assets dir, modified to accommodate modern web apps.
// Default: https://android.googlesource.com/platform/frameworks/base/+/282e181b58cf72b6ca770dc7ca5f91f135444502/tools/aapt/AaptAssets.cpp#61
ignoreAssetsPattern = '!.svn:!.git:!.ds_store:!*.scc:.*:!CVS:!thumbs.db:!picasa.ini:!*~'
}
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
repositories {
flatDir{
dirs '../capacitor-cordova-android-plugins/src/main/libs', 'libs'
}
}
dependencies {
implementation fileTree(include: ['*.jar'], dir: 'libs')
implementation "androidx.appcompat:appcompat:$androidxAppCompatVersion"
implementation "androidx.coordinatorlayout:coordinatorlayout:$androidxCoordinatorLayoutVersion"
implementation "androidx.core:core-splashscreen:$coreSplashScreenVersion"
implementation "androidx.media:media:1.7.0"
implementation project(':capacitor-android')
testImplementation "junit:junit:$junitVersion"
androidTestImplementation "androidx.test.ext:junit:$androidxJunitVersion"
androidTestImplementation "androidx.test.espresso:espresso-core:$androidxEspressoCoreVersion"
implementation project(':capacitor-cordova-android-plugins')
}
apply from: 'capacitor.build.gradle'
try {
def servicesJSON = file('google-services.json')
if (servicesJSON.text) {
apply plugin: 'com.google.gms.google-services'
}
} catch(Exception e) {
logger.info("google-services.json not found, google-services plugin not applied. Push Notifications won't work")
}

View file

@ -0,0 +1,19 @@
// DO NOT EDIT THIS FILE! IT IS GENERATED EACH TIME "capacitor update" IS RUN
android {
compileOptions {
sourceCompatibility JavaVersion.VERSION_21
targetCompatibility JavaVersion.VERSION_21
}
}
apply from: "../capacitor-cordova-android-plugins/cordova.variables.gradle"
dependencies {
implementation project(':capacitor-app')
}
if (hasProperty('postBuildExtras')) {
postBuildExtras()
}

21
android/android/app/proguard-rules.pro vendored Normal file
View file

@ -0,0 +1,21 @@
# Add project specific ProGuard rules here.
# You can control the set of applied configuration files using the
# proguardFiles setting in build.gradle.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html
# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
# public *;
#}
# Uncomment this to preserve the line number information for
# debugging stack traces.
#-keepattributes SourceFile,LineNumberTable
# If you keep the line number information, uncomment this to
# hide the original source file name.
#-renamesourcefileattribute SourceFile

View file

@ -0,0 +1,50 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:networkSecurityConfig="@xml/network_security_config"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity
android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|smallestScreenSize|screenLayout|uiMode|navigation|density"
android:name=".MainActivity"
android:label="@string/title_activity_main"
android:theme="@style/AppTheme.NoActionBarLaunch"
android:launchMode="singleTask"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name=".MediaService"
android:exported="false"
android:foregroundServiceType="mediaPlayback" />
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="${applicationId}.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths"></meta-data>
</provider>
</application>
<!-- Permissions -->
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_MEDIA_PLAYBACK" />
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
</manifest>

View file

@ -0,0 +1,24 @@
package app.sonda;
import android.os.Bundle;
import android.webkit.WebView;
import com.getcapacitor.BridgeActivity;
public class MainActivity extends BridgeActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
WebView web = getBridge().getWebView();
web.addJavascriptInterface(new SondaNative(this), "SondaNative");
// The buttons of the notification and of the lock screen go back to the page.
MediaService.listener = (name, ms) -> web.post(() -> web.evaluateJavascript(
"window.sondaNativeAction && window.sondaNativeAction('" + name + "'," + ms + ")", null));
}
@Override
public void onDestroy() {
MediaService.listener = null;
if (isFinishing()) MediaService.end(this);
super.onDestroy();
}
}

View file

@ -0,0 +1,219 @@
package app.sonda;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ServiceInfo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.IBinder;
import android.support.v4.media.MediaMetadataCompat;
import android.support.v4.media.session.MediaSessionCompat;
import android.support.v4.media.session.PlaybackStateCompat;
import androidx.core.app.NotificationCompat;
import androidx.core.content.ContextCompat;
import androidx.media.app.NotificationCompat.MediaStyle;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
/**
* Keeps the playback alive while the screen is off or another app is in front, and shows what plays with its
* controls in a notification and on the lock screen. The web app does the playing; this only mirrors it, and
* passes the buttons back through {@link #listener}.
*/
public class MediaService extends Service {
/** Where a press of a button goes: the name is play, pause, next, previous or seekto. */
interface Listener {
void onAction(String name, long ms);
}
static volatile Listener listener;
private static final String CHANNEL = "playback";
private static final int NOTIFICATION_ID = 1;
private static final String PLAY = "app.sonda.PLAY";
private static final String PAUSE = "app.sonda.PAUSE";
private static final String NEXT = "app.sonda.NEXT";
private static final String PREVIOUS = "app.sonda.PREVIOUS";
// The latest word of the page, kept here because the service may start after it was said.
private static NowPlaying latest;
private static MediaService instance;
private MediaSessionCompat session;
private String artworkUrl = "";
private Bitmap artwork;
/** Shows what plays. The first time it starts the service; after that it only updates it. */
static void show(Context context, NowPlaying now) {
latest = now;
if (instance != null) {
instance.apply(now);
} else {
ContextCompat.startForegroundService(context, new Intent(context, MediaService.class));
}
}
/** Nothing plays any more: the notification goes. */
static void end(Context context) {
latest = null;
if (instance != null) instance.shutDown();
else context.stopService(new Intent(context, MediaService.class));
}
@Override
public void onCreate() {
super.onCreate();
instance = this;
createChannel();
session = new MediaSessionCompat(this, "Sonda");
session.setCallback(new MediaSessionCompat.Callback() {
@Override public void onPlay() { send("play", 0); }
@Override public void onPause() { send("pause", 0); }
@Override public void onSkipToNext() { send("next", 0); }
@Override public void onSkipToPrevious() { send("previous", 0); }
@Override public void onSeekTo(long pos) { send("seekto", pos); }
});
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
String action = intent == null ? null : intent.getAction();
if (PLAY.equals(action)) send("play", 0);
else if (PAUSE.equals(action)) send("pause", 0);
else if (NEXT.equals(action)) send("next", 0);
else if (PREVIOUS.equals(action)) send("previous", 0);
if (latest != null) {
apply(latest);
} else {
// Started with nothing to show, or after the app was killed: Android wants a notification anyway, then it goes.
startForeground(NOTIFICATION_ID, notification(null));
shutDown();
}
return START_NOT_STICKY;
}
/** The person swiped the app away: the page is gone, so the music and its notification go too. */
@Override
public void onTaskRemoved(Intent rootIntent) {
latest = null;
shutDown();
}
@Override
public void onDestroy() {
instance = null;
if (session != null) {
session.setActive(false);
session.release();
session = null;
}
super.onDestroy();
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
private void send(String name, long ms) {
Listener l = listener;
if (l != null) l.onAction(name, ms);
}
private void shutDown() {
stopForeground(STOP_FOREGROUND_REMOVE);
stopSelf();
}
private void apply(NowPlaying now) {
session.setMetadata(
new MediaMetadataCompat.Builder()
.putString(MediaMetadataCompat.METADATA_KEY_TITLE, now.title)
.putString(MediaMetadataCompat.METADATA_KEY_ARTIST, now.artist)
.putString(MediaMetadataCompat.METADATA_KEY_ALBUM, now.album)
.putLong(MediaMetadataCompat.METADATA_KEY_DURATION, now.durationMs)
.putBitmap(MediaMetadataCompat.METADATA_KEY_ALBUM_ART, now.artworkUrl.equals(artworkUrl) ? artwork : null)
.build());
long actions = PlaybackStateCompat.ACTION_PLAY | PlaybackStateCompat.ACTION_PAUSE | PlaybackStateCompat.ACTION_PLAY_PAUSE
| PlaybackStateCompat.ACTION_SKIP_TO_NEXT | PlaybackStateCompat.ACTION_SKIP_TO_PREVIOUS | PlaybackStateCompat.ACTION_SEEK_TO;
session.setPlaybackState(
new PlaybackStateCompat.Builder()
.setActions(actions)
.setState(now.playing ? PlaybackStateCompat.STATE_PLAYING : PlaybackStateCompat.STATE_PAUSED, now.positionNow(), now.playing ? 1f : 0f)
.build());
session.setActive(true);
Notification n = notification(now);
if (Build.VERSION.SDK_INT >= 29) {
startForeground(NOTIFICATION_ID, n, ServiceInfo.FOREGROUND_SERVICE_TYPE_MEDIA_PLAYBACK);
} else {
startForeground(NOTIFICATION_ID, n);
}
if (!now.artworkUrl.isEmpty() && !now.artworkUrl.equals(artworkUrl)) fetchArtwork(now.artworkUrl);
}
private Notification notification(NowPlaying now) {
NotificationCompat.Builder b = new NotificationCompat.Builder(this, CHANNEL)
.setSmallIcon(R.drawable.ic_stat_sonda)
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
.setOnlyAlertOnce(true)
.setShowWhen(false)
.setContentIntent(PendingIntent.getActivity(
this, 0, new Intent(this, MainActivity.class).setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT));
if (now == null) return b.setContentTitle("Sonda").build();
b.setContentTitle(now.title).setContentText(now.artist).setSubText(now.album);
if (now.artworkUrl.equals(artworkUrl) && artwork != null) b.setLargeIcon(artwork);
b.addAction(android.R.drawable.ic_media_previous, getString(R.string.previous), button(PREVIOUS));
if (now.playing) b.addAction(android.R.drawable.ic_media_pause, getString(R.string.pause), button(PAUSE));
else b.addAction(android.R.drawable.ic_media_play, getString(R.string.play), button(PLAY));
b.addAction(android.R.drawable.ic_media_next, getString(R.string.next), button(NEXT));
b.setStyle(new MediaStyle().setMediaSession(session.getSessionToken()).setShowActionsInCompactView(0, 1, 2));
return b.build();
}
private PendingIntent button(String action) {
return PendingIntent.getService(
this, action.hashCode(), new Intent(this, MediaService.class).setAction(action), PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT);
}
private void createChannel() {
if (Build.VERSION.SDK_INT < 26) return;
NotificationChannel channel = new NotificationChannel(CHANNEL, getString(R.string.channel_playback), NotificationManager.IMPORTANCE_LOW);
channel.setShowBadge(false);
getSystemService(NotificationManager.class).createNotificationChannel(channel);
}
/** The cover comes from the server with the token in its address; a cover that does not come leaves the notification without one. */
private void fetchArtwork(String url) {
artworkUrl = url;
artwork = null;
new Thread(() -> {
Bitmap bitmap = null;
try {
HttpURLConnection c = (HttpURLConnection) new URL(url).openConnection();
c.setConnectTimeout(8000);
c.setReadTimeout(8000);
try (InputStream in = c.getInputStream()) {
bitmap = BitmapFactory.decodeStream(in);
} finally {
c.disconnect();
}
} catch (Exception ignored) {
// No cover: the notification stays as it is.
}
final Bitmap result = bitmap;
ContextCompat.getMainExecutor(this).execute(() -> {
if (instance != this || !url.equals(artworkUrl) || result == null) return;
artwork = result;
if (latest != null) apply(latest);
});
}).start();
}
}

View file

@ -0,0 +1,51 @@
package app.sonda;
import android.os.SystemClock;
import org.json.JSONException;
import org.json.JSONObject;
/** What the web app says is playing: the song, whether it plays and where it is. */
final class NowPlaying {
final String title;
final String artist;
final String album;
final String artworkUrl;
final boolean playing;
final long durationMs;
private final long positionMs;
private final long receivedAt;
private NowPlaying(String title, String artist, String album, String artworkUrl, boolean playing, long positionMs, long durationMs) {
this.title = title;
this.artist = artist;
this.album = album;
this.artworkUrl = artworkUrl;
this.playing = playing;
this.positionMs = positionMs;
this.durationMs = durationMs;
this.receivedAt = SystemClock.elapsedRealtime();
}
/** Where the song is now: what the page said, plus the time that has passed if it plays. */
long positionNow() {
long position = playing ? positionMs + (SystemClock.elapsedRealtime() - receivedAt) : positionMs;
return durationMs > 0 ? Math.min(position, durationMs) : position;
}
/** The JSON the page sends; null when it is not what was expected. */
static NowPlaying parse(String json) {
try {
JSONObject o = new JSONObject(json);
return new NowPlaying(
o.optString("title"),
o.optString("artist"),
o.optString("album"),
o.optString("artworkUrl"),
o.optBoolean("playing"),
Math.max(0, o.optLong("positionMs")),
Math.max(0, o.optLong("durationMs")));
} catch (JSONException e) {
return null;
}
}
}

View file

@ -0,0 +1,47 @@
package app.sonda;
import android.Manifest;
import android.app.Activity;
import android.content.pm.PackageManager;
import android.os.Build;
import android.webkit.JavascriptInterface;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
/**
* What the web page can ask of the app. A WebView has no Media Session API, so the page tells the app what plays
* and the app keeps a notification with the controls, and the playback alive while the screen is off.
* It is on every page the WebView loads, which is the server the person chose.
*/
final class SondaNative {
private final Activity activity;
private boolean askedForNotifications = false;
SondaNative(Activity activity) {
this.activity = activity;
}
@JavascriptInterface
public void update(String json) {
NowPlaying now = NowPlaying.parse(json);
if (now == null) return;
activity.runOnUiThread(() -> {
askForNotifications();
MediaService.show(activity, now);
});
}
@JavascriptInterface
public void stop() {
activity.runOnUiThread(() -> MediaService.end(activity));
}
/** From Android 13 a notification needs a yes. Without it the playback goes on, only the notification is hidden. */
private void askForNotifications() {
if (askedForNotifications || Build.VERSION.SDK_INT < 33) return;
askedForNotifications = true;
if (ContextCompat.checkSelfPermission(activity, Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(activity, new String[] {Manifest.permission.POST_NOTIFICATIONS}, 1);
}
}
}

View file

@ -0,0 +1,10 @@
<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:fillColor="#FFFFFFFF"
android:pathData="M12,3v10.55c-0.59,-0.34 -1.27,-0.55 -2,-0.55 -2.21,0 -4,1.79 -4,4s1.79,4 4,4 4,-1.79 4,-4V7h4V3h-6z" />
</vector>

View file

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<color android:color="#08161D" />
</item>
</layer-list>

View file

@ -0,0 +1,12 @@
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<WebView
android:layout_width="match_parent"
android:layout_height="match_parent" />
</androidx.coordinatorlayout.widget.CoordinatorLayout>

View file

@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
<background android:drawable="@color/ic_launcher_background"/>
<foreground android:drawable="@mipmap/ic_launcher_foreground"/>
</adaptive-icon>

View file

@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
<background android:drawable="@color/ic_launcher_background"/>
<foreground android:drawable="@mipmap/ic_launcher_foreground"/>
</adaptive-icon>

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.2 KiB

Some files were not shown because too many files have changed in this diff Show more