Skip to content

Unofficial YouTube Music / Spotify Premium client for Android, built in Liquid Glass. Audio effects, Spotify Connect, listening history, 8 languages. Rust core on librespot.

Turn the monthly recap into a library page and count YouTube Music listens

Lelonio264732e8131b
diff --git a/app/src/main/java/dev/lelonio/square/backend/youtube/YouTubeBackend.kt b/app/src/main/java/dev/lelonio/square/backend/youtube/YouTubeBackend.kt
index f3c8ffc..ebe9858 100644
--- a/app/src/main/java/dev/lelonio/square/backend/youtube/YouTubeBackend.kt
+++ b/app/src/main/java/dev/lelonio/square/backend/youtube/YouTubeBackend.kt
@@ -426,6 +426,29 @@ class YouTubeBackend(private val account: YouTubeAccount) : MusicBackend {
artworkUrl = item.thumbnail,
)
+ /**
+ * The account's YouTube Music history: sections, newest first, each with
+ * its songs, newest first. Null when no account is signed in.
+ *
+ * Asked for in English whatever the phone reads, because the section
+ * titles are the only dates the page has ("Today", "Last week", a month)
+ * and they have to be read back into days; see YouTubeListening. The
+ * language is swapped under the same lock as the country in [wherever].
+ */
+ suspend fun listeningHistory(): List<Pair<String, List<CatalogTrack>>>? = withContext(Dispatchers.IO) {
+ if (!account.isSignedIn) return@withContext null
+ val page = regionLock.withLock {
+ val kept = YouTube.locale
+ YouTube.locale = kept.copy(hl = "en")
+ try {
+ YouTube.musicHistory()
+ } finally {
+ YouTube.locale = kept
+ }
+ }.getOrThrow()
+ page.sections.orEmpty().map { section -> section.title to section.songs.map(::toCatalogTrack) }
+ }
+
private fun toCatalogTrack(item: SongItem): CatalogTrack {
// Every name its own way in, and the record too: what makes the lines
// under the title in the player lead somewhere, as they do for Spotify.
diff --git a/app/src/main/java/dev/lelonio/square/data/ListeningHistory.kt b/app/src/main/java/dev/lelonio/square/data/ListeningHistory.kt
index a3b7a53..3c8736c 100644
--- a/app/src/main/java/dev/lelonio/square/data/ListeningHistory.kt
+++ b/app/src/main/java/dev/lelonio/square/data/ListeningHistory.kt
@@ -54,6 +54,23 @@ object ListeningHistory {
} else events + ListeningEvent("spotify:$at:${track.uri}", track, at, qualified = true, spotifyAt = at)
}
+ /**
+ * A play read from an account that keeps no times; see [YouTubeListening].
+ *
+ * Square's own measurement of the same song inside [window] is that play,
+ * once: it is marked as seen by the account and nothing is added. Otherwise
+ * the play is added at [at].
+ */
+ fun mergeRemote(events: List<ListeningEvent>, track: CatalogTrack, at: Long, window: LongRange): List<ListeningEvent> {
+ val match = events.filter {
+ it.spotifyAt == null && it.id.startsWith("local:") && it.qualified &&
+ it.track.uri == track.uri && it.startedAt in window
+ }.minByOrNull { it.startedAt }
+ return if (match != null) events.map {
+ if (it.id == match.id) it.copy(spotifyAt = it.startedAt) else it
+ } else events + ListeningEvent("remote:$at:${track.uri}", track, at, qualified = true, spotifyAt = at)
+ }
+
fun summarize(events: List<ListeningEvent>, month: YearMonth, zone: ZoneId = ZoneId.systemDefault()): MonthlyListening {
val start = month.atDay(1).atStartOfDay(zone).toInstant().toEpochMilli()
val end = month.plusMonths(1).atDay(1).atStartOfDay(zone).toInstant().toEpochMilli()
diff --git a/app/src/main/java/dev/lelonio/square/data/ListeningStore.kt b/app/src/main/java/dev/lelonio/square/data/ListeningStore.kt
index 91a2fc8..30f8d9a 100644
--- a/app/src/main/java/dev/lelonio/square/data/ListeningStore.kt
+++ b/app/src/main/java/dev/lelonio/square/data/ListeningStore.kt
@@ -10,37 +10,115 @@ import kotlinx.coroutines.withContext
import kotlinx.serialization.builtins.ListSerializer
import kotlinx.serialization.json.Json
+/**
+ * What was listened to, kept apart per source.
+ *
+ * One history for the signed-in Spotify account and one for YouTube Music.
+ * There used to be a single history, for Spotify alone: YouTube Music was not
+ * recorded at all, and a history that belonged to one account at a time could
+ * only have been shared by throwing the other's away at every switch.
+ * [events] is the history of the source on screen; see [show].
+ */
class ListeningStore(context: Context) {
+ enum class Source { SPOTIFY, YOUTUBE_MUSIC }
+
private val prefs = context.getSharedPreferences("square_listening", Context.MODE_PRIVATE)
private val json = Json { ignoreUnknownKeys = true }
private val serializer = ListSerializer(ListeningEvent.serializer())
private val lock = Mutex()
- private val mutable = MutableStateFlow(runCatching {
- json.decodeFromString(serializer, prefs.getString("events", "[]")!!)
- }.getOrDefault(emptyList()))
- val events = mutable.asStateFlow()
+ private val cache = HashMap<String, List<ListeningEvent>>()
+ private var source = Source.SPOTIFY
+
+ init {
+ // The single history from before, which was the Spotify account's.
+ val legacy = prefs.getString("events", null)
+ val owner = account
+ if (legacy != null) {
+ prefs.edit().apply { if (owner != null) putString(key(owner), legacy) }.remove("events").apply()
+ }
+ }
+
+ /** The Spotify account whose history is kept. */
val account get() = prefs.getString("account", null)
+ private val mutable = MutableStateFlow(account?.let(::read).orEmpty())
+ val events = mutable.asStateFlow()
+
+ /** Who a source's listens are filed under; null while Spotify has no account. */
+ fun ownerOf(source: Source): String? = when (source) {
+ Source.SPOTIFY -> account
+ Source.YOUTUBE_MUSIC -> YOUTUBE_OWNER
+ }
+
+ /** Puts this source's history in [events]. */
+ suspend fun show(source: Source) = withContext(Dispatchers.IO) { lock.withLock {
+ mutable.value = ownerOf(source)?.let(::read).orEmpty()
+ } }
+
+ /** A different Spotify account signed in: the last one's history goes. */
suspend fun useAccount(id: String) = withContext(Dispatchers.IO) { lock.withLock {
- if (account != id) {
- mutable.value = emptyList()
- prefs.edit().putString("account", id).remove("events").apply()
- }
+ val old = account
+ if (old == id) return@withLock
+ prefs.edit().putString("account", id).apply { if (old != null) remove(key(old)) }.apply()
+ old?.let(cache::remove)
+ if (source == Source.SPOTIFY) mutable.value = read(id)
} }
+
suspend fun record(event: ListeningEvent, owner: String) = withContext(Dispatchers.IO) { lock.withLock {
- if (account != owner) return@withLock
- save(ListeningHistory.record(mutable.value, event))
+ if (!known(owner)) return@withLock
+ save(owner, ListeningHistory.record(read(owner), event))
} }
+
suspend fun import(plays: List<Pair<CatalogTrack, Long>>, owner: String) = withContext(Dispatchers.IO) { lock.withLock {
- if (account != owner) return@withLock
- save(plays.fold(mutable.value) { events, (track, at) -> ListeningHistory.merge(events, track, at) })
+ if (!known(owner)) return@withLock
+ save(owner, plays.fold(read(owner)) { events, (track, at) -> ListeningHistory.merge(events, track, at) })
} }
+
+ /** Plays read from YouTube Music's history; see [YouTubeListening.plays]. */
+ suspend fun importRemote(plays: List<YouTubeListening.RemotePlay>, owner: String) = withContext(Dispatchers.IO) { lock.withLock {
+ if (!known(owner)) return@withLock
+ save(owner, plays.fold(read(owner)) { events, play ->
+ ListeningHistory.mergeRemote(events, play.track, play.at, play.window)
+ })
+ } }
+
+ /** The songs YouTube Music's history listed last time, newest first, and when. */
+ fun youtubeReading(): Pair<List<String>, Long>? {
+ val at = prefs.getLong("youtube-read-at", 0L).takeIf { it > 0 } ?: return null
+ val songs = prefs.getString("youtube-read", null)?.split('\n')?.filter { it.isNotEmpty() } ?: return null
+ return songs to at
+ }
+
+ fun keepYoutubeReading(songs: List<String>, at: Long) {
+ prefs.edit().putString("youtube-read", songs.joinToString("\n")).putLong("youtube-read-at", at).apply()
+ }
+
+ /** Signing out of Spotify: its history goes, YouTube Music's stays. */
suspend fun clear() = withContext(Dispatchers.IO) { lock.withLock {
- prefs.edit().clear().apply(); mutable.value = emptyList()
+ val old = account
+ prefs.edit().remove("account").apply { if (old != null) remove(key(old)) }.apply()
+ old?.let(cache::remove)
+ if (source == Source.SPOTIFY) mutable.value = emptyList()
} }
- private fun save(events: List<ListeningEvent>) {
- if (events == mutable.value) return
- mutable.value = events
- prefs.edit().putString("events", json.encodeToString(serializer, events)).apply()
+
+ private fun known(owner: String) = owner == YOUTUBE_OWNER || owner == account
+
+ private fun key(owner: String) = "events:$owner"
+
+ private fun read(owner: String): List<ListeningEvent> = cache.getOrPut(owner) {
+ runCatching { json.decodeFromString(serializer, prefs.getString(key(owner), null) ?: "[]") }
+ .getOrDefault(emptyList())
+ }
+
+ private fun save(owner: String, events: List<ListeningEvent>) {
+ if (events == read(owner)) return
+ cache[owner] = events
+ prefs.edit().putString(key(owner), json.encodeToString(serializer, events)).apply()
+ if (ownerOf(source) == owner) mutable.value = events
+ }
+
+ companion object {
+ const val YOUTUBE_OWNER = "youtube-music"
}
}
diff --git a/app/src/main/java/dev/lelonio/square/data/YouTubeListening.kt b/app/src/main/java/dev/lelonio/square/data/YouTubeListening.kt
new file mode 100644
index 0000000..bde7b83
--- /dev/null
+++ b/app/src/main/java/dev/lelonio/square/data/YouTubeListening.kt
@@ -0,0 +1,115 @@
+package dev.lelonio.square.data
+
+import java.time.LocalDate
+import java.time.YearMonth
+import java.time.ZoneId
+import java.time.format.DateTimeFormatter
+import java.time.format.DateTimeFormatterBuilder
+import java.util.Locale
+
+/**
+ * What YouTube Music's history page can say about when, and how often.
+ *
+ * The page is not a log. It lists each song once, where it was last played,
+ * newest first, under headings rather than times ("Today", "Last week", a
+ * month). So two things are read out of it here: the day a heading stands for,
+ * for a first reading of what came before Square was there to watch; and,
+ * between one reading and the next, which songs came back to the top, which is
+ * what a song played again does.
+ */
+object YouTubeListening {
+ /** A play read from the account, with the stretch of time it happened in. */
+ data class RemotePlay(val track: CatalogTrack, val at: Long, val window: LongRange)
+
+ /**
+ * The day a heading of the page stands for, asked for in English; null for
+ * a heading this does not know, whose songs are then left out rather than
+ * given a day they may not have.
+ */
+ fun sectionDay(title: String, today: LocalDate): LocalDate? {
+ val words = title.trim().lowercase(Locale.ENGLISH)
+ val day = when (words) {
+ "today" -> today
+ "yesterday" -> today.minusDays(1)
+ "this week" -> today.minusDays(2)
+ "last week" -> today.minusWeeks(1)
+ "this month" -> today.minusDays(14).coerceAtLeast(today.withDayOfMonth(1))
+ "last month" -> today.minusMonths(1).withDayOfMonth(15)
+ else -> month(words, today)?.let { month ->
+ if (month == YearMonth.from(today)) today.withDayOfMonth(1) else month.atDay(15)
+ }
+ }
+ return day?.takeIf { it <= today }
+ }
+
+ private val monthYear: DateTimeFormatter = DateTimeFormatterBuilder()
+ .parseCaseInsensitive().appendPattern("MMMM yyyy").toFormatter(Locale.ENGLISH)
+ private val monthOnly: DateTimeFormatter = DateTimeFormatterBuilder()
+ .parseCaseInsensitive().appendPattern("MMMM").toFormatter(Locale.ENGLISH)
+
+ private fun month(words: String, today: LocalDate): YearMonth? =
+ runCatching { YearMonth.parse(words, monthYear) }.getOrNull()
+ ?: runCatching {
+ // A month without a year is this year's, or last year's when
+ // it has not come round yet.
+ val named = java.time.Month.from(monthOnly.parse(words))
+ val month = YearMonth.of(today.year, named)
+ if (month > YearMonth.from(today)) month.minusYears(1) else month
+ }.getOrNull()
+
+ /**
+ * The songs played since [previous] was read, newest first.
+ *
+ * A song played again leaves its place and goes to the top, so [now] is
+ * some songs on top of [previous] with those songs taken out of it. The
+ * smallest such top is what was played. Null when the two readings have
+ * nothing in common, which is not a later reading of the same history: a
+ * different account, or one cleared.
+ */
+ fun replays(previous: List<String>, now: List<String>): List<String>? {
+ if (now.isEmpty()) return emptyList()
+ if (previous.isEmpty() || previous.none { it in now.toSet() }) return null
+ for (top in 0..now.size) {
+ val played = now.subList(0, top).toSet()
+ val rest = now.subList(top, now.size)
+ val before = previous.filter { it !in played }
+ val overlap = minOf(rest.size, before.size)
+ if (rest.subList(0, overlap) == before.subList(0, overlap)) return now.subList(0, top)
+ }
+ return now
+ }
+
+ /**
+ * The plays to file from one reading of the page.
+ *
+ * The first reading, or one of a history that is no longer the one last
+ * read, takes each song once on the day of its heading. Later readings take
+ * only what came back to the top, spread over the time since the last one,
+ * the newest at the end of it.
+ */
+ fun plays(
+ sections: List<Pair<String, List<CatalogTrack>>>,
+ previous: List<String>?,
+ previousAt: Long,
+ now: Long,
+ zone: ZoneId = ZoneId.systemDefault(),
+ ): List<RemotePlay> {
+ val songs = sections.flatMap { it.second }
+ val fresh = previous?.let { replays(it, songs.map { song -> song.uri }) }
+ if (fresh == null) {
+ val today = java.time.Instant.ofEpochMilli(now).atZone(zone).toLocalDate()
+ return sections.flatMap { (title, tracks) ->
+ val day = sectionDay(title, today) ?: return@flatMap emptyList()
+ val start = day.atStartOfDay(zone).toInstant().toEpochMilli()
+ val end = minOf(day.plusDays(1).atStartOfDay(zone).toInstant().toEpochMilli() - 1, now)
+ val at = minOf(day.atTime(12, 0).atZone(zone).toInstant().toEpochMilli(), now)
+ tracks.map { RemotePlay(it, at, start..end) }
+ }
+ }
+ val byUri = songs.associateBy { it.uri }
+ val span = (now - previousAt).coerceAtLeast(0)
+ return fresh.mapIndexed { index, uri ->
+ RemotePlay(byUri.getValue(uri), now - span * index / fresh.size, previousAt..now)
+ }
+ }
+}
diff --git a/app/src/main/java/dev/lelonio/square/playback/PlaybackService.kt b/app/src/main/java/dev/lelonio/square/playback/PlaybackService.kt
index f96e0f4..e5bf401 100644
--- a/app/src/main/java/dev/lelonio/square/playback/PlaybackService.kt
+++ b/app/src/main/java/dev/lelonio/square/playback/PlaybackService.kt
@@ -1550,18 +1550,23 @@ class PlaybackService : MediaLibraryService() {
}
try {
while (true) {
- val account = container.listeningStore.account
+ // Filed under the source it was played from: Spotify's
+ // account, or YouTube Music's history on this phone.
+ val source = when (container.preferences.backend.value) {
+ dev.lelonio.square.backend.BackendId.SPOTIFY -> dev.lelonio.square.data.ListeningStore.Source.SPOTIFY
+ dev.lelonio.square.backend.BackendId.YOUTUBE_MUSIC -> dev.lelonio.square.data.ListeningStore.Source.YOUTUBE_MUSIC
+ }
+ val account = container.listeningStore.ownerOf(source)
if (account != owner) { sampler.reset(); owner = account }
if (sampledPlayer !== player) {
sampledPlayer?.removeListener(listener)
sampledPlayer = player
player.addListener(listener)
}
- val spotify = container.preferences.backend.value == dev.lelonio.square.backend.BackendId.SPOTIFY
val remote = (player as? LibrespotPlayer)?.isRemotePlayback == true
val item = player.currentMediaItem
val metadata = item?.mediaMetadata
- val track = if (spotify && !remote && account != null && item != null &&
+ val track = if (!remote && account != null && item != null &&
!metadata?.title.isNullOrBlank()) CatalogTrack(
uri = item.mediaId,
name = metadata?.title.toString(),
diff --git a/app/src/main/java/dev/lelonio/square/ui/MainViewModel.kt b/app/src/main/java/dev/lelonio/square/ui/MainViewModel.kt
index 30ce173..79efcb0 100644
--- a/app/src/main/java/dev/lelonio/square/ui/MainViewModel.kt
+++ b/app/src/main/java/dev/lelonio/square/ui/MainViewModel.kt
@@ -1976,12 +1976,29 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {
}
val listeningEvents = container.listeningStore.events
+
+ init {
+ // The month in music is the one of the source in use.
+ viewModelScope.launch {
+ container.preferences.backend.collect { backend ->
+ container.listeningStore.show(
+ when (backend) {
+ BackendId.SPOTIFY -> dev.lelonio.square.data.ListeningStore.Source.SPOTIFY
+ BackendId.YOUTUBE_MUSIC -> dev.lelonio.square.data.ListeningStore.Source.YOUTUBE_MUSIC
+ },
+ )
+ }
+ }
+ }
private var listeningSync: kotlinx.coroutines.Job? = null
private var lastListeningSync = 0L
fun syncListeningHistory() {
- if (container.preferences.backend.value != dev.lelonio.square.backend.BackendId.SPOTIFY ||
- listeningSync?.isActive == true || System.currentTimeMillis() - lastListeningSync < 60_000) return
+ if (listeningSync?.isActive == true || System.currentTimeMillis() - lastListeningSync < 60_000) return
+ if (container.preferences.backend.value == dev.lelonio.square.backend.BackendId.YOUTUBE_MUSIC) {
+ syncYouTubeListening()
+ return
+ }
listeningSync = viewModelScope.launch {
runCatching {
val owner = meId ?: runCatching { dev.lelonio.square.nativecore.NativeBridge.username() }
@@ -2007,6 +2024,34 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {
}
}
+ /**
+ * Reads the account's YouTube Music history into the month in music.
+ *
+ * Only while the app is open, as Spotify's is: every few minutes, from the
+ * loop in SquareApp. Between two readings a song played again goes back to
+ * the top of the page, and that is what is counted; see YouTubeListening.
+ */
+ private fun syncYouTubeListening() {
+ val store = container.listeningStore
+ listeningSync = viewModelScope.launch {
+ runCatching {
+ val sections = container.youtubeBackend.listeningHistory() ?: return@runCatching
+ val now = System.currentTimeMillis()
+ val last = store.youtubeReading()
+ val plays = dev.lelonio.square.data.YouTubeListening.plays(
+ sections = sections,
+ previous = last?.first,
+ previousAt = last?.second ?: now,
+ now = now,
+ )
+ store.importRemote(plays, dev.lelonio.square.data.ListeningStore.YOUTUBE_OWNER)
+ store.keepYoutubeReading(sections.flatMap { it.second }.map { it.uri }, now)
+ android.util.Log.i(TAG, "youtube history: ${sections.map { it.first }}, ${plays.size} plays filed")
+ }.onSuccess { lastListeningSync = System.currentTimeMillis() }
+ .onFailure { android.util.Log.w(TAG, "youtube history unavailable: ${describe(it)}") }
+ }
+ }
+
val recent: StateFlow<List<CatalogTrack>> =
combine(container.recentStore.tracks, container.preferences.backend) { tracks, _ ->
// A nameless row is one that was recorded before the session had
diff --git a/app/src/main/java/dev/lelonio/square/ui/SquareApp.kt b/app/src/main/java/dev/lelonio/square/ui/SquareApp.kt
index 26ddc7d..a651d0f 100644
--- a/app/src/main/java/dev/lelonio/square/ui/SquareApp.kt
+++ b/app/src/main/java/dev/lelonio/square/ui/SquareApp.kt
@@ -1794,7 +1794,8 @@ fun SquareApp(
onRetry = { viewModel.retryFailed() },
onLogOut = viewModel::logOut,
onOpenPlaylist = { navController.openPlaylist(viewModel, it) },
- listeningEvents = if (backend == dev.lelonio.square.backend.BackendId.SPOTIFY) listeningEvents else null,
+ listeningEvents = listeningEvents,
+ listeningFromSpotify = backend == dev.lelonio.square.backend.BackendId.SPOTIFY,
playlistOrder = playlistOrder,
pinned = pinnedPlaylists,
canEdit = viewModel.canEditPlaylists,
diff --git a/app/src/main/java/dev/lelonio/square/ui/library/LibraryScreen.kt b/app/src/main/java/dev/lelonio/square/ui/library/LibraryScreen.kt
index fd44bf1..8a6401f 100644
--- a/app/src/main/java/dev/lelonio/square/ui/library/LibraryScreen.kt
+++ b/app/src/main/java/dev/lelonio/square/ui/library/LibraryScreen.kt
@@ -2,6 +2,11 @@ package dev.lelonio.square.ui.library
import androidx.annotation.StringRes
import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.animation.AnimatedContent
+import androidx.compose.animation.togetherWith
+import androidx.compose.animation.fadeIn
+import androidx.compose.animation.fadeOut
+import androidx.compose.animation.core.tween
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
@@ -147,6 +152,8 @@ fun LibraryScreen(
onUseYouTube: () -> Unit = {},
onOpenSettings: () -> Unit = {},
listeningEvents: List<dev.lelonio.square.data.ListeningEvent>? = null,
+ /** Whether those were played from Spotify, rather than YouTube Music. */
+ listeningFromSpotify: Boolean = true,
backdrop: Backdrop,
) {
when (state) {
@@ -277,6 +284,23 @@ fun LibraryScreen(
.distinctBy { it.uri }
}
+ // The month in music takes the library's place while it is open,
+ // and gives it back as it was: the scroll positions and choices
+ // above are held outside this.
+ AnimatedContent(
+ targetState = recapOpen && listeningEvents != null,
+ transitionSpec = { fadeIn(tween(220)) togetherWith fadeOut(tween(160)) },
+ label = "libraryRecap",
+ ) { showRecap ->
+ if (showRecap) {
+ MonthlyListeningPage(
+ events = listeningEvents.orEmpty(),
+ fromSpotify = listeningFromSpotify,
+ backdrop = backdrop,
+ contentPadding = contentPadding,
+ onBack = { recapOpen = false },
+ )
+ } else {
Box(Modifier.fillMaxSize()) {
Column(Modifier.fillMaxSize()) {
Header(
@@ -421,9 +445,6 @@ fun LibraryScreen(
}
}
- if (recapOpen && listeningEvents != null) {
- MonthlyListeningDialog(listeningEvents, backdrop, onDismiss = { recapOpen = false })
- }
// The app's own menu rather than Material's card: see GlassMenu.
// The same one the track sort on a playlist page opens, for the
@@ -458,6 +479,8 @@ fun LibraryScreen(
}
}
}
+ }
+ }
}
}
}
diff --git a/app/src/main/java/dev/lelonio/square/ui/library/MonthlyListeningDialog.kt b/app/src/main/java/dev/lelonio/square/ui/library/MonthlyListeningDialog.kt
deleted file mode 100644
index 03612b6..0000000
--- a/app/src/main/java/dev/lelonio/square/ui/library/MonthlyListeningDialog.kt
+++ /dev/null
@@ -1,111 +0,0 @@
-package dev.lelonio.square.ui.library
-
-import androidx.compose.foundation.layout.*
-import androidx.compose.foundation.rememberScrollState
-import androidx.compose.foundation.verticalScroll
-import androidx.compose.foundation.shape.RoundedCornerShape
-import androidx.compose.ui.window.Dialog
-import androidx.compose.ui.window.DialogProperties
-import androidx.compose.ui.platform.LocalConfiguration
-import androidx.compose.ui.Alignment
-import androidx.compose.material3.Icon
-import dev.lelonio.square.ui.components.menuSkin
-import com.adamglin.PhosphorIcons
-import com.adamglin.phosphoricons.Regular
-import com.adamglin.phosphoricons.regular.X
-import androidx.compose.material3.MaterialTheme
-import androidx.compose.material3.Text
-import androidx.compose.runtime.*
-import androidx.compose.ui.Modifier
-import androidx.compose.ui.res.stringResource
-import androidx.compose.ui.text.font.FontWeight
-import androidx.compose.ui.text.style.TextOverflow
-import androidx.compose.ui.unit.dp
-import dev.lelonio.square.R
-import dev.lelonio.square.data.ListeningEvent
-import dev.lelonio.square.data.ListeningHistory
-import dev.lelonio.square.ui.components.Artwork
-import dev.lelonio.square.ui.glass.LiquidButton
-import dev.lelonio.square.ui.glass.backdrop.Backdrop
-import dev.lelonio.square.ui.theme.Ink
-import dev.lelonio.square.ui.theme.InkDim
-import java.time.Instant
-import java.time.YearMonth
-import java.time.ZoneId
-import java.time.format.DateTimeFormatter
-import java.util.Locale
-
-@Composable
-fun MonthlyListeningDialog(events: List<ListeningEvent>, backdrop: Backdrop, onDismiss: () -> Unit) {
- val current = YearMonth.now()
- var month by remember { mutableStateOf(current) }
-
- val summary = remember(events, month) { ListeningHistory.summarize(events, month) }
- val first = remember(events) {
- events.minOfOrNull { it.startedAt }?.let {
- YearMonth.from(Instant.ofEpochMilli(it).atZone(ZoneId.systemDefault()))
- } ?: current
- }
- val maxHeight = LocalConfiguration.current.screenHeightDp.dp * 0.82f
- Dialog(onDismissRequest = onDismiss, properties = DialogProperties(usePlatformDefaultWidth = false)) {
- Column(Modifier.padding(20.dp).fillMaxWidth().heightIn(max = maxHeight)
- .menuSkin(RoundedCornerShape(28.dp)).verticalScroll(rememberScrollState()).padding(22.dp),
- verticalArrangement = Arrangement.spacedBy(18.dp)) {
- Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {
- Text(stringResource(R.string.recap_title), modifier = Modifier.weight(1f),
- style = MaterialTheme.typography.titleLarge, color = Ink)
- LiquidButton(onClick = onDismiss, backdrop = backdrop, flat = true,
- modifier = Modifier.size(44.dp), contentHeight = 44.dp, contentPadding = 0.dp) {
- Icon(PhosphorIcons.Regular.X, contentDescription = stringResource(R.string.close),
- tint = Ink, modifier = Modifier.size(20.dp))
- }
- }
- Text(month.format(DateTimeFormatter.ofPattern("LLLL yyyy", Locale.getDefault())),
- style = MaterialTheme.typography.titleMedium, color = InkDim)
- Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically,
- horizontalArrangement = Arrangement.spacedBy(18.dp)) {
- summary.tracks.firstOrNull()?.first?.let { track ->
- Artwork(track.artworkUrl, track.name, Modifier.size(72.dp), corner = 14.dp)
- }
- Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(4.dp)) {
- Text(stringResource(R.string.recap_plays, summary.plays),
- style = MaterialTheme.typography.headlineMedium, fontWeight = FontWeight.Bold, color = Ink)
- if (summary.minutes > 0) Text(stringResource(R.string.recap_minutes, summary.minutes),
- style = MaterialTheme.typography.bodyMedium, color = InkDim)
- }
- }
- Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween) {
- LiquidButton(onClick = { if (month > first) month = month.minusMonths(1) }, backdrop = backdrop,
- isInteractive = month > first, flat = true, contentHeight = 32.dp) {
- Text(stringResource(R.string.recap_previous), color = if (month > first) Ink else InkDim)
- }
- if (month < current) LiquidButton(onClick = { month = month.plusMonths(1) }, backdrop = backdrop,
- flat = true, contentHeight = 32.dp) {
- Text(stringResource(R.string.recap_next), color = Ink)
- }
- }
- if (summary.tracks.isNotEmpty()) {
- Text(stringResource(R.string.recap_tracks), style = MaterialTheme.typography.titleMedium, color = Ink)
- summary.tracks.take(5).forEach { (track, count) ->
- Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(12.dp)) {
- Artwork(track.artworkUrl, track.name, Modifier.size(44.dp))
- Column(Modifier.weight(1f)) {
- Text(track.name, maxLines = 1, overflow = TextOverflow.Ellipsis, color = Ink)
- Text(track.artist, maxLines = 1, overflow = TextOverflow.Ellipsis,
- style = MaterialTheme.typography.bodySmall, color = InkDim)
- }
- Text(count.toString(), color = InkDim)
- }
- }
- Text(stringResource(R.string.recap_artists), style = MaterialTheme.typography.titleMedium, color = Ink)
- summary.artists.take(5).forEach { (artist, count) ->
- Row(Modifier.fillMaxWidth()) {
- Text(artist, modifier = Modifier.weight(1f), color = Ink)
- Text(count.toString(), color = InkDim)
- }
- }
- }
- Text(stringResource(R.string.recap_partial), style = MaterialTheme.typography.bodySmall, color = InkDim)
- }
- }
-}
diff --git a/app/src/main/java/dev/lelonio/square/ui/library/MonthlyListeningPage.kt b/app/src/main/java/dev/lelonio/square/ui/library/MonthlyListeningPage.kt
new file mode 100644
index 0000000..be81983
--- /dev/null
+++ b/app/src/main/java/dev/lelonio/square/ui/library/MonthlyListeningPage.kt
@@ -0,0 +1,409 @@
+package dev.lelonio.square.ui.library
+
+import androidx.activity.compose.BackHandler
+import androidx.compose.animation.AnimatedContent
+import androidx.compose.animation.core.tween
+import androidx.compose.animation.fadeIn
+import androidx.compose.animation.fadeOut
+import androidx.compose.animation.togetherWith
+import androidx.compose.foundation.background
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Box
+import androidx.compose.foundation.layout.PaddingValues
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.aspectRatio
+import androidx.compose.foundation.layout.fillMaxHeight
+import androidx.compose.foundation.layout.fillMaxSize
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.layout.size
+import androidx.compose.foundation.layout.width
+import androidx.compose.foundation.rememberScrollState
+import androidx.compose.foundation.verticalScroll
+import androidx.compose.material3.Icon
+import androidx.compose.material3.MaterialTheme
+import androidx.compose.material3.Text
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.remember
+import androidx.compose.runtime.setValue
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.draw.clip
+import androidx.compose.ui.graphics.Brush
+import androidx.compose.ui.graphics.Color
+import androidx.compose.ui.res.stringResource
+import androidx.compose.ui.text.font.FontWeight
+import androidx.compose.ui.text.style.TextAlign
+import androidx.compose.ui.text.style.TextOverflow
+import androidx.compose.ui.unit.dp
+import androidx.compose.ui.unit.sp
+import com.adamglin.PhosphorIcons
+import com.adamglin.phosphoricons.Regular
+import com.adamglin.phosphoricons.regular.ArrowLeft
+import com.adamglin.phosphoricons.regular.CaretLeft
+import com.adamglin.phosphoricons.regular.CaretRight
+import dev.lelonio.square.R
+import dev.lelonio.square.data.CatalogTrack
+import dev.lelonio.square.data.ListeningEvent
+import dev.lelonio.square.data.ListeningHistory
+import dev.lelonio.square.data.MonthlyListening
+import dev.lelonio.square.ui.components.Artwork
+import dev.lelonio.square.ui.glass.LiquidButton
+import dev.lelonio.square.ui.glass.backdrop.Backdrop
+import dev.lelonio.square.ui.glass.pressable
+import dev.lelonio.square.ui.glass.shapes.ContinuousRoundedRectangle
+import dev.lelonio.square.ui.theme.Ink
+import dev.lelonio.square.ui.theme.InkDim
+import java.time.Instant
+import java.time.YearMonth
+import java.time.ZoneId
+import java.time.format.DateTimeFormatter
+import java.util.Locale
+
+/**
+ * The month in music, as a page of the library.
+ *
+ * It takes the library's place rather than sitting over it: it was a Material
+ * dialog, then a panel over the dimmed page, and either way a box from
+ * somewhere else on top of the library. Here it has the library's own heading,
+ * with the same way back the settings pages have, and it leads with the
+ * month's song as a picture rather than a row, the way a recap is read: the
+ * song first, then how much, then the rest of the ranking.
+ */
+@Composable
+fun MonthlyListeningPage(
+ events: List<ListeningEvent>,
+ /** Which note goes at the bottom: what Square can and cannot count. */
+ fromSpotify: Boolean,
+ backdrop: Backdrop,
+ contentPadding: PaddingValues,
+ onBack: () -> Unit,
+) {
+ BackHandler(onBack = onBack)
+ val current = YearMonth.now()
+ var month by remember { mutableStateOf(current) }
+ val first = remember(events) {
+ events.minOfOrNull { it.spotifyAt ?: it.startedAt }?.let {
+ YearMonth.from(Instant.ofEpochMilli(it).atZone(ZoneId.systemDefault()))
+ }?.coerceAtMost(current) ?: current
+ }
+
+ Column(
+ Modifier
+ .fillMaxSize()
+ .verticalScroll(rememberScrollState())
+ .padding(top = contentPadding.calculateTopPadding(), bottom = contentPadding.calculateBottomPadding()),
+ ) {
+ Row(
+ Modifier
+ .fillMaxWidth()
+ .padding(start = 16.dp, end = 24.dp, top = 8.dp, bottom = 4.dp),
+ verticalAlignment = Alignment.CenterVertically,
+ ) {
+ LiquidButton(onClick = onBack, backdrop = backdrop) {
+ Icon(PhosphorIcons.Regular.ArrowLeft, contentDescription = stringResource(R.string.back))
+ }
+ Text(
+ stringResource(R.string.recap_title),
+ style = MaterialTheme.typography.headlineMedium,
+ fontWeight = FontWeight.Bold,
+ maxLines = 2,
+ modifier = Modifier.padding(start = 14.dp),
+ )
+ }
+ Header(
+ month = month,
+ canGoBack = month > first,
+ canGoForward = month < current,
+ onBack = { month = month.minusMonths(1) },
+ onForward = { month = month.plusMonths(1) },
+ )
+ AnimatedContent(
+ targetState = month,
+ transitionSpec = { fadeIn(tween(180)) togetherWith fadeOut(tween(120)) },
+ label = "recapMonth",
+ ) { shown ->
+ val summary = remember(events, shown) { ListeningHistory.summarize(events, shown) }
+ Column(
+ Modifier.padding(start = 20.dp, end = 20.dp, bottom = 24.dp),
+ verticalArrangement = Arrangement.spacedBy(18.dp),
+ ) {
+ Body(summary)
+ Text(
+ stringResource(if (fromSpotify) R.string.recap_partial else R.string.recap_partial_youtube),
+ style = MaterialTheme.typography.bodySmall,
+ color = InkDim,
+ )
+ }
+ }
+ }
+}
+
+@Composable
+private fun Header(
+ month: YearMonth,
+ canGoBack: Boolean,
+ canGoForward: Boolean,
+ onBack: () -> Unit,
+ onForward: () -> Unit,
+) {
+ Column(
+ Modifier
+ .fillMaxWidth()
+ .padding(start = 14.dp, end = 14.dp, top = 12.dp, bottom = 14.dp),
+ horizontalAlignment = Alignment.CenterHorizontally,
+ ) {
+ Row(
+ Modifier.fillMaxWidth().padding(top = 4.dp),
+ verticalAlignment = Alignment.CenterVertically,
+ ) {
+ Step(PhosphorIcons.Regular.CaretLeft, stringResource(R.string.recap_previous), canGoBack, onBack)
+ Text(
+ month.format(DateTimeFormatter.ofPattern("LLLL yyyy", Locale.getDefault()))
+ .replaceFirstChar { it.titlecase(Locale.getDefault()) },
+ style = MaterialTheme.typography.headlineSmall,
+ fontWeight = FontWeight.Bold,
+ color = Ink,
+ textAlign = TextAlign.Center,
+ maxLines = 1,
+ modifier = Modifier.weight(1f),
+ )
+ Step(PhosphorIcons.Regular.CaretRight, stringResource(R.string.recap_next), canGoForward, onForward)
+ }
+ }
+}
+
+@Composable
+private fun Step(
+ icon: androidx.compose.ui.graphics.vector.ImageVector,
+ label: String,
+ enabled: Boolean,
+ onClick: () -> Unit,
+) {
+ Box(
+ Modifier
+ .size(40.dp)
+ .clip(ContinuousRoundedRectangle(20.dp))
+ .background(if (enabled) FILM else Color.Transparent)
+ .pressable(onClick, pressedScale = 0.9f, enabled = enabled),
+ contentAlignment = Alignment.Center,
+ ) {
+ Icon(
+ icon,
+ contentDescription = label,
+ tint = if (enabled) Ink else InkDim.copy(alpha = 0.35f),
+ modifier = Modifier.size(18.dp),
+ )
+ }
+}
+
+@Composable
+private fun Body(summary: MonthlyListening) {
+ val top = summary.tracks.firstOrNull()?.first
+ if (top != null) SongOfTheMonth(top)
+
+ Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(12.dp)) {
+ Stat(summary.plays.toString(), stringResource(R.string.recap_stat_plays), Modifier.weight(1f))
+ Stat(summary.minutes.toString(), stringResource(R.string.recap_stat_minutes), Modifier.weight(1f))
+ }
+
+ if (summary.plays == 0) {
+ Text(
+ stringResource(R.string.recap_empty),
+ style = MaterialTheme.typography.bodyLarge,
+ color = InkDim,
+ textAlign = TextAlign.Center,
+ modifier = Modifier.fillMaxWidth().padding(vertical = 12.dp),
+ )
+ return
+ }
+
+ Section(stringResource(R.string.recap_tracks))
+ Column(verticalArrangement = Arrangement.spacedBy(10.dp)) {
+ summary.tracks.take(RANKED).forEachIndexed { at, (track, count) -> TrackRank(at + 1, track, count) }
+ }
+
+ if (summary.artists.isNotEmpty()) {
+ Section(stringResource(R.string.recap_artists))
+ val most = summary.artists.first().second.coerceAtLeast(1)
+ Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
+ summary.artists.take(RANKED).forEachIndexed { at, (artist, count) ->
+ ArtistRank(at + 1, artist, count, count.toFloat() / most)
+ }
+ }
+ }
+}
+
+/** The month's most played song, as a picture with its name written on it. */
+@Composable
+private fun SongOfTheMonth(track: CatalogTrack) {
+ val shape = ContinuousRoundedRectangle(26.dp)
+ Box(
+ Modifier
+ .fillMaxWidth()
+ .aspectRatio(1.25f)
+ .clip(shape),
+ ) {
+ Artwork(track.artworkUrl, track.name, Modifier.fillMaxSize(), corner = 0.dp)
+ Box(
+ Modifier
+ .fillMaxSize()
+ .background(Brush.verticalGradient(0.45f to Color.Transparent, 1f to Color.Black.copy(alpha = 0.78f))),
+ )
+ Column(
+ Modifier
+ .align(Alignment.BottomStart)
+ .padding(18.dp),
+ ) {
+ Text(
+ stringResource(R.string.recap_song_of_month).uppercase(),
+ style = MaterialTheme.typography.labelSmall,
+ fontSize = 11.sp,
+ fontWeight = FontWeight.Bold,
+ color = Color.White.copy(alpha = 0.75f),
+ )
+ Text(
+ track.name,
+ style = MaterialTheme.typography.headlineSmall,
+ fontWeight = FontWeight.Bold,
+ color = Color.White,
+ maxLines = 2,
+ overflow = TextOverflow.Ellipsis,
+ modifier = Modifier.padding(top = 2.dp),
+ )
+ Text(
+ track.artist,
+ style = MaterialTheme.typography.titleMedium,
+ color = Color.White.copy(alpha = 0.8f),
+ maxLines = 1,
+ overflow = TextOverflow.Ellipsis,
+ )
+ }
+ }
+}
+
+@Composable
+private fun Stat(value: String, label: String, modifier: Modifier = Modifier) {
+ Column(
+ modifier
+ .clip(ContinuousRoundedRectangle(22.dp))
+ .background(FILM)
+ .padding(horizontal = 16.dp, vertical = 14.dp),
+ ) {
+ Text(
+ value,
+ style = MaterialTheme.typography.headlineMedium,
+ fontWeight = FontWeight.Bold,
+ color = Ink,
+ maxLines = 1,
+ )
+ Text(
+ label,
+ style = MaterialTheme.typography.bodyMedium,
+ color = InkDim,
+ maxLines = 1,
+ overflow = TextOverflow.Ellipsis,
+ )
+ }
+}
+
+@Composable
+private fun Section(title: String) {
+ Text(
+ title,
+ style = MaterialTheme.typography.titleMedium,
+ fontWeight = FontWeight.SemiBold,
+ color = Ink,
+ modifier = Modifier.padding(top = 4.dp),
+ )
+}
+
+@Composable
+private fun Rank(place: Int) {
+ Text(
+ place.toString(),
+ style = MaterialTheme.typography.titleMedium,
+ fontWeight = FontWeight.Bold,
+ color = if (place == 1) Ink else InkDim,
+ textAlign = TextAlign.Center,
+ modifier = Modifier.width(26.dp),
+ )
+}
+
+@Composable
+private fun TrackRank(place: Int, track: CatalogTrack, plays: Int) {
+ Row(
+ Modifier.fillMaxWidth(),
+ horizontalArrangement = Arrangement.spacedBy(12.dp),
+ verticalAlignment = Alignment.CenterVertically,
+ ) {
+ Rank(place)
+ Artwork(track.artworkUrl, track.name, Modifier.size(46.dp), corner = 10.dp)
+ Column(Modifier.weight(1f)) {
+ Text(
+ track.name,
+ style = MaterialTheme.typography.bodyLarge,
+ color = Ink,
+ maxLines = 1,
+ overflow = TextOverflow.Ellipsis,
+ )
+ Text(
+ track.artist,
+ style = MaterialTheme.typography.bodySmall,
+ color = InkDim,
+ maxLines = 1,
+ overflow = TextOverflow.Ellipsis,
+ )
+ }
+ Text(plays.toString(), style = MaterialTheme.typography.bodyMedium, color = InkDim)
+ }
+}
+
+/** An artist, with a bar as long as their share of the month's favourite. */
+@Composable
+private fun ArtistRank(place: Int, artist: String, plays: Int, share: Float) {
+ Row(
+ Modifier.fillMaxWidth(),
+ horizontalArrangement = Arrangement.spacedBy(12.dp),
+ verticalAlignment = Alignment.CenterVertically,
+ ) {
+ Rank(place)
+ Box(
+ Modifier
+ .weight(1f)
+ .clip(ContinuousRoundedRectangle(14.dp))
+ .background(FILM),
+ ) {
+ Box(Modifier.matchParentSize()) {
+ Box(
+ Modifier
+ .fillMaxWidth(share.coerceIn(0.08f, 1f))
+ .fillMaxHeight()
+ .background(MaterialTheme.colorScheme.primary.copy(alpha = 0.32f)),
+ )
+ }
+ Row(
+ Modifier.fillMaxWidth().padding(horizontal = 14.dp, vertical = 10.dp),
+ verticalAlignment = Alignment.CenterVertically,
+ ) {
+ Text(
+ artist,
+ style = MaterialTheme.typography.bodyLarge,
+ color = Ink,
+ maxLines = 1,
+ overflow = TextOverflow.Ellipsis,
+ modifier = Modifier.weight(1f),
+ )
+ Text(plays.toString(), style = MaterialTheme.typography.bodyMedium, color = InkDim)
+ }
+ }
+ }
+}
+
+private const val RANKED = 5
+
+/** The ground of the tiles: a shade of the ink, so it reads in both themes. */
+private val FILM: Color @Composable get() = Ink.copy(alpha = 0.08f)
diff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xml
index e610e8b..deb50ca 100644
--- a/app/src/main/res/values-de/strings.xml
+++ b/app/src/main/res/values-de/strings.xml
@@ -534,4 +534,9 @@
<item quantity="other">%1$d ausgewählt</item>
</plurals>
<string name="new_release_followed_tag">Von deinen Künstlern</string>
+ <string name="recap_song_of_month">Song des Monats</string>
+ <string name="recap_stat_plays">Wiedergaben</string>
+ <string name="recap_stat_minutes">Minuten in Square</string>
+ <string name="recap_empty">Diesen Monat noch nichts gehört.</string>
+ <string name="recap_partial_youtube">Enthält, was du in Square hörst, und, solange Square geöffnet ist, deinen YouTube-Music-Verlauf. Wiedergaben aus anderen Apps und auf anderen Geräten sind ungefähr: YouTube nennt nur den Tag, nicht die Uhrzeit.</string>
</resources>
diff --git a/app/src/main/res/values-es/strings.xml b/app/src/main/res/values-es/strings.xml
index 24bdcab..4e4d5bd 100644
--- a/app/src/main/res/values-es/strings.xml
+++ b/app/src/main/res/values-es/strings.xml
@@ -540,4 +540,9 @@
<item quantity="other">%1$d seleccionadas</item>
</plurals>
<string name="new_release_followed_tag">De tus artistas</string>
+ <string name="recap_song_of_month">Canción del mes</string>
+ <string name="recap_stat_plays">reproducciones</string>
+ <string name="recap_stat_minutes">minutos en Square</string>
+ <string name="recap_empty">Aún no hay escuchas este mes.</string>
+ <string name="recap_partial_youtube">Incluye lo que escuchas en Square y, mientras Square está abierta, tu historial de YouTube Music. Las escuchas en otras apps y dispositivos son aproximadas: YouTube no da la hora, solo el día.</string>
</resources>
diff --git a/app/src/main/res/values-fr/strings.xml b/app/src/main/res/values-fr/strings.xml
index 45c7329..c8690ea 100644
--- a/app/src/main/res/values-fr/strings.xml
+++ b/app/src/main/res/values-fr/strings.xml
@@ -534,4 +534,9 @@
<item quantity="other">%1$d sélectionnés</item>
</plurals>
<string name="new_release_followed_tag">De tes artistes</string>
+ <string name="recap_song_of_month">Titre du mois</string>
+ <string name="recap_stat_plays">écoutes</string>
+ <string name="recap_stat_minutes">minutes dans Square</string>
+ <string name="recap_empty">Aucune écoute ce mois-ci pour l’instant.</string>
+ <string name="recap_partial_youtube">Comprend ce que tu écoutes dans Square et, tant que Square est ouverte, ton historique YouTube Music. Les écoutes depuis d’autres apps et appareils sont approximatives : YouTube ne donne pas l’heure, seulement le jour.</string>
</resources>
diff --git a/app/src/main/res/values-hi/strings.xml b/app/src/main/res/values-hi/strings.xml
index c626817..48f7979 100644
--- a/app/src/main/res/values-hi/strings.xml
+++ b/app/src/main/res/values-hi/strings.xml
@@ -549,4 +549,9 @@
<item quantity="other">%1$d चुने गए</item>
</plurals>
<string name="new_release_followed_tag">आपके कलाकारों से</string>
+ <string name="recap_song_of_month">महीने का गाना</string>
+ <string name="recap_stat_plays">बार सुना</string>
+ <string name="recap_stat_minutes">Square में मिनट</string>
+ <string name="recap_empty">इस महीने अभी तक कुछ नहीं सुना।</string>
+ <string name="recap_partial_youtube">इसमें Square में सुने गए गाने और, जब तक Square खुला है, आपका YouTube Music इतिहास शामिल है। दूसरे ऐप और डिवाइस पर सुने गए गाने अनुमानित हैं: YouTube समय नहीं, सिर्फ़ दिन बताता है।</string>
</resources>
diff --git a/app/src/main/res/values-it/strings.xml b/app/src/main/res/values-it/strings.xml
index df98d96..dfe3461 100644
--- a/app/src/main/res/values-it/strings.xml
+++ b/app/src/main/res/values-it/strings.xml
@@ -571,4 +571,9 @@
<item quantity="other">%1$d selezionati</item>
</plurals>
<string name="new_release_followed_tag">Dai tuoi artisti</string>
+ <string name="recap_song_of_month">Brano del mese</string>
+ <string name="recap_stat_plays">ascolti</string>
+ <string name="recap_stat_minutes">minuti in Square</string>
+ <string name="recap_empty">Ancora nessun ascolto questo mese.</string>
+ <string name="recap_partial_youtube">Include quello che ascolti in Square e, mentre Square è aperta, la cronologia di YouTube Music. Gli ascolti da altre app e dispositivi sono approssimativi: YouTube non dice l’ora, solo il giorno.</string>
</resources>
diff --git a/app/src/main/res/values-pt/strings.xml b/app/src/main/res/values-pt/strings.xml
index a33fcf2..75d8979 100644
--- a/app/src/main/res/values-pt/strings.xml
+++ b/app/src/main/res/values-pt/strings.xml
@@ -534,4 +534,9 @@
<item quantity="other">%1$d selecionadas</item>
</plurals>
<string name="new_release_followed_tag">Dos seus artistas</string>
+ <string name="recap_song_of_month">Música do mês</string>
+ <string name="recap_stat_plays">reproduções</string>
+ <string name="recap_stat_minutes">minutos no Square</string>
+ <string name="recap_empty">Nenhuma reprodução neste mês ainda.</string>
+ <string name="recap_partial_youtube">Inclui o que você ouve no Square e, enquanto o Square está aberto, seu histórico do YouTube Music. Reproduções em outros apps e dispositivos são aproximadas: o YouTube não informa a hora, só o dia.</string>
</resources>
diff --git a/app/src/main/res/values-ru/strings.xml b/app/src/main/res/values-ru/strings.xml
index 6b341c5..7865a64 100644
--- a/app/src/main/res/values-ru/strings.xml
+++ b/app/src/main/res/values-ru/strings.xml
@@ -563,4 +563,9 @@
<item quantity="other">Выбрано %1$d</item>
</plurals>
<string name="new_release_followed_tag">От ваших исполнителей</string>
+ <string name="recap_song_of_month">Трек месяца</string>
+ <string name="recap_stat_plays">прослушиваний</string>
+ <string name="recap_stat_minutes">минут в Square</string>
+ <string name="recap_empty">В этом месяце пока ничего не прослушано.</string>
+ <string name="recap_partial_youtube">Учитывается то, что вы слушаете в Square, и, пока Square открыт, история YouTube Music. Прослушивания в других приложениях и на других устройствах приблизительны: YouTube сообщает только день, а не время.</string>
</resources>
diff --git a/app/src/main/res/values-tr/strings.xml b/app/src/main/res/values-tr/strings.xml
index 96cf93f..05d227e 100644
--- a/app/src/main/res/values-tr/strings.xml
+++ b/app/src/main/res/values-tr/strings.xml
@@ -547,4 +547,9 @@
<item quantity="other">%1$d seçildi</item>
</plurals>
<string name="new_release_followed_tag">Sanatçılarından</string>
+ <string name="recap_song_of_month">Ayın şarkısı</string>
+ <string name="recap_stat_plays">dinleme</string>
+ <string name="recap_stat_minutes">Square’de dakika</string>
+ <string name="recap_empty">Bu ay henüz dinleme yok.</string>
+ <string name="recap_partial_youtube">Square’de dinlediklerini ve Square açıkken YouTube Music geçmişini içerir. Diğer uygulama ve cihazlardaki dinlemeler yaklaşıktır: YouTube saati değil, yalnızca günü verir.</string>
</resources>
diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml
index e99dabe..1507e2a 100644
--- a/app/src/main/res/values/strings.xml
+++ b/app/src/main/res/values/strings.xml
@@ -598,4 +598,9 @@
<item quantity="other">%1$d selected</item>
</plurals>
<string name="new_release_followed_tag">From your artists</string>
+ <string name="recap_song_of_month">Song of the month</string>
+ <string name="recap_stat_plays">plays</string>
+ <string name="recap_stat_minutes">minutes in Square</string>
+ <string name="recap_empty">No listens this month yet.</string>
+ <string name="recap_partial_youtube">Includes what you play in Square and, while Square is open, your YouTube Music history. Plays from other apps and devices are approximate: YouTube does not say when, only the day.</string>
</resources>
diff --git a/app/src/test/java/dev/lelonio/square/data/YouTubeListeningTest.kt b/app/src/test/java/dev/lelonio/square/data/YouTubeListeningTest.kt
new file mode 100644
index 0000000..57f9ee6
--- /dev/null
+++ b/app/src/test/java/dev/lelonio/square/data/YouTubeListeningTest.kt
@@ -0,0 +1,63 @@
+package dev.lelonio.square.data
+
+import java.time.LocalDate
+import java.time.ZoneOffset
+import org.junit.Assert.*
+import org.junit.Test
+
+class YouTubeListeningTest {
+ private val today = LocalDate.of(2026, 10, 9)
+ private fun track(id: String) = CatalogTrack(uri = "ytmusic:track:$id", name = id, artist = "artist", durationMs = 1000)
+
+ @Test fun headingsAreReadIntoDays() {
+ assertEquals(today, YouTubeListening.sectionDay("Today", today))
+ assertEquals(today.minusDays(1), YouTubeListening.sectionDay("Yesterday", today))
+ assertEquals(today.minusWeeks(1), YouTubeListening.sectionDay("Last week", today))
+ assertEquals(LocalDate.of(2026, 8, 15), YouTubeListening.sectionDay("August 2026", today))
+ assertEquals(LocalDate.of(2025, 12, 15), YouTubeListening.sectionDay("December", today))
+ assertEquals(LocalDate.of(2026, 10, 1), YouTubeListening.sectionDay("October", today))
+ assertNull(YouTubeListening.sectionDay("Oggi", today))
+ }
+
+ @Test fun replaysAreTheSongsThatCameBackToTheTop() {
+ val before = listOf("a", "b", "c", "d")
+ assertEquals(emptyList<String>(), YouTubeListening.replays(before, before))
+ assertEquals(listOf("x", "y"), YouTubeListening.replays(before, listOf("x", "y", "a", "b", "c", "d")))
+ assertEquals(listOf("c", "x"), YouTubeListening.replays(before, listOf("c", "x", "a", "b", "d")))
+ // The top song played again, after something new.
+ assertEquals(listOf("a", "x"), YouTubeListening.replays(before, listOf("a", "x", "b", "c", "d")))
+ // The page is a window: the oldest fall off its end.
+ assertEquals(listOf("x"), YouTubeListening.replays(before, listOf("x", "a", "b", "c")))
+ assertNull(YouTubeListening.replays(before, listOf("p", "q")))
+ }
+
+ @Test fun firstReadingFilesEachSongOnItsHeadingsDay() {
+ val now = today.atTime(18, 0).toInstant(ZoneOffset.UTC).toEpochMilli()
+ val plays = YouTubeListening.plays(
+ sections = listOf("Today" to listOf(track("a")), "Unknown" to listOf(track("b")), "Last week" to listOf(track("c"))),
+ previous = null, previousAt = now, now = now, zone = ZoneOffset.UTC,
+ )
+ assertEquals(listOf("a", "c"), plays.map { it.track.name })
+ assertEquals(today.atTime(12, 0).toInstant(ZoneOffset.UTC).toEpochMilli(), plays[0].at)
+ }
+
+ @Test fun laterReadingsFileOnlyReplaysWithinTheTimeSince() {
+ val plays = YouTubeListening.plays(
+ sections = listOf("Today" to listOf(track("x"), track("a"), track("b"))),
+ previous = listOf("ytmusic:track:a", "ytmusic:track:b"), previousAt = 1_000, now = 5_000,
+ )
+ assertEquals(listOf("x"), plays.map { it.track.name })
+ assertEquals(5_000L, plays.single().at)
+ assertEquals(1_000L..5_000L, plays.single().window)
+ }
+
+ @Test fun squaresOwnPlayIsNotCountedTwice() {
+ val song = track("a")
+ val local = ListeningEvent("local:2000:${song.uri}", song, 2_000, qualified = true)
+ val merged = ListeningHistory.mergeRemote(listOf(local), song, 5_000, 1_000L..5_000L)
+ assertEquals(1, merged.size)
+ assertEquals(2_000L, merged.single().spotifyAt)
+ val again = ListeningHistory.mergeRemote(merged, song, 6_000, 5_000L..6_000L)
+ assertEquals(2, again.size)
+ }
+}