Compare commits

..
96 changed files with 98 additions and 4130 deletions

View file

@ -1,38 +1,5 @@
# 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)
### Features

View file

@ -1,9 +1,5 @@
# 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.
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.
@ -394,7 +390,7 @@ Back up the database and `sonda.toml`. Your music stays wherever you keep it.
## 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. 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.
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.
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`):
@ -408,25 +404,6 @@ 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`.
## 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
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
View file

@ -1,14 +0,0 @@
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

View file

@ -1,101 +0,0 @@
# 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

View file

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

View file

@ -1,55 +0,0 @@
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

@ -1,19 +0,0 @@
// 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()
}

View file

@ -1,21 +0,0 @@
# 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

@ -1,50 +0,0 @@
<?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

@ -1,24 +0,0 @@
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

@ -1,219 +0,0 @@
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

@ -1,51 +0,0 @@
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

@ -1,47 +0,0 @@
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

@ -1,10 +0,0 @@
<?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

@ -1,6 +0,0 @@
<?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

@ -1,12 +0,0 @@
<?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

@ -1,5 +0,0 @@
<?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

@ -1,5 +0,0 @@
<?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.

Before

Width:  |  Height:  |  Size: 3.9 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 8.2 KiB

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