Skip to content

Native Android client for Spotify, built with Jetpack Compose

New releases of followed artists in a notification

kota-zo6ba184032bcf
diff --git a/base/app/src/main/java/app/myspoti/MyspotiApplication.kt b/base/app/src/main/java/app/myspoti/MyspotiApplication.kt
index 531b51ec..b53296a3 100644
--- a/base/app/src/main/java/app/myspoti/MyspotiApplication.kt
+++ b/base/app/src/main/java/app/myspoti/MyspotiApplication.kt
@@ -42,6 +42,8 @@ class MyspotiApplication : Application() {
com.music.spotui.extensions.Extensions.attempts.last().map { "play attempt" to it.summary() }
}
prefetch()
+ // New releases of the artists followed, said in a notification (a setting).
+ com.music.spotui.data.NewReleaseNotifier.start(this)
}
/**
diff --git a/base/app/src/main/java/com/music/spotui/data/NewReleaseNotifier.kt b/base/app/src/main/java/com/music/spotui/data/NewReleaseNotifier.kt
new file mode 100644
index 00000000..9e08ca1d
--- /dev/null
+++ b/base/app/src/main/java/com/music/spotui/data/NewReleaseNotifier.kt
@@ -0,0 +1,105 @@
+/* SPDX-License-Identifier: GPL-3.0-only */
+package com.music.spotui.data
+
+import android.Manifest
+import android.app.NotificationChannel
+import android.app.NotificationManager
+import android.app.PendingIntent
+import android.content.Context
+import android.content.Intent
+import android.content.pm.PackageManager
+import android.net.Uri
+import android.os.Build
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.setValue
+import androidx.core.app.NotificationCompat
+import androidx.core.app.NotificationManagerCompat
+import app.myspoti.engine.R
+import app.myspoti.host.android.Logbook
+import app.myspoti.host.android.MyspotiRuntime
+import kotlinx.coroutines.CoroutineScope
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.SupervisorJob
+import kotlinx.coroutines.delay
+import kotlinx.coroutines.flow.first
+import kotlinx.coroutines.launch
+
+/**
+ * A notification when an artist the user follows releases something (asked on Reddit, Discord
+ * and GitHub #125 #130): Spotify's own "What's New" feed is read while the app runs, at most
+ * every [GAP_MS], and what it did not hold the last time is said, five at most, a tap opening
+ * the release. The first read only remembers the feed: nothing old is announced.
+ */
+object NewReleaseNotifier {
+ private const val PREFS = "new_releases"
+ private const val KEY_ON = "on"
+ private const val KEY_SEEN = "seen"
+ private const val KEY_AT = "checked_at"
+ private const val CHANNEL = "new_releases"
+ private const val GROUP = "app.myspoti.new_releases"
+ private const val GAP_MS = 6 * 3_600_000L
+ private const val MAX_SHOWN = 5
+ private const val SEEN_KEPT = 300
+
+ /** The notifications are wanted (a setting, on by default). */
+ var on by mutableStateOf(true)
+ private set
+
+ fun setOn(context: Context, value: Boolean) {
+ on = value
+ context.getSharedPreferences(PREFS, 0).edit().putBoolean(KEY_ON, value).apply()
+ }
+
+ /** Started once with the app: waits for the session, then looks every hour whether a read is due. */
+ fun start(context: Context) {
+ val app = context.applicationContext
+ on = app.getSharedPreferences(PREFS, 0).getBoolean(KEY_ON, true)
+ CoroutineScope(SupervisorJob() + Dispatchers.IO).launch {
+ MyspotiRuntime.api.ready.first { it }
+ while (true) {
+ if (on && signedIn(app)) runCatching { checkIfDue(app) }.onFailure { Logbook.log("new releases: not read (${it.javaClass.simpleName})") }
+ delay(3_600_000L)
+ }
+ }
+ }
+
+ private fun signedIn(context: Context) = context.getSharedPreferences("myspoti_prefs", Context.MODE_PRIVATE).getBoolean("LoggedIn", false)
+
+ private suspend fun checkIfDue(context: Context) {
+ val prefs = context.getSharedPreferences(PREFS, 0)
+ val now = System.currentTimeMillis()
+ if (now - prefs.getLong(KEY_AT, 0L) in 0 until GAP_MS) return
+ val feed = MyspotiRuntime.api.home.whatsNew(0, 30).items
+ val seen = prefs.getString(KEY_SEEN, null)?.split('\n')?.filter { it.isNotBlank() }
+ val fresh = if (seen == null) emptyList() else feed.filter { it.uri !in seen }
+ prefs.edit()
+ .putString(KEY_SEEN, (feed.map { it.uri } + seen.orEmpty()).distinct().take(SEEN_KEPT).joinToString("\n"))
+ .putLong(KEY_AT, now).apply()
+ Logbook.log("new releases: ${feed.size} in the feed, ${fresh.size} new${if (seen == null) " (first read, nothing said)" else ""}")
+ if (fresh.isNotEmpty()) show(context, fresh.take(MAX_SHOWN))
+ }
+
+ private fun show(context: Context, releases: List<app.myspoti.api.Album>) {
+ if (Build.VERSION.SDK_INT >= 33 &&
+ context.checkSelfPermission(Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) return
+ val manager = context.getSystemService(NotificationManager::class.java) ?: return
+ if (manager.getNotificationChannel(CHANNEL) == null)
+ manager.createNotificationChannel(NotificationChannel(CHANNEL, context.getString(R.string.notify_releases_channel), NotificationManager.IMPORTANCE_DEFAULT))
+ val compat = NotificationManagerCompat.from(context)
+ releases.forEach { a ->
+ val id = a.uri.substringAfterLast(':')
+ val open = Intent(Intent.ACTION_VIEW, Uri.parse("https://open.spotify.com/album/$id")).setClassName(context, "app.myspoti.MainActivity")
+ .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
+ val tap = PendingIntent.getActivity(context, id.hashCode(), open, PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT)
+ val artist = a.artists.joinToString { it.name }
+ val n = NotificationCompat.Builder(context, CHANNEL)
+ .setSmallIcon(R.drawable.msp_ic_notification)
+ .setContentTitle(context.getString(R.string.notify_release_title, artist))
+ .setContentText(a.name)
+ .setContentIntent(tap).setAutoCancel(true).setGroup(GROUP)
+ .build()
+ runCatching { compat.notify(id.hashCode(), n) }
+ }
+ }
+}
diff --git a/base/app/src/main/java/com/music/spotui/ui/immersive/pages/ImmersiveSettingsScreen.kt b/base/app/src/main/java/com/music/spotui/ui/immersive/pages/ImmersiveSettingsScreen.kt
index ca2c631a..443fc36c 100644
--- a/base/app/src/main/java/com/music/spotui/ui/immersive/pages/ImmersiveSettingsScreen.kt
+++ b/base/app/src/main/java/com/music/spotui/ui/immersive/pages/ImmersiveSettingsScreen.kt
@@ -247,6 +247,14 @@ private fun PlaybackPage(navController: NavController, open: (SettingsPage) -> U
detail = stringResource(R.string.settings_autoplay_detail),
)
}
+ row {
+ ImmersiveSwitchRow(
+ stringResource(R.string.settings_release_notify),
+ checked = com.music.spotui.data.NewReleaseNotifier.on,
+ onChecked = { com.music.spotui.data.NewReleaseNotifier.setOn(ctx, it) },
+ detail = stringResource(R.string.settings_release_notify_detail),
+ )
+ }
row {
ImmersiveSwitchRow(
stringResource(R.string.myspoti_shuffle_title),
diff --git a/base/app/src/main/java/com/music/spotui/ui/screens/SettingsScreen.kt b/base/app/src/main/java/com/music/spotui/ui/screens/SettingsScreen.kt
index 8c1b426a..0d34a2c7 100644
--- a/base/app/src/main/java/com/music/spotui/ui/screens/SettingsScreen.kt
+++ b/base/app/src/main/java/com/music/spotui/ui/screens/SettingsScreen.kt
@@ -113,6 +113,12 @@ fun SettingsScreen(navController: NavController) {
checked = com.music.spotui.data.preferences.AutoplayPref.on,
onChecked = { com.music.spotui.data.preferences.AutoplayPref.set(ctx, it) },
)
+ OptionRow(
+ label = stringResource(R.string.settings_release_notify),
+ detail = stringResource(R.string.settings_release_notify_detail),
+ checked = com.music.spotui.data.NewReleaseNotifier.on,
+ onChecked = { com.music.spotui.data.NewReleaseNotifier.setOn(ctx, it) },
+ )
OptionRow(
label = stringResource(R.string.myspoti_shuffle_title),
detail = stringResource(R.string.myspoti_shuffle_detail),
diff --git a/base/app/src/main/res/values-de/myspoti_strings.xml b/base/app/src/main/res/values-de/myspoti_strings.xml
index 9a4d679f..f9c66192 100644
--- a/base/app/src/main/res/values-de/myspoti_strings.xml
+++ b/base/app/src/main/res/values-de/myspoti_strings.xml
@@ -765,4 +765,8 @@
<string name="automix_reason_mobile_data">Gerade kein Mix: Der nächste Stream wird über mobile Daten nicht analysiert und daher übergeblendet.</string>
<string name="automix_reason_frugal">Gerade kein Mix: Der nächste Song wurde im Energiesparmodus nicht rechtzeitig analysiert und wird übergeblendet.</string>
<string name="automix_reason_not_analyzed">Gerade kein Mix: Der nächste Song konnte nicht rechtzeitig analysiert werden und wird übergeblendet.</string>
+ <string name="notify_releases_channel">Neuerscheinungen</string>
+ <string name="notify_release_title">Neu von %1$s</string>
+ <string name="settings_release_notify">Benachrichtigungen für Neuerscheinungen</string>
+ <string name="settings_release_notify_detail">Eine Benachrichtigung, wenn ein Künstler, dem du folgst, etwas veröffentlicht; alle paar Stunden geprüft, solange Myspoti läuft</string>
</resources>
diff --git a/base/app/src/main/res/values-el/myspoti_strings.xml b/base/app/src/main/res/values-el/myspoti_strings.xml
index 3ab70293..cafdc69e 100644
--- a/base/app/src/main/res/values-el/myspoti_strings.xml
+++ b/base/app/src/main/res/values-el/myspoti_strings.xml
@@ -765,4 +765,8 @@
<string name="automix_reason_mobile_data">Καμία μίξη τώρα: η επόμενη ροή δεν αναλύεται με δεδομένα κινητής, οπότε αλλάζει με σβήσιμο.</string>
<string name="automix_reason_frugal">Καμία μίξη τώρα: το επόμενο τραγούδι δεν αναλύθηκε εγκαίρως λόγω εξοικονόμησης ενέργειας, οπότε αλλάζει με σβήσιμο.</string>
<string name="automix_reason_not_analyzed">Καμία μίξη τώρα: το επόμενο τραγούδι δεν αναλύθηκε εγκαίρως, οπότε αλλάζει με σβήσιμο.</string>
+ <string name="notify_releases_channel">Νέες κυκλοφορίες</string>
+ <string name="notify_release_title">Νέο από %1$s</string>
+ <string name="settings_release_notify">Ειδοποιήσεις νέων κυκλοφοριών</string>
+ <string name="settings_release_notify_detail">Μια ειδοποίηση όταν ένας καλλιτέχνης που ακολουθείς κυκλοφορεί κάτι, με έλεγχο κάθε λίγες ώρες όσο τρέχει το Myspoti</string>
</resources>
diff --git a/base/app/src/main/res/values-es/myspoti_strings.xml b/base/app/src/main/res/values-es/myspoti_strings.xml
index 5171dd7d..c7a932a0 100644
--- a/base/app/src/main/res/values-es/myspoti_strings.xml
+++ b/base/app/src/main/res/values-es/myspoti_strings.xml
@@ -765,4 +765,8 @@
<string name="automix_reason_mobile_data">Sin mezcla ahora: la siguiente transmisión no se analiza con datos móviles, así que cambia con un fundido.</string>
<string name="automix_reason_frugal">Sin mezcla ahora: la siguiente canción no se analizó a tiempo por el ahorro de energía, así que cambia con un fundido.</string>
<string name="automix_reason_not_analyzed">Sin mezcla ahora: la siguiente canción no se pudo analizar a tiempo, así que cambia con un fundido.</string>
+ <string name="notify_releases_channel">Novedades</string>
+ <string name="notify_release_title">Nuevo de %1$s</string>
+ <string name="settings_release_notify">Notificaciones de novedades</string>
+ <string name="settings_release_notify_detail">Una notificación cuando un artista que sigues publica algo, comprobado cada pocas horas mientras Myspoti está abierto</string>
</resources>
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 1eb256be..2475e06f 100644
--- a/base/app/src/main/res/values-fr/myspoti_strings.xml
+++ b/base/app/src/main/res/values-fr/myspoti_strings.xml
@@ -770,4 +770,8 @@
<string name="automix_reason_mobile_data">Pas de mix pour l\'instant : le flux suivant n\'est pas analysé en données mobiles, il passera en fondu.</string>
<string name="automix_reason_frugal">Pas de mix pour l\'instant : le morceau suivant n\'a pas été analysé à temps en économie d\'énergie, il passera en fondu.</string>
<string name="automix_reason_not_analyzed">Pas de mix pour l\'instant : le morceau suivant n\'a pas pu être analysé à temps, il passera en fondu.</string>
+ <string name="notify_releases_channel">Nouveautés</string>
+ <string name="notify_release_title">Nouveau de %1$s</string>
+ <string name="settings_release_notify">Notifications des nouveautés</string>
+ <string name="settings_release_notify_detail">Une notification quand un artiste que tu suis sort quelque chose, vérifié toutes les quelques heures pendant que Myspoti tourne</string>
</resources>
diff --git a/base/app/src/main/res/values-it/myspoti_strings.xml b/base/app/src/main/res/values-it/myspoti_strings.xml
index dc5db3e0..a64edf9e 100644
--- a/base/app/src/main/res/values-it/myspoti_strings.xml
+++ b/base/app/src/main/res/values-it/myspoti_strings.xml
@@ -765,4 +765,8 @@
<string name="automix_reason_mobile_data">Nessun mix ora: lo stream successivo non viene analizzato con i dati mobili, quindi cambia in dissolvenza.</string>
<string name="automix_reason_frugal">Nessun mix ora: il brano successivo non è stato analizzato in tempo per il risparmio energetico, quindi cambia in dissolvenza.</string>
<string name="automix_reason_not_analyzed">Nessun mix ora: il brano successivo non è stato analizzato in tempo, quindi cambia in dissolvenza.</string>
+ <string name="notify_releases_channel">Nuove uscite</string>
+ <string name="notify_release_title">Novità da %1$s</string>
+ <string name="settings_release_notify">Notifiche delle nuove uscite</string>
+ <string name="settings_release_notify_detail">Una notifica quando un artista che segui pubblica qualcosa, controllato ogni poche ore mentre Myspoti è attivo</string>
</resources>
diff --git a/base/app/src/main/res/values-pl/myspoti_strings.xml b/base/app/src/main/res/values-pl/myspoti_strings.xml
index 0a175915..a095e2f9 100644
--- a/base/app/src/main/res/values-pl/myspoti_strings.xml
+++ b/base/app/src/main/res/values-pl/myspoti_strings.xml
@@ -780,4 +780,8 @@
<string name="automix_reason_mobile_data">Teraz bez miksu: następny strumień nie jest analizowany przez dane komórkowe, więc zmieni się z przejściem.</string>
<string name="automix_reason_frugal">Teraz bez miksu: następny utwór nie został przeanalizowany na czas w trybie oszczędzania energii, więc zmieni się z przejściem.</string>
<string name="automix_reason_not_analyzed">Teraz bez miksu: następnego utworu nie udało się przeanalizować na czas, więc zmieni się z przejściem.</string>
+ <string name="notify_releases_channel">Nowości</string>
+ <string name="notify_release_title">Nowość od %1$s</string>
+ <string name="settings_release_notify">Powiadomienia o nowościach</string>
+ <string name="settings_release_notify_detail">Powiadomienie, gdy obserwowany artysta coś wyda; sprawdzane co kilka godzin, gdy Myspoti działa</string>
</resources>
diff --git a/base/app/src/main/res/values-pt-rBR/myspoti_strings.xml b/base/app/src/main/res/values-pt-rBR/myspoti_strings.xml
index acb1b665..ae2f03b1 100644
--- a/base/app/src/main/res/values-pt-rBR/myspoti_strings.xml
+++ b/base/app/src/main/res/values-pt-rBR/myspoti_strings.xml
@@ -744,4 +744,8 @@
<string name="automix_reason_mobile_data">Sem mixagem agora: o próximo stream não é analisado nos dados móveis, então muda com um fade.</string>
<string name="automix_reason_frugal">Sem mixagem agora: a próxima música não foi analisada a tempo por causa da economia de energia, então muda com um fade.</string>
<string name="automix_reason_not_analyzed">Sem mixagem agora: a próxima música não pôde ser analisada a tempo, então muda com um fade.</string>
+ <string name="notify_releases_channel">Lançamentos</string>
+ <string name="notify_release_title">Novo de %1$s</string>
+ <string name="settings_release_notify">Notificações de lançamentos</string>
+ <string name="settings_release_notify_detail">Uma notificação quando um artista que você segue lança algo, verificado a cada poucas horas enquanto o Myspoti está aberto</string>
</resources>
diff --git a/base/app/src/main/res/values-pt-rPT/myspoti_strings.xml b/base/app/src/main/res/values-pt-rPT/myspoti_strings.xml
index cbc65639..4c5d359f 100644
--- a/base/app/src/main/res/values-pt-rPT/myspoti_strings.xml
+++ b/base/app/src/main/res/values-pt-rPT/myspoti_strings.xml
@@ -711,4 +711,8 @@
<string name="automix_reason_mobile_data">Sem mistura agora: a próxima emissão não é analisada com dados móveis, por isso muda com um desvanecimento.</string>
<string name="automix_reason_frugal">Sem mistura agora: a próxima música não foi analisada a tempo por causa da poupança de energia, por isso muda com um desvanecimento.</string>
<string name="automix_reason_not_analyzed">Sem mistura agora: a próxima música não pôde ser analisada a tempo, por isso muda com um desvanecimento.</string>
+ <string name="notify_releases_channel">Novidades</string>
+ <string name="notify_release_title">Novo de %1$s</string>
+ <string name="settings_release_notify">Notificações de novidades</string>
+ <string name="settings_release_notify_detail">Uma notificação quando um artista que segues lança algo, verificado a cada poucas horas enquanto o Myspoti está aberto</string>
</resources>
diff --git a/base/app/src/main/res/values-pt/myspoti_strings.xml b/base/app/src/main/res/values-pt/myspoti_strings.xml
index 6c208774..d59e2453 100644
--- a/base/app/src/main/res/values-pt/myspoti_strings.xml
+++ b/base/app/src/main/res/values-pt/myspoti_strings.xml
@@ -765,4 +765,8 @@
<string name="automix_reason_mobile_data">Sem mistura agora: o próximo stream não é analisado com dados móveis, por isso muda com um fade.</string>
<string name="automix_reason_frugal">Sem mistura agora: a próxima música não foi analisada a tempo por causa da poupança de energia, por isso muda com um fade.</string>
<string name="automix_reason_not_analyzed">Sem mistura agora: a próxima música não pôde ser analisada a tempo, por isso muda com um fade.</string>
+ <string name="notify_releases_channel">Novidades</string>
+ <string name="notify_release_title">Novo de %1$s</string>
+ <string name="settings_release_notify">Notificações de novidades</string>
+ <string name="settings_release_notify_detail">Uma notificação quando um artista que segues lança algo, verificado a cada poucas horas enquanto o Myspoti está aberto</string>
</resources>
diff --git a/base/app/src/main/res/values-ru/myspoti_strings.xml b/base/app/src/main/res/values-ru/myspoti_strings.xml
index a15d9460..e6652725 100644
--- a/base/app/src/main/res/values-ru/myspoti_strings.xml
+++ b/base/app/src/main/res/values-ru/myspoti_strings.xml
@@ -780,4 +780,8 @@
<string name="automix_reason_mobile_data">Сейчас без сведения: следующий поток не анализируется по мобильной сети, поэтому сменится плавным переходом.</string>
<string name="automix_reason_frugal">Сейчас без сведения: следующий трек не успел проанализироваться из-за энергосбережения, поэтому сменится плавным переходом.</string>
<string name="automix_reason_not_analyzed">Сейчас без сведения: следующий трек не удалось проанализировать вовремя, поэтому сменится плавным переходом.</string>
+ <string name="notify_releases_channel">Новинки</string>
+ <string name="notify_release_title">Новое от %1$s</string>
+ <string name="settings_release_notify">Уведомления о новинках</string>
+ <string name="settings_release_notify_detail">Уведомление, когда артист, на которого вы подписаны, что-то выпускает; проверка каждые несколько часов, пока Myspoti работает</string>
</resources>
diff --git a/base/app/src/main/res/values-zh/myspoti_strings.xml b/base/app/src/main/res/values-zh/myspoti_strings.xml
index cf355014..c4f6966b 100644
--- a/base/app/src/main/res/values-zh/myspoti_strings.xml
+++ b/base/app/src/main/res/values-zh/myspoti_strings.xml
@@ -765,4 +765,8 @@
<string name="automix_reason_mobile_data">暂不混音:使用移动数据时不分析下一个流,因此将淡入淡出。</string>
<string name="automix_reason_frugal">暂不混音:节能模式下下一首歌曲未能及时分析,因此将淡入淡出。</string>
<string name="automix_reason_not_analyzed">暂不混音:下一首歌曲未能及时分析,因此将淡入淡出。</string>
+ <string name="notify_releases_channel">新发行</string>
+ <string name="notify_release_title">%1$s 的新作品</string>
+ <string name="settings_release_notify">新发行通知</string>
+ <string name="settings_release_notify_detail">你关注的艺人发布新作品时发送通知,Myspoti 运行时每隔几小时检查一次</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 c6ff5c8d..722ea3e7 100644
--- a/base/app/src/main/res/values/myspoti_strings.xml
+++ b/base/app/src/main/res/values/myspoti_strings.xml
@@ -772,4 +772,8 @@
<string name="automix_reason_mobile_data">No mix now: the next stream is not analysed on mobile data, so it fades.</string>
<string name="automix_reason_frugal">No mix now: the next song was not analysed in time while saving energy, so it fades.</string>
<string name="automix_reason_not_analyzed">No mix now: the next song could not be analysed in time, so it fades.</string>
+ <string name="notify_releases_channel">New releases</string>
+ <string name="notify_release_title">New from %1$s</string>
+ <string name="settings_release_notify">New release notifications</string>
+ <string name="settings_release_notify_detail">A notification when an artist you follow releases something, checked every few hours while Myspoti runs</string>
</resources>