Skip to content

Native Android client for Spotify, built with Jetpack Compose

Hearts at once, page prefetch, setup screen, local folders

kota-zo9789e8c8b93e
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 11a015fb..5edfa400 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -17,6 +17,9 @@ A new engine, written from scratch, and a cleaner app on top of it.
- **Playback goes on with the screen off**: the app no longer leaves the foreground between two songs, so Android stops freezing it after the first song.
- **Switching accounts works**: after a logout, signing in with another account shows that account, not the previous one.
- **Sort by** in playlists and Liked Songs: title, artist, album or duration.
+- **Hearts show at once** in playlists: the liked songs were only checked after a tap (a playlist in the check made Spotify refuse it). Lists at the top of the library and the home shortcuts load before you open them.
+- **Setup screen** after signing in: notifications, local music, Bluetooth and unrestricted battery, each with its own button.
+- **Folders in Local Files**: choose the folders shown; WhatsApp, Telegram, recordings and ringtones start hidden.
- **Spotify keeps working after its updates**: the app picks up the Web Player's new operations by itself when Spotify ships a new version.
- **No ads**: the ad audio is refused, so the player skips the ad within a second, and nothing false is reported to Spotify.
- **Podcasts and audiobooks are back**: shows, episodes, chapters, **Your Episodes** in Your Library, and **playback speed** (from the song menu) for episodes.
diff --git a/base/api-spotify/src/main/kotlin/app/myspoti/spotify/SpotifyLibrary.kt b/base/api-spotify/src/main/kotlin/app/myspoti/spotify/SpotifyLibrary.kt
index 71e0e869..20d4d421 100644
--- a/base/api-spotify/src/main/kotlin/app/myspoti/spotify/SpotifyLibrary.kt
+++ b/base/api-spotify/src/main/kotlin/app/myspoti/spotify/SpotifyLibrary.kt
@@ -32,8 +32,26 @@ class SpotifyLibrary(private val bridge: Bridge, private val gql: Gql) : Library
override val changes: SharedFlow<Unit> = _changes
private fun changed() { _changes.tryEmit(Unit) }
- override suspend fun contains(uris: List<Uri>): List<Boolean> =
- (bridge.call("library.contains", uris(uris) as kotlinx.serialization.json.JsonObject) as JsonArray).map { it.jsonPrimitive.boolean }
+ /**
+ * The page's LibraryAPI rejects the whole list ("Unknown URI type!") as soon as it holds a
+ * playlist: playlists are asked to the rootlist (the followed / own playlists), the rest to
+ * the library, and the answers come back in the order of [uris].
+ */
+ override suspend fun contains(uris: List<Uri>): List<Boolean> {
+ if (uris.isEmpty()) return emptyList()
+ val (lists, others) = uris.withIndex().partition { it.value.contains(":playlist:") }
+ val out = BooleanArray(uris.size)
+ if (others.isNotEmpty()) {
+ val flags = bridge.call("library.contains", uris(others.map { it.value }) as kotlinx.serialization.json.JsonObject) as JsonArray
+ others.forEachIndexed { i, v -> out[v.index] = flags.getOrNull(i)?.jsonPrimitive?.boolean == true }
+ }
+ if (lists.isNotEmpty()) {
+ val arg = JsonArray(lists.map { JsonPrimitive(it.value) })
+ val flags = bridge.service("RootlistAPI", "contains", arg) as? JsonArray
+ lists.forEachIndexed { i, v -> out[v.index] = flags?.getOrNull(i)?.jsonPrimitive?.boolean == true }
+ }
+ return out.toList()
+ }
override suspend fun add(uris: List<Uri>) {
bridge.call("library.add", uris(uris) as kotlinx.serialization.json.JsonObject); changed()
diff --git a/base/app/src/main/AndroidManifest.xml b/base/app/src/main/AndroidManifest.xml
index 54bbd680..958ca33d 100644
--- a/base/app/src/main/AndroidManifest.xml
+++ b/base/app/src/main/AndroidManifest.xml
@@ -2,6 +2,7 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
+ <uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
diff --git a/base/app/src/main/java/app/myspoti/MainActivity.kt b/base/app/src/main/java/app/myspoti/MainActivity.kt
index e7b58d9d..cf534f05 100644
--- a/base/app/src/main/java/app/myspoti/MainActivity.kt
+++ b/base/app/src/main/java/app/myspoti/MainActivity.kt
@@ -38,20 +38,23 @@ class MainActivity : AppCompatActivity() {
private var showingLogin by mutableStateOf(false)
/** Back from Spotify's login, waiting for the session: a native loading screen, not the web page. */
private var connecting by mutableStateOf(false)
+ /** The one-time setup screen (permissions, battery) after signing in. */
+ private var setupNeeded by mutableStateOf(false)
private val prefs get() = getSharedPreferences("myspoti_prefs", Context.MODE_PRIVATE)
- private val notificationPermission = registerForActivityResult(ActivityResultContracts.RequestPermission()) {}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
signedIn = prefs.getBoolean("LoggedIn", false)
+ setupNeeded = com.music.spotui.ui.screens.Setup.needed(this)
root = FrameLayout(this)
val compose = ComposeView(this).apply {
setContent {
SpotuiTheme {
androidx.compose.foundation.layout.Box(androidx.compose.ui.Modifier.fillMaxSize()) {
when {
+ signedIn && setupNeeded -> com.music.spotui.ui.screens.SetupScreen(onDone = { setupNeeded = false })
signedIn -> App()
connecting -> ConnectingScreen()
else -> WelcomeScreen(onLogin = { showLogin() })
@@ -72,7 +75,6 @@ class MainActivity : AppCompatActivity() {
watchSession()
watchLoginReturn()
watchLogout()
- askNotifications()
handle(intent)
}
@@ -156,11 +158,6 @@ class MainActivity : AppCompatActivity() {
}
}
- private fun askNotifications() {
- if (Build.VERSION.SDK_INT >= 33 &&
- ContextCompat.checkSelfPermission(this, Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED
- ) notificationPermission.launch(Manifest.permission.POST_NOTIFICATIONS)
- }
/** Spotify links (open.spotify.com/...) play their item; voice search plays its best match. */
private fun handle(intent: Intent?) {
diff --git a/base/app/src/main/java/com/music/spotui/data/local/LocalMusic.kt b/base/app/src/main/java/com/music/spotui/data/local/LocalMusic.kt
index ba9730f7..ad0d5c83 100644
--- a/base/app/src/main/java/com/music/spotui/data/local/LocalMusic.kt
+++ b/base/app/src/main/java/com/music/spotui/data/local/LocalMusic.kt
@@ -19,6 +19,8 @@ data class LocalTrack(
val album: String,
val durationMs: Long,
val artUri: Uri,
+ /** The file's folder on the phone, e.g. "Music/Album/" (MediaStore relative path). */
+ val folder: String = "",
)
/** The device's music files, read through MediaStore (no file access beyond audio). */
@@ -32,7 +34,18 @@ object LocalMusic {
@Volatile private var cache: List<LocalTrack>? = null
- suspend fun tracks(context: Context, refresh: Boolean = false): List<LocalTrack> = withContext(Dispatchers.IO) {
+ /** The tracks shown in Local Files: all of them but those of the folders left out ([LocalFolders]). */
+ suspend fun tracks(context: Context, refresh: Boolean = false): List<LocalTrack> {
+ val all = allTracks(context, refresh)
+ val out = LocalFolders.excluded(context, all.map { it.folder }.toSet())
+ return if (out.isEmpty()) all else all.filter { it.folder !in out }
+ }
+
+ /** Every folder holding music, with its number of tracks, by name. */
+ suspend fun folders(context: Context): List<Pair<String, Int>> =
+ allTracks(context).groupingBy { it.folder }.eachCount().toList().sortedBy { it.first.lowercase() }
+
+ private suspend fun allTracks(context: Context, refresh: Boolean = false): List<LocalTrack> = withContext(Dispatchers.IO) {
if (!hasPermission(context)) return@withContext emptyList()
cache?.takeIf { !refresh }?.let { return@withContext it }
val collection = if (Build.VERSION.SDK_INT >= 29) MediaStore.Audio.Media.getContentUri(MediaStore.VOLUME_EXTERNAL)
@@ -40,6 +53,7 @@ object LocalMusic {
val projection = arrayOf(
MediaStore.Audio.Media._ID, MediaStore.Audio.Media.TITLE, MediaStore.Audio.Media.ARTIST,
MediaStore.Audio.Media.ALBUM, MediaStore.Audio.Media.DURATION, MediaStore.Audio.Media.ALBUM_ID,
+ MediaStore.Audio.Media.RELATIVE_PATH,
)
val out = ArrayList<LocalTrack>()
context.contentResolver.query(
@@ -53,6 +67,7 @@ object LocalMusic {
val iAlbum = c.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM)
val iDur = c.getColumnIndexOrThrow(MediaStore.Audio.Media.DURATION)
val iAlbumId = c.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM_ID)
+ val iPath = c.getColumnIndex(MediaStore.Audio.Media.RELATIVE_PATH)
while (c.moveToNext()) {
val id = c.getLong(iId)
val artist = c.getString(iArtist)?.takeIf { it != MediaStore.UNKNOWN_STRING }.orEmpty()
@@ -64,6 +79,7 @@ object LocalMusic {
album = c.getString(iAlbum).orEmpty(),
durationMs = c.getLong(iDur),
artUri = ContentUris.withAppendedId(Uri.parse("content://media/external/audio/albumart"), c.getLong(iAlbumId)),
+ folder = if (iPath >= 0) c.getString(iPath).orEmpty() else "",
)
}
}
@@ -71,3 +87,39 @@ object LocalMusic {
out
}
}
+
+
+/**
+ * Folders left out of Local Files (WhatsApp voice notes and audio, recordings…), chosen in
+ * Local Files. Messaging and recording folders start left out; the user decides afterwards.
+ */
+object LocalFolders {
+ private const val PREFS = "local_folders"
+ private const val KEY_OUT = "excluded"
+ private const val KEY_SEEN = "seen"
+ private val defaultOut = Regex("""(?i)whatsapp|telegram|signal|messenger|recordings?|enregistrements|voice|notifications|ringtones|alarms|call""")
+
+ private fun prefs(context: Context) = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
+
+ /** The folders left out; new messaging / recording folders are added the first time they are seen. */
+ fun excluded(context: Context, known: Set<String>): Set<String> {
+ val p = prefs(context)
+ val out = p.getStringSet(KEY_OUT, emptySet()).orEmpty().toMutableSet()
+ val seen = p.getStringSet(KEY_SEEN, emptySet()).orEmpty()
+ val fresh = known - seen
+ if (fresh.isNotEmpty()) {
+ out += fresh.filter { defaultOut.containsMatchIn(it) }
+ p.edit().putStringSet(KEY_OUT, out).putStringSet(KEY_SEEN, seen + fresh).apply()
+ }
+ return out
+ }
+
+ fun isExcluded(context: Context, folder: String) = folder in prefs(context).getStringSet(KEY_OUT, emptySet()).orEmpty()
+
+ fun set(context: Context, folder: String, shown: Boolean) {
+ val p = prefs(context)
+ val out = p.getStringSet(KEY_OUT, emptySet()).orEmpty().toMutableSet()
+ if (shown) out -= folder else out += folder
+ p.edit().putStringSet(KEY_OUT, out).apply()
+ }
+}
diff --git a/base/app/src/main/java/com/music/spotui/di/Haptics.kt b/base/app/src/main/java/com/music/spotui/di/Haptics.kt
index 62624200..ac79082c 100644
--- a/base/app/src/main/java/com/music/spotui/di/Haptics.kt
+++ b/base/app/src/main/java/com/music/spotui/di/Haptics.kt
@@ -27,6 +27,26 @@ object Haptics {
else HapticFeedbackConstants.CLOCK_TICK
)
+ /**
+ * One tick of a rising buzz, [level] 0..1 (the debug button while it is held): stronger
+ * as the hold goes on, so the finger feels it is getting somewhere.
+ */
+ fun ramp(level: Float) {
+ val v = view?.get() ?: return
+ val vibrator = (if (Build.VERSION.SDK_INT >= 31)
+ v.context.getSystemService(android.os.VibratorManager::class.java)?.defaultVibrator
+ else @Suppress("DEPRECATION") v.context.getSystemService(android.os.Vibrator::class.java)) ?: return
+ val l = level.coerceIn(0.05f, 1f)
+ runCatching {
+ if (Build.VERSION.SDK_INT >= 30 && vibrator.areAllPrimitivesSupported(android.os.VibrationEffect.Composition.PRIMITIVE_TICK)) {
+ vibrator.vibrate(android.os.VibrationEffect.startComposition()
+ .addPrimitive(android.os.VibrationEffect.Composition.PRIMITIVE_TICK, l).compose())
+ } else {
+ vibrator.vibrate(android.os.VibrationEffect.createOneShot(12, (40 + 215 * l).toInt().coerceIn(1, 255)))
+ }
+ }
+ }
+
/** A completed action (queued, removed, transferred). */
fun confirm() = perform(HapticFeedbackConstants.CONFIRM)
}
diff --git a/base/app/src/main/java/com/music/spotui/ui/components/BetaLogButton.kt b/base/app/src/main/java/com/music/spotui/ui/components/BetaLogButton.kt
index f1427423..7245da78 100644
--- a/base/app/src/main/java/com/music/spotui/ui/components/BetaLogButton.kt
+++ b/base/app/src/main/java/com/music/spotui/ui/components/BetaLogButton.kt
@@ -49,48 +49,78 @@ import app.myspoti.engine.R
import com.music.spotui.data.BetaLogs
/**
- * Beta builds: a tiny, faint dot in the bottom-right corner. Holding it makes it grow; held
- * until full size, it opens the app's logs of the last [BetaLogs.MINUTES] minutes, ready to copy
- * into a bug report. A short touch does nothing, so it never gets in the way.
+ * Beta builds: a small bug icon in the bottom-right corner, next to the Library tab. Holding
+ * it makes it grow; held until full size, it opens the app's logs of the last
+ * [BetaLogs.MINUTES] minutes, ready to copy into a bug report. A short touch does nothing.
*/
@Composable
fun BetaLogButton(modifier: Modifier = Modifier) {
var open by remember { mutableStateOf(false) }
val grow = remember { androidx.compose.animation.core.Animatable(0f) }
val scope = androidx.compose.runtime.rememberCoroutineScope()
- Box(
+ // The full player covers the tabs: no bug icon over it.
+ if (!com.music.spotui.ui.navigation.PlayerSheet.open.value) Box(
modifier
.navigationBarsPadding()
- .padding(end = 2.dp, bottom = 132.dp)
- .size(28.dp)
+ .padding(end = 4.dp, bottom = 23.dp)
+ .size(44.dp)
.pointerInput(Unit) {
detectTapGestures(onPress = {
val job = scope.launch {
grow.animateTo(1f, androidx.compose.animation.core.tween(HOLD_MS, easing = androidx.compose.animation.core.LinearEasing))
- Haptics.click()
+ Haptics.confirm()
open = true
}
+ // Ticks that get stronger and closer while the finger stays down.
+ val buzz = scope.launch {
+ while (grow.value < 1f) {
+ Haptics.ramp(grow.value)
+ kotlinx.coroutines.delay((140 - 100 * grow.value).toLong())
+ }
+ }
tryAwaitRelease()
job.cancel()
+ buzz.cancel()
scope.launch { grow.animateTo(0f, androidx.compose.animation.core.tween(150)) }
})
},
contentAlignment = Alignment.Center,
) {
val g = grow.value
- Box(
- Modifier
- .size((10 + 18 * g).dp)
- .background(Color(0xFF1DB954).copy(alpha = 0.45f + 0.5f * g), CircleShape)
- .border(1.dp, Color.White.copy(alpha = 0.5f), CircleShape),
- contentAlignment = Alignment.Center,
- ) {
- if (g > 0.6f) Text("log", color = Color.Black.copy(alpha = (g - 0.6f) * 2.5f), fontSize = 8.sp, fontFamily = FontFamily.Monospace)
- }
+ BugIcon(
+ color = androidx.compose.ui.graphics.lerp(Color(0xFFB3B3B3), Color(0xFF1DB954), g),
+ modifier = Modifier.size((24 + 16 * g).dp),
+ )
}
if (open) LogsDialog(onDismiss = { open = false })
}
+/** A plain beetle, drawn here: rounded body split in two, head, antennae, three legs a side. */
+@Composable
+private fun BugIcon(color: Color, modifier: Modifier = Modifier) {
+ androidx.compose.foundation.Canvas(modifier) {
+ val w = size.width; val h = size.height
+ val stroke = androidx.compose.ui.graphics.drawscope.Stroke(width = w * 0.09f, cap = androidx.compose.ui.graphics.StrokeCap.Round)
+ val line = w * 0.09f
+ // Body.
+ drawRoundRect(color, topLeft = androidx.compose.ui.geometry.Offset(w * 0.28f, h * 0.32f),
+ size = androidx.compose.ui.geometry.Size(w * 0.44f, h * 0.58f),
+ cornerRadius = androidx.compose.ui.geometry.CornerRadius(w * 0.22f), style = stroke)
+ drawLine(color, androidx.compose.ui.geometry.Offset(w * 0.5f, h * 0.36f), androidx.compose.ui.geometry.Offset(w * 0.5f, h * 0.86f), line)
+ // Head.
+ drawArc(color, 180f, 180f, false, topLeft = androidx.compose.ui.geometry.Offset(w * 0.37f, h * 0.18f),
+ size = androidx.compose.ui.geometry.Size(w * 0.26f, h * 0.26f), style = stroke)
+ // Antennae.
+ drawLine(color, androidx.compose.ui.geometry.Offset(w * 0.42f, h * 0.2f), androidx.compose.ui.geometry.Offset(w * 0.34f, h * 0.08f), line, androidx.compose.ui.graphics.StrokeCap.Round)
+ drawLine(color, androidx.compose.ui.geometry.Offset(w * 0.58f, h * 0.2f), androidx.compose.ui.geometry.Offset(w * 0.66f, h * 0.08f), line, androidx.compose.ui.graphics.StrokeCap.Round)
+ // Legs.
+ for ((y, dy) in listOf(0.45f to -0.08f, 0.6f to 0f, 0.75f to 0.08f)) {
+ drawLine(color, androidx.compose.ui.geometry.Offset(w * 0.28f, h * y), androidx.compose.ui.geometry.Offset(w * 0.12f, h * (y + dy)), line, androidx.compose.ui.graphics.StrokeCap.Round)
+ drawLine(color, androidx.compose.ui.geometry.Offset(w * 0.72f, h * y), androidx.compose.ui.geometry.Offset(w * 0.88f, h * (y + dy)), line, androidx.compose.ui.graphics.StrokeCap.Round)
+ }
+ }
+}
+
private const val HOLD_MS = 900
@Composable
diff --git a/base/app/src/main/java/com/music/spotui/ui/screens/ContextScreen.kt b/base/app/src/main/java/com/music/spotui/ui/screens/ContextScreen.kt
index f303a427..fea8bfc2 100644
--- a/base/app/src/main/java/com/music/spotui/ui/screens/ContextScreen.kt
+++ b/base/app/src/main/java/com/music/spotui/ui/screens/ContextScreen.kt
@@ -96,6 +96,18 @@ class ContextViewModel(
private val inflight = java.util.concurrent.ConcurrentHashMap<String, kotlinx.coroutines.Deferred<Unit>>()
private val prefetchScope = kotlinx.coroutines.CoroutineScope(kotlinx.coroutines.SupervisorJob() + Dispatchers.IO)
+ /** Pages likely to be opened next (top of the library, home shortcuts), loaded quietly. */
+ fun prefetchSoon(pages: List<Pair<String, String>>) {
+ prefetchScope.launch {
+ kotlinx.coroutines.delay(1_000)
+ // One after the other: they must not slow down what is on screen.
+ for ((type, id) in pages) {
+ prefetch(type, id)
+ inflight["$type:$id"]?.await()
+ }
+ }
+ }
+
/** Start loading a page the user is about to open (first page of tracks). */
fun prefetch(type: String, id: String) {
if (id.isBlank() && type != "liked") return
@@ -110,7 +122,13 @@ class ContextViewModel(
else -> api.getPlaylistPage(id)
}
val first = flow.first { it !is Response.Loading }
- if (first is Response.Success) recent[key] = first
+ if (first is Response.Success) {
+ recent[key] = first
+ // The hearts are known before the page opens.
+ val p = first.data
+ if (p.type != "liked") SongPlayer.libraryContains(
+ p.tracks.mapNotNull { s -> s.spotifyTrackId.takeIf { it.isNotBlank() }?.let { "spotify:track:$it" } } + p.uri)
+ }
} catch (t: kotlinx.coroutines.CancellationException) {
throw t
} catch (_: Throwable) {
diff --git a/base/app/src/main/java/com/music/spotui/ui/screens/HomeScreen.kt b/base/app/src/main/java/com/music/spotui/ui/screens/HomeScreen.kt
index 845a7699..27d41b3b 100644
--- a/base/app/src/main/java/com/music/spotui/ui/screens/HomeScreen.kt
+++ b/base/app/src/main/java/com/music/spotui/ui/screens/HomeScreen.kt
@@ -164,6 +164,17 @@ fun HomeFeedContent(navController: NavController, feed: HomeFeedModel, facet: St
else feed.sections.map { s -> s.copy(items = s.items.filterNot { it is HomeItem.Show }) }.filter { it.items.isNotEmpty() }
val gridSection = sections.firstOrNull()?.takeIf { it.title.isBlank() }
val carousels = if (gridSection != null) sections.drop(1) else sections
+ // The shortcuts at the top load in the background, ready before a tap.
+ androidx.compose.runtime.LaunchedEffect(gridSection?.items?.map { it.name }) {
+ val top = gridSection?.items.orEmpty().take(8).mapNotNull { item ->
+ when (item) {
+ is HomeItem.Album -> item.id.takeIf { it.isNotBlank() }?.let { "album" to it }
+ is HomeItem.Playlist -> item.id.takeIf { it.isNotBlank() }?.let { "playlist" to it }
+ else -> null
+ }
+ }
+ if (top.isNotEmpty()) ContextViewModel.prefetchSoon(top)
+ }
LazyColumn(
contentPadding = PaddingValues(bottom = 130.dp),
diff --git a/base/app/src/main/java/com/music/spotui/ui/screens/LibraryScreeen.kt b/base/app/src/main/java/com/music/spotui/ui/screens/LibraryScreeen.kt
index f1fd870a..6ff0a528 100644
--- a/base/app/src/main/java/com/music/spotui/ui/screens/LibraryScreeen.kt
+++ b/base/app/src/main/java/com/music/spotui/ui/screens/LibraryScreeen.kt
@@ -105,6 +105,19 @@ fun LibraryScreen(navController: NavController) {
val libraryViewModel: LibraryViewModel = viewModel()
val entries by libraryViewModel.entries.collectAsState()
+ // The first lists of the library load in the background, ready before a tap.
+ androidx.compose.runtime.LaunchedEffect((entries as? Response.Success)?.data?.take(8)?.map { it.spotifyId }) {
+ val top = (entries as? Response.Success)?.data.orEmpty().take(8).mapNotNull { e ->
+ when {
+ e.isFolder || e.spotifyId.startsWith(LOCAL_PLAYLIST_PREFIX) -> null
+ e.spotifyId in setOf(Api.HomeCache.LOCAL_FILES_ID, Api.HomeCache.DOWNLOADS_ID, Api.HomeCache.EPISODES_ID) -> null
+ e.spotifyId == Api.HomeCache.LIKED_SONGS_ID -> "liked" to ""
+ e.isPlaylist -> "playlist" to e.spotifyId
+ else -> "album" to e.spotifyId
+ }
+ }
+ if (top.isNotEmpty()) ContextViewModel.prefetchSoon(top)
+ }
val account by libraryViewModel.account.collectAsState()
var showAccount by remember { mutableStateOf(false) }
val context = LocalContext.current
diff --git a/base/app/src/main/java/com/music/spotui/ui/screens/LocalFilesScreen.kt b/base/app/src/main/java/com/music/spotui/ui/screens/LocalFilesScreen.kt
index 105b26ac..ade3e3a6 100644
--- a/base/app/src/main/java/com/music/spotui/ui/screens/LocalFilesScreen.kt
+++ b/base/app/src/main/java/com/music/spotui/ui/screens/LocalFilesScreen.kt
@@ -1,5 +1,7 @@
package com.music.spotui.ui.screens
+import kotlinx.coroutines.launch
+import androidx.compose.foundation.layout.navigationBarsPadding
import android.content.Intent
import android.net.Uri
import android.provider.Settings
@@ -81,6 +83,12 @@ fun LocalFilesScreen(navController: NavController) {
val playingLocal = LocalPlayer.active.value
var adding by remember { mutableStateOf<LocalTrack?>(null) }
adding?.let { t -> AddLocalToPlaylistSheet(t, onDismiss = { adding = null }) }
+ var choosingFolders by remember { mutableStateOf(false) }
+ val scope = androidx.compose.runtime.rememberCoroutineScope()
+ if (choosingFolders) LocalFoldersSheet(
+ onChanged = { scope.launch { tracks = LocalMusic.tracks(context) } },
+ onDismiss = { choosingFolders = false },
+ )
Box(Modifier.fillMaxSize().background(AppBackground)) {
when {
@@ -114,6 +122,10 @@ fun LocalFilesScreen(navController: NavController) {
Text(pluralStringResource(R.plurals.local_files_count, n, n), color = Color(0xFFB3B3B3), fontSize = 14.sp,
modifier = Modifier.padding(top = 4.dp))
Row(Modifier.fillMaxWidth().padding(vertical = 12.dp), verticalAlignment = Alignment.CenterVertically) {
+ androidx.compose.material3.OutlinedButton(
+ onClick = { choosingFolders = true },
+ border = androidx.compose.foundation.BorderStroke(1.dp, Color(0xFF7F7F7F)),
+ ) { Text(stringResource(R.string.local_folders_button), color = Color.White, fontSize = 13.sp) }
Spacer(Modifier.weight(1f))
Icon(painterResource(R.drawable.ic_player_shuffle), stringResource(R.string.play_mode_item_shuffle_title), tint = Color.White,
modifier = Modifier.size(28.dp).pressable { tracks?.let { if (it.isNotEmpty()) LocalPlayer.play(it, it.indices.random(), shuffle = true) } })
@@ -198,3 +210,49 @@ private fun EmptyState(title: String, subtitle: String, button: String?, onClick
}
}
}
+
+
+/** The phone's music folders, each shown in Local Files or left out (WhatsApp audio…). */
+@OptIn(androidx.compose.material3.ExperimentalMaterial3Api::class)
+@Composable
+private fun LocalFoldersSheet(onChanged: () -> Unit, onDismiss: () -> Unit) {
+ val context = LocalContext.current
+ var folders by remember { mutableStateOf<List<Pair<String, Int>>>(emptyList()) }
+ var version by remember { mutableStateOf(0) }
+ LaunchedEffect(Unit) { folders = LocalMusic.folders(context) }
+ androidx.compose.material3.ModalBottomSheet(onDismissRequest = onDismiss, containerColor = Color(0xFF282828)) {
+ Column(Modifier.navigationBarsPadding().padding(bottom = 16.dp)) {
+ Text(stringResource(R.string.local_folders_title), color = Color.White, fontSize = 18.sp, fontWeight = FontWeight.Bold,
+ modifier = Modifier.padding(horizontal = 20.dp))
+ Text(stringResource(R.string.local_folders_detail), color = Color(0xFFB3B3B3), fontSize = 13.sp,
+ modifier = Modifier.padding(horizontal = 20.dp, vertical = 6.dp))
+ LazyColumn {
+ items(folders.size) { i ->
+ val (folder, count) = folders[i]
+ @Suppress("UNUSED_EXPRESSION") version
+ val shown = !com.music.spotui.data.local.LocalFolders.isExcluded(context, folder)
+ Row(
+ verticalAlignment = Alignment.CenterVertically,
+ modifier = Modifier.fillMaxWidth().padding(horizontal = 20.dp, vertical = 8.dp),
+ ) {
+ Column(Modifier.weight(1f)) {
+ val name = folder.trimEnd('/').substringAfterLast('/').ifBlank { folder.ifBlank { "/" } }
+ Text(name, color = Color.White, fontSize = 15.sp, maxLines = 1)
+ Text("$folder · ${pluralStringResource(R.plurals.local_files_count, count, count)}", color = Color(0xFF9A9A9A),
+ fontSize = 12.sp, maxLines = 1, overflow = androidx.compose.ui.text.style.TextOverflow.Ellipsis)
+ }
+ androidx.compose.material3.Switch(
+ checked = shown,
+ onCheckedChange = {
+ com.music.spotui.data.local.LocalFolders.set(context, folder, it)
+ version++
+ onChanged()
+ },
+ colors = androidx.compose.material3.SwitchDefaults.colors(checkedTrackColor = Color(0xFF1DB954)),
+ )
+ }
+ }
+ }
+ }
+ }
+}
diff --git a/base/app/src/main/java/com/music/spotui/ui/screens/SetupScreen.kt b/base/app/src/main/java/com/music/spotui/ui/screens/SetupScreen.kt
new file mode 100644
index 00000000..d4bdf670
--- /dev/null
+++ b/base/app/src/main/java/com/music/spotui/ui/screens/SetupScreen.kt
@@ -0,0 +1,118 @@
+package com.music.spotui.ui.screens
+
+import android.Manifest
+import android.content.Context
+import android.content.pm.PackageManager
+import android.os.Build
+import androidx.activity.compose.rememberLauncherForActivityResult
+import androidx.activity.result.contract.ActivityResultContracts
+import androidx.compose.foundation.background
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.Spacer
+import androidx.compose.foundation.layout.fillMaxSize
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.height
+import androidx.compose.foundation.layout.navigationBarsPadding
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.layout.size
+import androidx.compose.foundation.layout.statusBarsPadding
+import androidx.compose.foundation.rememberScrollState
+import androidx.compose.foundation.shape.RoundedCornerShape
+import androidx.compose.foundation.verticalScroll
+import androidx.compose.material.icons.Icons
+import androidx.compose.material.icons.filled.CheckCircle
+import androidx.compose.material3.Button
+import androidx.compose.material3.ButtonDefaults
+import androidx.compose.material3.Icon
+import androidx.compose.material3.Text
+import androidx.compose.material3.TextButton
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.LaunchedEffect
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableIntStateOf
+import androidx.compose.runtime.remember
+import androidx.compose.runtime.setValue
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.graphics.Color
+import androidx.compose.ui.platform.LocalContext
+import androidx.compose.ui.res.stringResource
+import androidx.compose.ui.text.font.FontWeight
+import androidx.compose.ui.unit.dp
+import androidx.compose.ui.unit.sp
+import app.myspoti.engine.R
+import app.myspoti.power.BatteryExemption
+import com.music.spotui.data.local.LocalMusic
+import com.music.spotui.ui.theme.AppBackground
+
+/**
+ * Shown once after signing in: what Myspoti needs from the phone, each with its own button.
+ * Nothing is required; "Continue" goes on with whatever was allowed.
+ */
+object Setup {
+ private const val KEY = "SetupDone"
+ fun needed(context: Context) = !context.getSharedPreferences("myspoti_prefs", Context.MODE_PRIVATE).getBoolean(KEY, false)
+ fun done(context: Context) = context.getSharedPreferences("myspoti_prefs", Context.MODE_PRIVATE).edit().putBoolean(KEY, true).apply()
+}
+
+private fun granted(context: Context, permission: String) =
+ context.checkSelfPermission(permission) == PackageManager.PERMISSION_GRANTED
+
+@Composable
+fun SetupScreen(onDone: () -> Unit) {
+ val context = LocalContext.current
+ // Re-read when coming back from a system dialog or the settings.
+ var tick by remember { mutableIntStateOf(0) }
+ LaunchedEffect(Unit) { while (true) { kotlinx.coroutines.delay(800); tick++ } }
+ val launcher = rememberLauncherForActivityResult(ActivityResultContracts.RequestPermission()) { tick++ }
+
+ Column(
+ Modifier.fillMaxSize().background(AppBackground).statusBarsPadding().navigationBarsPadding()
+ .verticalScroll(rememberScrollState()).padding(horizontal = 20.dp, vertical = 24.dp),
+ verticalArrangement = Arrangement.spacedBy(12.dp),
+ ) {
+ Text(stringResource(R.string.setup_title), color = Color.White, fontSize = 26.sp, fontWeight = FontWeight.Bold)
+ Text(stringResource(R.string.setup_subtitle), color = Color(0xFFB3B3B3), fontSize = 14.sp)
+ Spacer(Modifier.height(8.dp))
+ @Suppress("UNUSED_EXPRESSION") tick
+ if (Build.VERSION.SDK_INT >= 33) SetupRow(
+ stringResource(R.string.setup_notifications_title), stringResource(R.string.setup_notifications_detail),
+ granted(context, Manifest.permission.POST_NOTIFICATIONS),
+ ) { launcher.launch(Manifest.permission.POST_NOTIFICATIONS) }
+ SetupRow(
+ stringResource(R.string.setup_local_title), stringResource(R.string.setup_local_detail),
+ LocalMusic.hasPermission(context),
+ ) { launcher.launch(LocalMusic.permission) }
+ if (Build.VERSION.SDK_INT >= 31) SetupRow(
+ stringResource(R.string.setup_bluetooth_title), stringResource(R.string.setup_bluetooth_detail),
+ granted(context, Manifest.permission.BLUETOOTH_CONNECT),
+ ) { launcher.launch(Manifest.permission.BLUETOOTH_CONNECT) }
+ SetupRow(
+ stringResource(R.string.setup_battery_title), stringResource(R.string.setup_battery_detail),
+ BatteryExemption.isExempt(context),
+ ) { BatteryExemption.request(context) }
+ Spacer(Modifier.height(12.dp))
+ Button(
+ onClick = { Setup.done(context); onDone() },
+ colors = ButtonDefaults.buttonColors(containerColor = Color(0xFF1DB954), contentColor = Color.Black),
+ modifier = Modifier.fillMaxWidth().height(50.dp),
+ ) { Text(stringResource(R.string.setup_continue), fontWeight = FontWeight.Bold, fontSize = 16.sp) }
+ }
+}
+
+@Composable
+private fun SetupRow(title: String, detail: String, on: Boolean, onEnable: () -> Unit) {
+ Row(
+ verticalAlignment = Alignment.CenterVertically,
+ modifier = Modifier.fillMaxWidth().background(Color(0xFF1E1E1E), RoundedCornerShape(12.dp)).padding(16.dp),
+ ) {
+ Column(Modifier.weight(1f)) {
+ Text(title, color = Color.White, fontSize = 16.sp, fontWeight = FontWeight.SemiBold)
+ Text(detail, color = Color(0xFFB3B3B3), fontSize = 13.sp)
+ }
+ if (on) Icon(Icons.Default.CheckCircle, contentDescription = null, tint = Color(0xFF1DB954), modifier = Modifier.padding(start = 12.dp).size(28.dp))
+ else TextButton(onClick = onEnable) { Text(stringResource(R.string.setup_enable), color = Color(0xFF1DB954), fontWeight = FontWeight.Bold) }
+ }
+}
diff --git a/base/app/src/main/res/values-fr/myspoti_strings.xml b/base/app/src/main/res/values-fr/myspoti_strings.xml
index 4a9e81e0..9b36eabc 100644
--- a/base/app/src/main/res/values-fr/myspoti_strings.xml
+++ b/base/app/src/main/res/values-fr/myspoti_strings.xml
@@ -170,4 +170,19 @@
<string name="track_sort_artist">Artiste</string>
<string name="track_sort_album">Album</string>
<string name="track_sort_duration">Durée</string>
+ <string name="setup_title">Configurer Myspoti</string>
+ <string name="setup_subtitle">Autorise ce que tu veux ; tu pourras changer plus tard dans les réglages du téléphone.</string>
+ <string name="setup_notifications_title">Notifications</string>
+ <string name="setup_notifications_detail">Contrôles sur l\'écran verrouillé et dans les notifications</string>
+ <string name="setup_local_title">Sons locaux</string>
+ <string name="setup_local_detail">Lire les fichiers de musique du téléphone</string>
+ <string name="setup_bluetooth_title">Bluetooth</string>
+ <string name="setup_bluetooth_detail">Afficher le nom de ton casque ou de ton enceinte dans le lecteur</string>
+ <string name="setup_battery_title">Batterie sans restriction</string>
+ <string name="setup_battery_detail">La musique continue écran éteint</string>
+ <string name="setup_enable">Autoriser</string>
+ <string name="setup_continue">Continuer</string>
+ <string name="local_folders_button">Dossiers</string>
+ <string name="local_folders_title">Dossiers</string>
+ <string name="local_folders_detail">Choisis les dossiers affichés dans Fichiers locaux. Les applis de messagerie et les enregistrements sont masqués au départ.</string>
</resources>
diff --git a/base/app/src/main/res/values/myspoti_strings.xml b/base/app/src/main/res/values/myspoti_strings.xml
index 85dda9f7..a28621ae 100644
--- a/base/app/src/main/res/values/myspoti_strings.xml
+++ b/base/app/src/main/res/values/myspoti_strings.xml
@@ -170,4 +170,19 @@
<string name="track_sort_artist">Artist</string>
<string name="track_sort_album">Album</string>
<string name="track_sort_duration">Duration</string>
+ <string name="setup_title">Set up Myspoti</string>
+ <string name="setup_subtitle">Allow what you want; you can change it later in the phone settings.</string>
+ <string name="setup_notifications_title">Notifications</string>
+ <string name="setup_notifications_detail">Controls on the lock screen and in the notification shade</string>
+ <string name="setup_local_title">Local music</string>
+ <string name="setup_local_detail">Play the music files stored on the phone</string>
+ <string name="setup_bluetooth_title">Bluetooth</string>
+ <string name="setup_bluetooth_detail">Show the name of your headphones or speaker in the player</string>
+ <string name="setup_battery_title">Unrestricted battery</string>
+ <string name="setup_battery_detail">Music keeps playing with the screen off</string>
+ <string name="setup_enable">Allow</string>
+ <string name="setup_continue">Continue</string>
+ <string name="local_folders_button">Folders</string>
+ <string name="local_folders_title">Folders</string>
+ <string name="local_folders_detail">Choose the folders shown in Local Files. Messaging apps and recordings start hidden.</string>
</resources>