Bläddra i källkod

增加Apk,未来扩展成管理本地目录能力

sequoia00 2 veckor sedan
förälder
incheckning
7fdc767eb8

+ 10 - 1
.gitignore

@@ -3,4 +3,13 @@ __pycache__/
 .*
 !.gitignore
 /mp3file/
-nohup.out
+nohup.out
+
+# Android APK project generated files
+/apk/.gradle/
+/apk/build/
+/apk/app/build/
+/apk/local.properties
+/apk/**/*.apk
+/apk/**/*.aab
+/apk/**/*.ap_

+ 48 - 0
apk/app/build.gradle.kts

@@ -0,0 +1,48 @@
+plugins {
+    id("com.android.application")
+    id("org.jetbrains.kotlin.android")
+}
+
+android {
+    namespace = "com.musicweb.player"
+    compileSdk = 35
+
+    defaultConfig {
+        applicationId = "com.musicweb.player"
+        minSdk = 24
+        targetSdk = 35
+        versionCode = 1
+        versionName = "1.0"
+    }
+
+    buildTypes {
+        release {
+            isMinifyEnabled = false
+            proguardFiles(
+                getDefaultProguardFile("proguard-android-optimize.txt"),
+                "proguard-rules.pro"
+            )
+        }
+    }
+
+    compileOptions {
+        sourceCompatibility = JavaVersion.VERSION_17
+        targetCompatibility = JavaVersion.VERSION_17
+    }
+    kotlinOptions {
+        jvmTarget = "17"
+    }
+
+    buildFeatures {
+        viewBinding = true
+    }
+}
+
+dependencies {
+    implementation("androidx.core:core-ktx:1.13.1")
+    implementation("androidx.appcompat:appcompat:1.7.0")
+    implementation("com.google.android.material:material:1.12.0")
+    implementation("androidx.media:media:1.7.0")
+    implementation("androidx.media3:media3-exoplayer:1.4.1")
+    implementation("androidx.media3:media3-session:1.4.1")
+}

+ 1 - 0
apk/app/proguard-rules.pro

@@ -0,0 +1 @@
+# Intentionally empty.

+ 38 - 0
apk/app/src/main/AndroidManifest.xml

@@ -0,0 +1,38 @@
+<?xml version="1.0" encoding="utf-8"?>
+<manifest xmlns:android="http://schemas.android.com/apk/res/android">
+
+    <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" />
+
+    <application
+        android:allowBackup="true"
+        android:label="@string/app_name"
+        android:icon="@mipmap/ic_launcher"
+        android:roundIcon="@mipmap/ic_launcher_round"
+        android:supportsRtl="true"
+        android:usesCleartextTraffic="true"
+        android:theme="@style/Theme.MusicWebPlayer">
+        <service
+            android:name=".player.PlayerService"
+            android:exported="false"
+            android:foregroundServiceType="mediaPlayback" />
+        <receiver
+            android:name=".player.MediaButtonReceiver"
+            android:exported="true">
+            <intent-filter>
+                <action android:name="android.intent.action.MEDIA_BUTTON" />
+            </intent-filter>
+        </receiver>
+        <activity
+            android:name=".MainActivity"
+            android:exported="true">
+            <intent-filter>
+                <action android:name="android.intent.action.MAIN" />
+                <category android:name="android.intent.category.LAUNCHER" />
+            </intent-filter>
+        </activity>
+    </application>
+
+</manifest>

+ 314 - 0
apk/app/src/main/java/com/musicweb/player/MainActivity.kt

@@ -0,0 +1,314 @@
+package com.musicweb.player
+
+import android.annotation.SuppressLint
+import android.content.BroadcastReceiver
+import android.content.Context
+import android.content.Intent
+import android.content.IntentFilter
+import android.os.Bundle
+import android.view.ViewGroup
+import android.webkit.JavascriptInterface
+import android.webkit.WebChromeClient
+import android.webkit.WebResourceRequest
+import android.webkit.WebSettings
+import android.webkit.WebView
+import android.webkit.WebViewClient
+import android.widget.EditText
+import android.widget.LinearLayout
+import androidx.appcompat.app.AppCompatActivity
+import androidx.core.content.ContextCompat
+import com.google.android.material.dialog.MaterialAlertDialogBuilder
+import com.musicweb.player.player.PlayerService
+
+class MainActivity : AppCompatActivity() {
+    private lateinit var webView: WebView
+    private val prefs by lazy { getSharedPreferences("musicweb_apk", MODE_PRIVATE) }
+    private val playbackReceiver = object : BroadcastReceiver() {
+        override fun onReceive(context: Context?, intent: Intent?) {
+            if (intent?.action != PlayerService.ACTION_PLAYBACK_STATE || !this@MainActivity::webView.isInitialized) return
+            val isPlaying = intent.getBooleanExtra(PlayerService.EXTRA_IS_PLAYING, false)
+            val position = intent.getLongExtra(PlayerService.EXTRA_POSITION, 0L)
+            val duration = intent.getLongExtra(PlayerService.EXTRA_DURATION, 0L)
+            val index = intent.getIntExtra(PlayerService.EXTRA_CURRENT_INDEX, -1)
+            val name = intent.getStringExtra(PlayerService.EXTRA_TRACK_NAME).orEmpty()
+            val path = intent.getStringExtra(PlayerService.EXTRA_TRACK_PATH).orEmpty()
+            val error = intent.getStringExtra(PlayerService.EXTRA_ERROR).orEmpty()
+            runOnUiThread {
+                val script = """
+                    window.__musicwebNativeUpdate && window.__musicwebNativeUpdate({
+                      isPlaying: $isPlaying,
+                      position: $position,
+                      duration: $duration,
+                      index: $index,
+                      name: ${name.quoteForJs()},
+                      path: ${path.quoteForJs()},
+                      error: ${error.quoteForJs()}
+                    });
+                """.trimIndent()
+                webView.evaluateJavascript(script, null)
+            }
+        }
+    }
+
+    @SuppressLint("SetJavaScriptEnabled")
+    override fun onCreate(savedInstanceState: Bundle?) {
+        super.onCreate(savedInstanceState)
+
+        webView = WebView(this).apply {
+            layoutParams = ViewGroup.LayoutParams(
+                ViewGroup.LayoutParams.MATCH_PARENT,
+                ViewGroup.LayoutParams.MATCH_PARENT
+            )
+            settings.apply {
+                javaScriptEnabled = true
+                domStorageEnabled = true
+                cacheMode = WebSettings.LOAD_DEFAULT
+                mediaPlaybackRequiresUserGesture = false
+                mixedContentMode = WebSettings.MIXED_CONTENT_ALWAYS_ALLOW
+                allowFileAccess = true
+                allowContentAccess = true
+            }
+            WebView.setWebContentsDebuggingEnabled(true)
+            addJavascriptInterface(Bridge(), "AndroidPlayer")
+            webViewClient = object : WebViewClient() {
+                override fun shouldOverrideUrlLoading(view: WebView?, request: WebResourceRequest?) = false
+                override fun onPageFinished(view: WebView?, url: String?) {
+                    super.onPageFinished(view, url)
+                    injectBridge()
+                }
+            }
+            webChromeClient = WebChromeClient()
+        }
+        setContentView(webView)
+
+        if (prefs.getString(KEY_BASE_URL, null).isNullOrBlank()) {
+            promptForUrl()
+        } else {
+            webView.loadUrl(requireBaseUrl())
+        }
+    }
+
+    override fun onBackPressed() {
+        if (this::webView.isInitialized && webView.canGoBack()) webView.goBack() else super.onBackPressed()
+    }
+
+    override fun onStart() {
+        super.onStart()
+        ContextCompat.registerReceiver(
+            this,
+            playbackReceiver,
+            IntentFilter(PlayerService.ACTION_PLAYBACK_STATE),
+            ContextCompat.RECEIVER_NOT_EXPORTED
+        )
+    }
+
+    override fun onStop() {
+        unregisterReceiver(playbackReceiver)
+        super.onStop()
+    }
+
+    private fun requireBaseUrl(): String {
+        return prefs.getString(KEY_BASE_URL, DEFAULT_BASE_URL)?.trim().orEmpty()
+            .ifBlank { DEFAULT_BASE_URL }
+            .trimEnd('/')
+    }
+
+    private fun promptForUrl() {
+        val input = EditText(this).apply {
+            setText(DEFAULT_BASE_URL)
+            setSelection(text.length)
+        }
+        val container = LinearLayout(this).apply {
+            setPadding(48, 32, 48, 0)
+            addView(input)
+        }
+        MaterialAlertDialogBuilder(this)
+            .setTitle(R.string.set_server_title)
+            .setMessage(R.string.set_server_message)
+            .setView(container)
+            .setCancelable(false)
+            .setPositiveButton(android.R.string.ok) { _, _ ->
+                val url = input.text?.toString()?.trim().orEmpty().ifBlank { DEFAULT_BASE_URL }
+                prefs.edit().putString(KEY_BASE_URL, url).apply()
+                webView.loadUrl(url.trimEnd('/'))
+            }
+            .show()
+    }
+
+    private fun injectBridge() {
+        val script = """
+            (function() {
+              if (window.__musicwebNativeBridgeInstalled) return;
+              window.__musicwebNativeBridgeInstalled = true;
+              const absoluteUrl = (url) => {
+                try {
+                  const parsed = new URL(url || "", window.location.href);
+                  parsed.pathname = parsed.pathname
+                    .split('/')
+                    .map(part => encodeURIComponent(decodeURIComponent(part)))
+                    .join('/');
+                  return parsed.toString();
+                } catch (e) {
+                  return url || "";
+                }
+              };
+              const toQueueJson = () => JSON.stringify((state.currentQueue || []).map(t => ({
+                path: t.path || "",
+                url: absoluteUrl(t.url || ""),
+                name: t.name || "",
+                folder: t.folder || ""
+              })));
+              const updateNativeUi = (index) => {
+                if (!state.currentQueue.length) return;
+                state.currentTrackIndex = index;
+                const track = state.currentQueue[index];
+                if (typeof updateDock === 'function') updateDock(track);
+                if (typeof renderQueue === 'function') renderQueue();
+                if (typeof savePlaybackState === 'function') savePlaybackState();
+              };
+              const sync = () => {
+                if (window.AndroidPlayer && state.currentQueue && state.currentQueue.length) {
+                  AndroidPlayer.setQueue(toQueueJson(), Number(state.currentTrackIndex || 0));
+                }
+              };
+              const formatNativeTime = (ms) => {
+                const total = Math.max(0, Math.floor((Number(ms) || 0) / 1000));
+                const minutes = Math.floor(total / 60);
+                const seconds = total % 60;
+                return String(minutes).padStart(2, '0') + ':' + String(seconds).padStart(2, '0');
+              };
+              window.__musicwebNativeUpdate = function(payload) {
+                const playing = !!payload.isPlaying;
+                const toggle = document.getElementById('playToggleBtn');
+                const playIcon = document.querySelector('.icon-play');
+                const pauseIcon = document.querySelector('.icon-pause');
+                if (toggle) {
+                  toggle.classList.toggle('is-playing', playing);
+                  toggle.dataset.tip = playing ? '暂停' : '播放';
+                }
+                if (playIcon) playIcon.classList.toggle('is-hidden', playing);
+                if (pauseIcon) pauseIcon.classList.toggle('is-hidden', !playing);
+                if (payload.index >= 0 && state.currentQueue && state.currentQueue[payload.index]) {
+                  state.currentTrackIndex = payload.index;
+                  if (typeof renderQueue === 'function') renderQueue();
+                }
+                const duration = Number(payload.duration || 0);
+                const position = Number(payload.position || 0);
+                const progress = duration > 0 ? (position / duration) * 100 : 0;
+                const bar = document.getElementById('progressBar');
+                if (bar) bar.value = String(Math.max(0, Math.min(100, progress)));
+                const currentLabel = document.getElementById('currentTimeLabel');
+                const durationLabel = document.getElementById('durationLabel');
+                if (currentLabel) currentLabel.textContent = formatNativeTime(position);
+                if (durationLabel) durationLabel.textContent = formatNativeTime(duration);
+                if (payload.name) {
+                  const title = document.getElementById('dockTitle');
+                  const dockPath = document.getElementById('dockPath');
+                  const nowTitle = document.getElementById('nowTitle');
+                  const nowMeta = document.getElementById('nowMeta');
+                  if (title) title.textContent = payload.name;
+                  if (dockPath) dockPath.textContent = payload.path || '';
+                  if (nowTitle) nowTitle.textContent = payload.name;
+                  if (nowMeta) nowMeta.textContent = payload.path || '';
+                }
+              };
+              window.startQueue = function(tracks, index) {
+                if (!tracks || !tracks.length) return;
+                state.currentQueue = [...tracks];
+                updateNativeUi(index);
+                AndroidPlayer.playQueue(toQueueJson(), Number(state.currentTrackIndex || 0));
+              };
+              window.playTrack = function(index) {
+                if (!state.currentQueue.length) return;
+                updateNativeUi(index);
+                AndroidPlayer.playQueue(toQueueJson(), Number(state.currentTrackIndex || 0));
+              };
+              window.playPrevious = function() { AndroidPlayer.previous(); };
+              window.playNext = function() { AndroidPlayer.next(); };
+              window.nextTrack = function() { AndroidPlayer.next(); };
+              const playBtn = document.getElementById('playToggleBtn');
+              if (playBtn && !playBtn.dataset.nativeBound) {
+                playBtn.dataset.nativeBound = '1';
+                playBtn.onclick = function() { AndroidPlayer.toggle(); };
+              }
+              const prevBtn = document.getElementById('prevBtn');
+              if (prevBtn && !prevBtn.dataset.nativeBound) {
+                prevBtn.dataset.nativeBound = '1';
+                prevBtn.onclick = function() { AndroidPlayer.previous(); };
+              }
+              const nextBtn = document.getElementById('nextBtn');
+              if (nextBtn && !nextBtn.dataset.nativeBound) {
+                nextBtn.dataset.nativeBound = '1';
+                nextBtn.onclick = function() { AndroidPlayer.next(); };
+              }
+              sync();
+            })();
+        """.trimIndent()
+        webView.evaluateJavascript(script, null)
+    }
+
+    inner class Bridge {
+        @JavascriptInterface
+        fun setQueue(queueJson: String, index: Int) {
+            val intent = Intent(this@MainActivity, PlayerService::class.java).apply {
+                action = PlayerService.ACTION_SET_QUEUE
+                putExtra(PlayerService.EXTRA_QUEUE_JSON, queueJson)
+                putExtra(PlayerService.EXTRA_INDEX, index)
+            }
+            startService(intent)
+        }
+
+        @JavascriptInterface
+        fun playQueue(queueJson: String, index: Int) {
+            val intent = Intent(this@MainActivity, PlayerService::class.java).apply {
+                action = PlayerService.ACTION_PLAY_QUEUE
+                putExtra(PlayerService.EXTRA_QUEUE_JSON, queueJson)
+                putExtra(PlayerService.EXTRA_INDEX, index)
+            }
+            ContextCompat.startForegroundService(this@MainActivity, intent)
+        }
+
+        @JavascriptInterface
+        fun toggle() {
+            startService(Intent(this@MainActivity, PlayerService::class.java).apply {
+                action = PlayerService.ACTION_TOGGLE
+            })
+        }
+
+        @JavascriptInterface
+        fun next() {
+            startService(Intent(this@MainActivity, PlayerService::class.java).apply {
+                action = PlayerService.ACTION_NEXT
+            })
+        }
+
+        @JavascriptInterface
+        fun previous() {
+            startService(Intent(this@MainActivity, PlayerService::class.java).apply {
+                action = PlayerService.ACTION_PREVIOUS
+            })
+        }
+    }
+
+    companion object {
+        private const val KEY_BASE_URL = "base_url"
+        private const val DEFAULT_BASE_URL = "http://110.42.102.94:8006/"
+    }
+}
+
+private fun String.quoteForJs(): String {
+    return buildString {
+        append('"')
+        this@quoteForJs.forEach { char ->
+            when (char) {
+                '\\' -> append("\\\\")
+                '"' -> append("\\\"")
+                '\n' -> append("\\n")
+                '\r' -> append("\\r")
+                '\t' -> append("\\t")
+                else -> append(char)
+            }
+        }
+        append('"')
+    }
+}

+ 30 - 0
apk/app/src/main/java/com/musicweb/player/player/MediaButtonReceiver.kt

@@ -0,0 +1,30 @@
+package com.musicweb.player.player
+
+import android.content.BroadcastReceiver
+import android.content.Context
+import android.content.Intent
+import android.view.KeyEvent
+import androidx.core.content.ContextCompat
+
+class MediaButtonReceiver : BroadcastReceiver() {
+    override fun onReceive(context: Context, intent: Intent) {
+        if (intent.action != Intent.ACTION_MEDIA_BUTTON) return
+        val event = intent.getParcelableExtra<KeyEvent>(Intent.EXTRA_KEY_EVENT) ?: return
+        if (event.action != KeyEvent.ACTION_UP) return
+
+        val action = when (event.keyCode) {
+            KeyEvent.KEYCODE_MEDIA_PLAY,
+            KeyEvent.KEYCODE_MEDIA_PAUSE,
+            KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE,
+            KeyEvent.KEYCODE_HEADSETHOOK -> PlayerService.ACTION_TOGGLE
+            KeyEvent.KEYCODE_MEDIA_NEXT -> PlayerService.ACTION_NEXT
+            KeyEvent.KEYCODE_MEDIA_PREVIOUS -> PlayerService.ACTION_PREVIOUS
+            else -> return
+        }
+
+        ContextCompat.startForegroundService(
+            context,
+            Intent(context, PlayerService::class.java).apply { this.action = action }
+        )
+    }
+}

+ 291 - 0
apk/app/src/main/java/com/musicweb/player/player/PlayerService.kt

@@ -0,0 +1,291 @@
+package com.musicweb.player.player
+
+import android.app.Notification
+import android.app.NotificationChannel
+import android.app.NotificationManager
+import android.app.PendingIntent
+import android.content.Context
+import android.content.Intent
+import android.net.Uri
+import android.os.Build
+import android.os.Handler
+import android.os.IBinder
+import android.os.Looper
+import android.util.Log
+import androidx.core.app.NotificationCompat
+import androidx.core.content.getSystemService
+import androidx.media3.common.MediaItem
+import androidx.media3.common.MediaMetadata
+import androidx.media3.common.MimeTypes
+import androidx.media3.common.PlaybackException
+import androidx.media3.common.Player
+import androidx.media3.exoplayer.ExoPlayer
+import androidx.media3.session.MediaStyleNotificationHelper
+import androidx.media3.session.MediaSession
+import androidx.media3.session.MediaSessionService
+import com.musicweb.player.MainActivity
+import com.musicweb.player.R
+import org.json.JSONArray
+
+data class TrackItem(
+    val path: String,
+    val url: String,
+    val name: String,
+    val folder: String? = null,
+)
+
+class PlayerService : MediaSessionService() {
+    private lateinit var player: ExoPlayer
+    private lateinit var mediaSession: MediaSession
+    private val queue = mutableListOf<TrackItem>()
+    private var lastErrorMessage: String? = null
+    private val progressHandler = Handler(Looper.getMainLooper())
+    private val progressRunnable = object : Runnable {
+        override fun run() {
+            broadcastPlaybackState()
+            progressHandler.postDelayed(this, 1000L)
+        }
+    }
+
+    override fun onCreate() {
+        super.onCreate()
+        createChannel()
+        player = ExoPlayer.Builder(this).build().apply {
+            addListener(object : Player.Listener {
+                override fun onIsPlayingChanged(isPlaying: Boolean) {
+                    updateNotification()
+                    broadcastPlaybackState()
+                }
+
+                override fun onPlayerError(error: PlaybackException) {
+                    lastErrorMessage = error.message ?: error.errorCodeName
+                    Log.e(TAG, "playback failed", error)
+                    updateNotification()
+                    broadcastPlaybackState()
+                }
+
+                override fun onPlaybackStateChanged(playbackState: Int) {
+                    broadcastPlaybackState()
+                }
+
+                override fun onMediaItemTransition(mediaItem: MediaItem?, reason: Int) {
+                    broadcastPlaybackState()
+                }
+            })
+        }
+        mediaSession = MediaSession.Builder(this, player).build()
+        progressHandler.post(progressRunnable)
+    }
+
+    override fun onBind(intent: Intent?): IBinder? {
+        updateNotification()
+        return super.onBind(intent)
+    }
+
+    override fun onGetSession(controllerInfo: MediaSession.ControllerInfo): MediaSession = mediaSession
+
+    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
+        when (intent?.action) {
+            ACTION_SET_QUEUE -> {
+                val items = parseQueue(intent.getStringExtra(EXTRA_QUEUE_JSON).orEmpty())
+                val index = intent.getIntExtra(EXTRA_INDEX, 0)
+                setQueue(items, index, playWhenReady = false)
+            }
+            ACTION_PLAY_QUEUE -> {
+                val items = parseQueue(intent.getStringExtra(EXTRA_QUEUE_JSON).orEmpty())
+                val index = intent.getIntExtra(EXTRA_INDEX, 0)
+                setQueue(items, index, playWhenReady = true)
+            }
+            ACTION_TOGGLE -> toggle()
+            ACTION_NEXT -> next()
+            ACTION_PREVIOUS -> previous()
+        }
+        updateNotification()
+        return START_STICKY
+    }
+
+    override fun onDestroy() {
+        progressHandler.removeCallbacks(progressRunnable)
+        mediaSession.release()
+        player.release()
+        super.onDestroy()
+    }
+
+    private fun setQueue(items: List<TrackItem>, index: Int, playWhenReady: Boolean) {
+        if (items.isEmpty()) return
+        lastErrorMessage = null
+        queue.clear()
+        queue.addAll(items)
+        val mediaItems = queue.map { item ->
+            MediaItem.Builder()
+                .setUri(item.url)
+                .setMediaId(item.path)
+                .setMimeType(mimeTypeFor(item.url, item.path))
+                .setMediaMetadata(
+                    MediaMetadata.Builder()
+                        .setTitle(item.name)
+                        .setArtist(item.folder.orEmpty())
+                        .build()
+                )
+                .build()
+        }
+        val safeIndex = index.coerceIn(0, mediaItems.lastIndex)
+        Log.d(TAG, "setQueue size=${mediaItems.size}, index=$safeIndex, url=${queue[safeIndex].url}")
+        player.setMediaItems(mediaItems, safeIndex, 0L)
+        player.prepare()
+        if (playWhenReady) player.play()
+        broadcastPlaybackState()
+    }
+
+    private fun toggle() {
+        if (player.isPlaying) player.pause() else player.play()
+    }
+
+    private fun next() {
+        if (player.hasNextMediaItem()) player.seekToNextMediaItem()
+        player.play()
+    }
+
+    private fun previous() {
+        if (player.hasPreviousMediaItem()) player.seekToPreviousMediaItem() else player.seekTo(0, 0L)
+        player.play()
+    }
+
+    private fun updateNotification() {
+        startForeground(NOTIFICATION_ID, buildNotification())
+    }
+
+    private fun broadcastPlaybackState() {
+        val duration = player.duration.takeIf { it > 0 } ?: 0L
+        val position = player.currentPosition.coerceAtLeast(0L)
+        val current = queue.getOrNull(player.currentMediaItemIndex)
+        sendBroadcast(
+            Intent(ACTION_PLAYBACK_STATE).apply {
+                setPackage(packageName)
+                putExtra(EXTRA_IS_PLAYING, player.isPlaying)
+                putExtra(EXTRA_POSITION, position)
+                putExtra(EXTRA_DURATION, duration)
+                putExtra(EXTRA_CURRENT_INDEX, player.currentMediaItemIndex)
+                putExtra(EXTRA_TRACK_NAME, current?.name.orEmpty())
+                putExtra(EXTRA_TRACK_PATH, current?.path.orEmpty())
+                putExtra(EXTRA_ERROR, lastErrorMessage.orEmpty())
+            }
+        )
+    }
+
+    private fun buildNotification(): Notification {
+        val openIntent = PendingIntent.getActivity(
+            this,
+            0,
+            Intent(this, MainActivity::class.java),
+            PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT
+        )
+        val playing = player.isPlaying
+        val title = queue.getOrNull(player.currentMediaItemIndex)?.name ?: getString(R.string.app_name)
+        return NotificationCompat.Builder(this, CHANNEL_ID)
+            .setSmallIcon(R.mipmap.ic_launcher)
+            .setContentTitle(title)
+            .setContentText(lastErrorMessage ?: if (playing) "正在播放" else "已暂停")
+            .setContentIntent(openIntent)
+            .setOngoing(playing)
+            .setOnlyAlertOnce(true)
+            .setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
+            .setStyle(
+                MediaStyleNotificationHelper.MediaStyle(mediaSession)
+                    .setShowActionsInCompactView(0, 1, 2)
+            )
+            .addAction(android.R.drawable.ic_media_previous, "上一曲", commandIntent(ACTION_PREVIOUS, 1))
+            .addAction(
+                if (playing) android.R.drawable.ic_media_pause else android.R.drawable.ic_media_play,
+                if (playing) "暂停" else "播放",
+                commandIntent(ACTION_TOGGLE, 2)
+            )
+            .addAction(android.R.drawable.ic_media_next, "下一曲", commandIntent(ACTION_NEXT, 3))
+            .build()
+    }
+
+    private fun commandIntent(action: String, requestCode: Int): PendingIntent {
+        val intent = Intent(this, PlayerService::class.java).apply { this.action = action }
+        return PendingIntent.getService(
+            this,
+            requestCode,
+            intent,
+            PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT
+        )
+    }
+
+    private fun createChannel() {
+        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) return
+        val manager = getSystemService<NotificationManager>() ?: return
+        manager.createNotificationChannel(
+            NotificationChannel(CHANNEL_ID, "Music Playback", NotificationManager.IMPORTANCE_LOW)
+        )
+    }
+
+    private fun parseQueue(json: String): List<TrackItem> {
+        if (json.isBlank()) return emptyList()
+        val array = JSONArray(json)
+        return buildList(array.length()) {
+            for (i in 0 until array.length()) {
+                val item = array.getJSONObject(i)
+                add(
+                    TrackItem(
+                        path = item.optString("path"),
+                        url = normalizeUrl(item.optString("url")),
+                        name = item.optString("name"),
+                        folder = item.optString("folder").takeIf { it.isNotBlank() },
+                    )
+                )
+            }
+        }
+    }
+
+    private fun normalizeUrl(url: String): String {
+        val raw = if (url.startsWith("http://") || url.startsWith("https://")) {
+            url
+        } else {
+            val uri = Uri.parse(url)
+            val path = uri.toString().ifBlank { return url }
+            "$DEFAULT_BASE_URL${path.trimStart('/')}"
+        }
+        val parsed = Uri.parse(raw)
+        val encodedPath = parsed.pathSegments.joinToString("/", prefix = "/") { Uri.encode(it) }
+        return parsed.buildUpon().encodedPath(encodedPath).build().toString()
+    }
+
+    private fun mimeTypeFor(url: String, path: String): String? {
+        val value = "$path $url".lowercase()
+        return when {
+            value.contains(".m4a") || value.contains(".mp4") -> MimeTypes.AUDIO_MP4
+            value.contains(".aac") -> MimeTypes.AUDIO_AAC
+            value.contains(".mp3") -> MimeTypes.AUDIO_MPEG
+            value.contains(".ogg") || value.contains(".oga") -> MimeTypes.AUDIO_OGG
+            value.contains(".opus") -> MimeTypes.AUDIO_OPUS
+            value.contains(".wav") -> MimeTypes.AUDIO_WAV
+            value.contains(".flac") -> MimeTypes.AUDIO_FLAC
+            else -> null
+        }
+    }
+
+    companion object {
+        private const val TAG = "MusicWebPlayer"
+        const val ACTION_SET_QUEUE = "com.musicweb.player.action.SET_QUEUE"
+        const val ACTION_PLAY_QUEUE = "com.musicweb.player.action.PLAY_QUEUE"
+        const val ACTION_TOGGLE = "com.musicweb.player.action.TOGGLE"
+        const val ACTION_NEXT = "com.musicweb.player.action.NEXT"
+        const val ACTION_PREVIOUS = "com.musicweb.player.action.PREVIOUS"
+        const val ACTION_PLAYBACK_STATE = "com.musicweb.player.action.PLAYBACK_STATE"
+        const val EXTRA_QUEUE_JSON = "queue_json"
+        const val EXTRA_INDEX = "index"
+        const val EXTRA_IS_PLAYING = "is_playing"
+        const val EXTRA_POSITION = "position"
+        const val EXTRA_DURATION = "duration"
+        const val EXTRA_CURRENT_INDEX = "current_index"
+        const val EXTRA_TRACK_NAME = "track_name"
+        const val EXTRA_TRACK_PATH = "track_path"
+        const val EXTRA_ERROR = "error"
+        private const val CHANNEL_ID = "musicweb_playback"
+        private const val NOTIFICATION_ID = 1001
+        private const val DEFAULT_BASE_URL = "http://110.42.102.94:8006/"
+    }
+}

+ 12 - 0
apk/app/src/main/res/drawable/ic_launcher_foreground.xml

@@ -0,0 +1,12 @@
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+    android:width="108dp"
+    android:height="108dp"
+    android:viewportWidth="108"
+    android:viewportHeight="108">
+    <path
+        android:fillColor="#1D6F5B"
+        android:pathData="M54,10C29.7,10 10,29.7 10,54s19.7,44 44,44 44,-19.7 44,-44S78.3,10 54,10z" />
+    <path
+        android:fillColor="#D7F3EA"
+        android:pathData="M76,39l-27.5,31L32,54.5l6.8,-6.8 9.5,9.5L69.2,33z" />
+</vector>

+ 5 - 0
apk/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml

@@ -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/white" />
+    <foreground android:drawable="@drawable/ic_launcher_foreground" />
+</adaptive-icon>

+ 5 - 0
apk/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml

@@ -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/white" />
+    <foreground android:drawable="@drawable/ic_launcher_foreground" />
+</adaptive-icon>

+ 9 - 0
apk/app/src/main/res/values/colors.xml

@@ -0,0 +1,9 @@
+<resources>
+    <color name="purple_200">#FFBB86FC</color>
+    <color name="purple_500">#FF6200EE</color>
+    <color name="purple_700">#FF3700B3</color>
+    <color name="teal_200">#FF03DAC5</color>
+    <color name="teal_700">#FF018786</color>
+    <color name="black">#FF000000</color>
+    <color name="white">#FFFFFFFF</color>
+</resources>

+ 5 - 0
apk/app/src/main/res/values/strings.xml

@@ -0,0 +1,5 @@
+<resources>
+    <string name="app_name">MusicWeb</string>
+    <string name="set_server_title">设置云端地址</string>
+    <string name="set_server_message">请输入可从安卓设备访问的音乐站点地址。</string>
+</resources>

+ 5 - 0
apk/app/src/main/res/values/themes.xml

@@ -0,0 +1,5 @@
+<resources xmlns:tools="http://schemas.android.com/tools">
+    <style name="Theme.MusicWebPlayer" parent="Theme.Material3.DayNight.NoActionBar">
+        <item name="android:statusBarColor" tools:targetApi="l">@android:color/black</item>
+    </style>
+</resources>

+ 4 - 0
apk/build.gradle.kts

@@ -0,0 +1,4 @@
+plugins {
+    id("com.android.application") version "8.5.2" apply false
+    id("org.jetbrains.kotlin.android") version "1.9.24" apply false
+}

+ 3 - 0
apk/gradle.properties

@@ -0,0 +1,3 @@
+org.gradle.jvmargs=-Xmx2g -Dfile.encoding=UTF-8
+android.useAndroidX=true
+android.nonTransitiveRClass=true

BIN
apk/gradle/wrapper/gradle-wrapper.jar


+ 7 - 0
apk/gradle/wrapper/gradle-wrapper.properties

@@ -0,0 +1,7 @@
+distributionBase=GRADLE_USER_HOME
+distributionPath=wrapper/dists
+distributionUrl=https\://services.gradle.org/distributions/gradle-8.7-bin.zip
+networkTimeout=60000
+validateDistributionUrl=true
+zipStoreBase=GRADLE_USER_HOME
+zipStorePath=wrapper/dists

+ 249 - 0
apk/gradlew

@@ -0,0 +1,249 @@
+#!/bin/sh
+
+#
+# Copyright © 2015-2021 the original authors.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      https://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+##############################################################################
+#
+#   Gradle start up script for POSIX generated by Gradle.
+#
+#   Important for running:
+#
+#   (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
+#       noncompliant, but you have some other compliant shell such as ksh or
+#       bash, then to run this script, type that shell name before the whole
+#       command line, like:
+#
+#           ksh Gradle
+#
+#       Busybox and similar reduced shells will NOT work, because this script
+#       requires all of these POSIX shell features:
+#         * functions;
+#         * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
+#           «${var#prefix}», «${var%suffix}», and «$( cmd )»;
+#         * compound commands having a testable exit status, especially «case»;
+#         * various built-in commands including «command», «set», and «ulimit».
+#
+#   Important for patching:
+#
+#   (2) This script targets any POSIX shell, so it avoids extensions provided
+#       by Bash, Ksh, etc; in particular arrays are avoided.
+#
+#       The "traditional" practice of packing multiple parameters into a
+#       space-separated string is a well documented source of bugs and security
+#       problems, so this is (mostly) avoided, by progressively accumulating
+#       options in "$@", and eventually passing that to Java.
+#
+#       Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
+#       and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
+#       see the in-line comments for details.
+#
+#       There are tweaks for specific operating systems such as AIX, CygWin,
+#       Darwin, MinGW, and NonStop.
+#
+#   (3) This script is generated from the Groovy template
+#       https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
+#       within the Gradle project.
+#
+#       You can find Gradle at https://github.com/gradle/gradle/.
+#
+##############################################################################
+
+# Attempt to set APP_HOME
+
+# Resolve links: $0 may be a link
+app_path=$0
+
+# Need this for daisy-chained symlinks.
+while
+    APP_HOME=${app_path%"${app_path##*/}"}  # leaves a trailing /; empty if no leading path
+    [ -h "$app_path" ]
+do
+    ls=$( ls -ld "$app_path" )
+    link=${ls#*' -> '}
+    case $link in             #(
+      /*)   app_path=$link ;; #(
+      *)    app_path=$APP_HOME$link ;;
+    esac
+done
+
+# This is normally unused
+# shellcheck disable=SC2034
+APP_BASE_NAME=${0##*/}
+# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
+APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit
+
+# Use the maximum available, or set MAX_FD != -1 to use that value.
+MAX_FD=maximum
+
+warn () {
+    echo "$*"
+} >&2
+
+die () {
+    echo
+    echo "$*"
+    echo
+    exit 1
+} >&2
+
+# OS specific support (must be 'true' or 'false').
+cygwin=false
+msys=false
+darwin=false
+nonstop=false
+case "$( uname )" in                #(
+  CYGWIN* )         cygwin=true  ;; #(
+  Darwin* )         darwin=true  ;; #(
+  MSYS* | MINGW* )  msys=true    ;; #(
+  NONSTOP* )        nonstop=true ;;
+esac
+
+CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
+
+
+# Determine the Java command to use to start the JVM.
+if [ -n "$JAVA_HOME" ] ; then
+    if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
+        # IBM's JDK on AIX uses strange locations for the executables
+        JAVACMD=$JAVA_HOME/jre/sh/java
+    else
+        JAVACMD=$JAVA_HOME/bin/java
+    fi
+    if [ ! -x "$JAVACMD" ] ; then
+        die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
+
+Please set the JAVA_HOME variable in your environment to match the
+location of your Java installation."
+    fi
+else
+    JAVACMD=java
+    if ! command -v java >/dev/null 2>&1
+    then
+        die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
+
+Please set the JAVA_HOME variable in your environment to match the
+location of your Java installation."
+    fi
+fi
+
+# Increase the maximum file descriptors if we can.
+if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
+    case $MAX_FD in #(
+      max*)
+        # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
+        # shellcheck disable=SC2039,SC3045
+        MAX_FD=$( ulimit -H -n ) ||
+            warn "Could not query maximum file descriptor limit"
+    esac
+    case $MAX_FD in  #(
+      '' | soft) :;; #(
+      *)
+        # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
+        # shellcheck disable=SC2039,SC3045
+        ulimit -n "$MAX_FD" ||
+            warn "Could not set maximum file descriptor limit to $MAX_FD"
+    esac
+fi
+
+# Collect all arguments for the java command, stacking in reverse order:
+#   * args from the command line
+#   * the main class name
+#   * -classpath
+#   * -D...appname settings
+#   * --module-path (only if needed)
+#   * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
+
+# For Cygwin or MSYS, switch paths to Windows format before running java
+if "$cygwin" || "$msys" ; then
+    APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
+    CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
+
+    JAVACMD=$( cygpath --unix "$JAVACMD" )
+
+    # Now convert the arguments - kludge to limit ourselves to /bin/sh
+    for arg do
+        if
+            case $arg in                                #(
+              -*)   false ;;                            # don't mess with options #(
+              /?*)  t=${arg#/} t=/${t%%/*}              # looks like a POSIX filepath
+                    [ -e "$t" ] ;;                      #(
+              *)    false ;;
+            esac
+        then
+            arg=$( cygpath --path --ignore --mixed "$arg" )
+        fi
+        # Roll the args list around exactly as many times as the number of
+        # args, so each arg winds up back in the position where it started, but
+        # possibly modified.
+        #
+        # NB: a `for` loop captures its iteration list before it begins, so
+        # changing the positional parameters here affects neither the number of
+        # iterations, nor the values presented in `arg`.
+        shift                   # remove old arg
+        set -- "$@" "$arg"      # push replacement arg
+    done
+fi
+
+
+# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
+DEFAULT_JVM_OPTS='-Dfile.encoding=UTF-8 "-Xmx64m" "-Xms64m"'
+
+# Collect all arguments for the java command:
+#   * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
+#     and any embedded shellness will be escaped.
+#   * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
+#     treated as '${Hostname}' itself on the command line.
+
+set -- \
+        "-Dorg.gradle.appname=$APP_BASE_NAME" \
+        -classpath "$CLASSPATH" \
+        org.gradle.wrapper.GradleWrapperMain \
+        "$@"
+
+# Stop when "xargs" is not available.
+if ! command -v xargs >/dev/null 2>&1
+then
+    die "xargs is not available"
+fi
+
+# Use "xargs" to parse quoted args.
+#
+# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
+#
+# In Bash we could simply go:
+#
+#   readarray ARGS < <( xargs -n1 <<<"$var" ) &&
+#   set -- "${ARGS[@]}" "$@"
+#
+# but POSIX shell has neither arrays nor command substitution, so instead we
+# post-process each arg (as a line of input to sed) to backslash-escape any
+# character that might be a shell metacharacter, then use eval to reverse
+# that process (while maintaining the separation between arguments), and wrap
+# the whole thing up as a single "set" statement.
+#
+# This will of course break if any of these variables contains a newline or
+# an unmatched quote.
+#
+
+eval "set -- $(
+        printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
+        xargs -n1 |
+        sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
+        tr '\n' ' '
+    )" '"$@"'
+
+exec "$JAVACMD" "$@"

+ 92 - 0
apk/gradlew.bat

@@ -0,0 +1,92 @@
+@rem
+@rem Copyright 2015 the original author or authors.
+@rem
+@rem Licensed under the Apache License, Version 2.0 (the "License");
+@rem you may not use this file except in compliance with the License.
+@rem You may obtain a copy of the License at
+@rem
+@rem      https://www.apache.org/licenses/LICENSE-2.0
+@rem
+@rem Unless required by applicable law or agreed to in writing, software
+@rem distributed under the License is distributed on an "AS IS" BASIS,
+@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+@rem See the License for the specific language governing permissions and
+@rem limitations under the License.
+@rem
+
+@if "%DEBUG%"=="" @echo off
+@rem ##########################################################################
+@rem
+@rem  Gradle startup script for Windows
+@rem
+@rem ##########################################################################
+
+@rem Set local scope for the variables with windows NT shell
+if "%OS%"=="Windows_NT" setlocal
+
+set DIRNAME=%~dp0
+if "%DIRNAME%"=="" set DIRNAME=.
+@rem This is normally unused
+set APP_BASE_NAME=%~n0
+set APP_HOME=%DIRNAME%
+
+@rem Resolve any "." and ".." in APP_HOME to make it shorter.
+for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
+
+@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
+set DEFAULT_JVM_OPTS=-Dfile.encoding=UTF-8 "-Xmx64m" "-Xms64m"
+
+@rem Find java.exe
+if defined JAVA_HOME goto findJavaFromJavaHome
+
+set JAVA_EXE=java.exe
+%JAVA_EXE% -version >NUL 2>&1
+if %ERRORLEVEL% equ 0 goto execute
+
+echo. 1>&2
+echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
+echo. 1>&2
+echo Please set the JAVA_HOME variable in your environment to match the 1>&2
+echo location of your Java installation. 1>&2
+
+goto fail
+
+:findJavaFromJavaHome
+set JAVA_HOME=%JAVA_HOME:"=%
+set JAVA_EXE=%JAVA_HOME%/bin/java.exe
+
+if exist "%JAVA_EXE%" goto execute
+
+echo. 1>&2
+echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
+echo. 1>&2
+echo Please set the JAVA_HOME variable in your environment to match the 1>&2
+echo location of your Java installation. 1>&2
+
+goto fail
+
+:execute
+@rem Setup the command line
+
+set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
+
+
+@rem Execute Gradle
+"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
+
+:end
+@rem End local scope for the variables with windows NT shell
+if %ERRORLEVEL% equ 0 goto mainEnd
+
+:fail
+rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
+rem the _cmd.exe /c_ return code!
+set EXIT_CODE=%ERRORLEVEL%
+if %EXIT_CODE% equ 0 set EXIT_CODE=1
+if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
+exit /b %EXIT_CODE%
+
+:mainEnd
+if "%OS%"=="Windows_NT" endlocal
+
+:omega

+ 18 - 0
apk/settings.gradle.kts

@@ -0,0 +1,18 @@
+pluginManagement {
+    repositories {
+        google()
+        mavenCentral()
+        gradlePluginPortal()
+    }
+}
+
+dependencyResolutionManagement {
+    repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
+    repositories {
+        google()
+        mavenCentral()
+    }
+}
+
+rootProject.name = "MusicWebPlayer"
+include(":app")

+ 9 - 1
playlists.json

@@ -1 +1,9 @@
-[]
+[
+  {
+    "id": "25a46a5ac7524491a8d6a1399d0cdbaa",
+    "name": "我的",
+    "tracks": [
+      "萨克斯风/《回家》CD1.mp3"
+    ]
+  }
+]