Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions app/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -446,6 +446,7 @@ dependencies {
// scrobbler (MediaScrobbleListenerService) already holds.
implementation("androidx.glance:glance-appwidget:1.1.1")
implementation("androidx.glance:glance-material3:1.1.1")
implementation("androidx.work:work-runtime-ktx:2.7.1")

// Required even in a Compose-only app: Theme.Material3.DayNight.NoActionBar
// (used as the AndroidManifest/splash theme parent in themes.xml) is an XML
Expand Down
5 changes: 2 additions & 3 deletions app/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
Expand Up @@ -45,9 +45,8 @@
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"
android:maxSdkVersion="32" />
<uses-permission android:name="android.permission.READ_MEDIA_AUDIO" />
<!-- WorkManager (pulled in by Glance widgets) adds a boot receiver. LastWave
schedules no persistent work and must never start at boot, so drop it:
auto-start-at-boot is a key signal antivirus "dropper" heuristics use. -->
<!-- Keep LastWave from starting at boot. WorkManager reschedules Smart
Downloads when LastWave is next opened. -->
<uses-permission
android:name="android.permission.RECEIVE_BOOT_COMPLETED"
tools:node="remove" />
Expand Down
11 changes: 11 additions & 0 deletions app/src/main/java/com/lastwave/app/LastWaveApplication.kt
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ class LastWaveApplication : Application(), ImageLoaderFactory {
@Inject lateinit var ytMusicSyncManager: dagger.Lazy<com.lastwave.app.data.ytmusic.YtMusicSyncManager>
@Inject lateinit var ytMusicHistorySyncManager: dagger.Lazy<com.lastwave.app.data.ytmusic.YtMusicHistorySyncManager>
@Inject lateinit var likedSongsManager: dagger.Lazy<com.lastwave.app.data.playlist.LikedSongsManager>
@Inject lateinit var smartDownloadsSync: dagger.Lazy<com.lastwave.app.data.download.smart.SmartDownloadsSync>
@Inject lateinit var trackDownloadManager: dagger.Lazy<com.lastwave.app.data.download.TrackDownloadManager>
@Inject lateinit var discordPresenceManager: dagger.Lazy<com.lastwave.app.presence.DiscordPresenceManager>
@Inject lateinit var appLocaleManager: dagger.Lazy<com.lastwave.app.util.AppLocaleManager>
Expand Down Expand Up @@ -133,6 +134,16 @@ class LastWaveApplication : Application(), ImageLoaderFactory {
runCatching { ytMusicHistorySyncManager.get().start() }
.onFailure { com.lastwave.app.diagnostics.AppLog.e("LastWaveStartup", "YT history sync startup disabled", it) }
}
applicationScope.launch {
delay(OPTIONAL_STARTUP_DELAY_MS)
try {
smartDownloadsSync.get().observeSettings()
} catch (cancellation: CancellationException) {
throw cancellation
} catch (error: Exception) {
com.lastwave.app.diagnostics.AppLog.e("LastWaveStartup", "Smart downloads scheduler unavailable", error)
}
}
// Reconcile public download directory & MediaStore with local database
// asynchronously on startup so offline playback works immediately.
applicationScope.launch(Dispatchers.IO) {
Expand Down
151 changes: 108 additions & 43 deletions app/src/main/java/com/lastwave/app/data/download/TrackDownloadManager.kt

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
Expand Up @@ -197,7 +197,9 @@ internal suspend fun TrackDownloadManager.finishConsentedDeleteImpl(track: Downl

/** DRM module downloads keep a descriptor sidecar; drop it with the audio. */
internal fun TrackDownloadManager.forgetOfflineSidecar(track: DownloadedTrackEntity) {
runCatching { moduleManager.deleteOfflineSidecar(track.title, track.artist) }
if (track.smartDownloadVideoId == null) {
runCatching { moduleManager.deleteOfflineSidecar(track.title, track.artist) }
}
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ import kotlin.coroutines.resumeWithException


internal fun TrackDownloadManager.showDownloadNotification(
notificationId: Int,
notificationId: Int?,
downloadKey: String,
title: String,
artist: String,
Expand All @@ -108,6 +108,7 @@ internal fun TrackDownloadManager.showDownloadNotification(
badgeText: String,
isWaitingForConnection: Boolean = false,
) {
if (notificationId == null) return
val cancelIntent = Intent(context, DownloadCancelReceiver::class.java).apply {
action = ACTION_CANCEL_DOWNLOAD
putExtra(EXTRA_DOWNLOAD_KEY, downloadKey)
Expand Down Expand Up @@ -146,11 +147,12 @@ internal fun TrackDownloadManager.showDownloadNotification(
}

internal fun TrackDownloadManager.showCompletedNotification(
notificationId: Int,
notificationId: Int?,
title: String,
artist: String,
badgeText: String,
) {
if (notificationId == null) return
val notification = NotificationCompat.Builder(context, CHANNEL_ID)
.setSmallIcon(android.R.drawable.stat_sys_download_done)
.setContentTitle("Download Complete")
Expand All @@ -164,12 +166,13 @@ internal fun TrackDownloadManager.showCompletedNotification(
}

internal fun TrackDownloadManager.showErrorNotification(
notificationId: Int,
notificationId: Int?,
downloadKey: String,
title: String,
artist: String,
error: String,
) {
if (notificationId == null) return
val notification = NotificationCompat.Builder(context, CHANNEL_ID)
.setSmallIcon(android.R.drawable.stat_notify_error)
.setContentTitle("Download Failed")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -550,7 +550,7 @@ internal data class DashFetchResult(

internal suspend fun TrackDownloadManager.downloadDashSegmentsToTempFile(
downloadKey: String,
notificationId: Int,
notificationId: Int?,
title: String,
artist: String,
formatBadge: String,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package com.lastwave.app.data.download.smart

import com.lastwave.app.data.music.HomeShelfItem
import com.lastwave.app.data.music.InnerTubeMusicApi

// YouTube's offline/auto_offline answers WEB_REMIX with timing only, even with Smart
// downloads on in YouTube Music, and app clients reject cookie auth. The personal mixes
// that Smart downloads saves (Liked Music, Supermix, Replay/Discover mixes) are on Home.
internal suspend fun InnerTubeMusicApi.fetchPersonalMixIds(): List<String> {
val ids = linkedSetOf<String>()
var page = fetchHomePage()
repeat(HOME_PAGE_LIMIT) {
page.shelves.asSequence().flatMap { it.items }.filterIsInstance<HomeShelfItem.Playlist>()
.map { it.playlist.id.removePrefix("VL") }
.filterTo(ids) { it == "LM" || it.startsWith("RDTMAK5uy_") }
page = fetchHomeContinuation(page.continuationToken ?: return ids.toList())
}
return ids.toList()
}

private const val HOME_PAGE_LIMIT = 6

/** Round-robin across groups so one large playlist cannot take the whole song limit. */
internal fun <T> Map<String, List<T>>.interleaved(): List<T> {
val groups = values.map { it.iterator() }
return buildList {
while (groups.any { it.hasNext() }) groups.forEach { if (it.hasNext()) add(it.next()) }
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
package com.lastwave.app.data.download.smart

import androidx.datastore.core.DataStore
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.core.booleanPreferencesKey
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.intPreferencesKey
import androidx.datastore.preferences.core.stringPreferencesKey
import com.lastwave.app.data.local.readSafely
import com.lastwave.app.data.music.YouTubeMusicTrack
import com.lastwave.app.data.local.recoverPreferences
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.map
import kotlinx.serialization.Serializable
import kotlinx.serialization.SerializationException
import kotlinx.serialization.json.Json
import javax.inject.Inject
import javax.inject.Singleton

data class SmartDownloadsSettings(
val enabled: Boolean = false,
val songLimit: Int = DEFAULT_SONG_LIMIT,
val wifiOnly: Boolean = true,
val storageLimitGiB: Int = DEFAULT_STORAGE_LIMIT_GIB,
) {
val storageLimitBytes: Long get() = storageLimitGiB * 1024L * 1024 * 1024

companion object {
const val MIN_SONG_LIMIT = 10
const val MAX_SONG_LIMIT = 500
const val DEFAULT_SONG_LIMIT = 250
const val MIN_STORAGE_LIMIT_GIB = 1
const val MAX_STORAGE_LIMIT_GIB = 64
const val DEFAULT_STORAGE_LIMIT_GIB = 2
}
}

@Serializable
internal data class SmartDownloadsPlan(
val account: String,
val songLimit: Int,
val checkInAt: Long,
val runUntil: Long,
val playlists: Map<String, List<String>>,
// Full tracks, so a download needs no extra /player lookup for its title and artist.
val pending: List<YouTubeMusicTrack>,
val storageLimitGiB: Int = SmartDownloadsSettings.DEFAULT_STORAGE_LIMIT_GIB,
val obsoleteVideoIds: Set<String> = emptySet(),
)

@Singleton
class SmartDownloadsPreferences @Inject constructor(
private val dataStore: DataStore<Preferences>,
) {
private val values = dataStore.data.recoverPreferences("SmartDownloads")
val settings = values.map { it.smartSettings() }.distinctUntilChanged()

private fun Preferences.smartSettings() = SmartDownloadsSettings(
enabled = readSafely(enabledKey) ?: false,
songLimit = (readSafely(limitKey) ?: SmartDownloadsSettings.DEFAULT_SONG_LIMIT)
.coerceIn(SmartDownloadsSettings.MIN_SONG_LIMIT, SmartDownloadsSettings.MAX_SONG_LIMIT),
wifiOnly = readSafely(wifiKey) ?: true,
storageLimitGiB = (readSafely(storageLimitKey) ?: SmartDownloadsSettings.DEFAULT_STORAGE_LIMIT_GIB)
.coerceIn(SmartDownloadsSettings.MIN_STORAGE_LIMIT_GIB, SmartDownloadsSettings.MAX_STORAGE_LIMIT_GIB),
)

suspend fun setEnabled(value: Boolean) {
dataStore.edit {
it[enabledKey] = value
if (!value) it.remove(planKey)
}
}

suspend fun setSongLimit(value: Int) {
dataStore.edit {
it[limitKey] = value.coerceIn(SmartDownloadsSettings.MIN_SONG_LIMIT, SmartDownloadsSettings.MAX_SONG_LIMIT)
}
}

suspend fun setWifiOnly(value: Boolean) {
dataStore.edit { it[wifiKey] = value }
}

suspend fun setStorageLimitGiB(value: Int) {
dataStore.edit {
it[storageLimitKey] = value.coerceIn(
SmartDownloadsSettings.MIN_STORAGE_LIMIT_GIB, SmartDownloadsSettings.MAX_STORAGE_LIMIT_GIB,
)
}
}

internal suspend fun readPlan(): SmartDownloadsPlan? {
val value = values.first().readSafely(planKey) ?: return null
return try {
Json.decodeFromString(SmartDownloadsPlan.serializer(), value)
} catch (_: SerializationException) {
null
}
}

internal suspend fun savePlan(plan: SmartDownloadsPlan, expected: SmartDownloadsSettings) {
dataStore.edit {
if (it.smartSettings() == expected) {
it[planKey] = Json.encodeToString(SmartDownloadsPlan.serializer(), plan)
}
}
}

private companion object {
val enabledKey = booleanPreferencesKey("lw_smart_downloads")
val limitKey = intPreferencesKey("lw_smart_download_song_limit")
val wifiKey = booleanPreferencesKey("lw_smart_downloads_wifi_only")
val storageLimitKey = intPreferencesKey("lw_smart_download_storage_limit_gib")
val planKey = stringPreferencesKey("lw_smart_download_plan")
}
}
Loading
Loading