From 813eb7fb32808cc52c1b444f2082ec319f52be40 Mon Sep 17 00:00:00 2001 From: Anthony La Date: Sun, 16 Feb 2025 11:45:11 -0800 Subject: [PATCH] Refactored wallpaper service --- app/src/main/AndroidManifest.xml | 1 + .../anthonyla/paperize/core/WallpaperUtil.kt | 3 +- .../wallpaper/presentation/PaperizeApp.kt | 27 +- .../presentation/album/AlbumsViewModel.kt | 1 - .../settings_screen/SettingsState.kt | 22 + .../settings_screen/SettingsViewModel.kt | 8 +- .../components/PreviewItem.kt | 6 +- .../WallpaperAlarmSchedulerImpl.kt | 1 + .../WallpaperReceiver.kt | 1 + .../wallpaper_service/HomeWallpaperService.kt | 889 +++++++++--------- .../wallpaper_service/LockWallpaperService.kt | 712 ++++++-------- 11 files changed, 800 insertions(+), 871 deletions(-) diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index 7a9d521..93cad41 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -19,6 +19,7 @@ android:icon="@mipmap/app_icon" android:label="@string/app_name" android:supportsRtl="true" + android:enableOnBackInvokedCallback="true" android:theme="@style/Theme.Paperize" tools:targetApi="tiramisu"> val currentSettings = settingsState.value - val albumName = album.album.initialAlbumName - val notSameAlbum = currentSettings.wallpaperSettings.homeAlbumName != currentSettings.wallpaperSettings.lockAlbumName - val newHomeAlbum = if (home) albumName else null - val newLockAlbum = if (lock) albumName else null + val notSameAlbum = currentSettings.wallpaperSettings.lockAlbumName != currentSettings.wallpaperSettings.homeAlbumName + val newLockAlbum = if (lock) album.album.initialAlbumName else null + val newHomeAlbum = if (home) album.album.initialAlbumName else null settingsViewModel.onEvent(SettingsEvent.SetAlbum( homeAlbumName = newHomeAlbum, lockAlbumName = newLockAlbum )) - val deselectName = when { - notSameAlbum && home -> currentSettings.wallpaperSettings.homeAlbumName - notSameAlbum && lock -> currentSettings.wallpaperSettings.lockAlbumName - else -> null - } albumsViewModel.onEvent( AlbumsEvent.AddSelectedAlbum( album = album, - deselectAlbumName = deselectName, + deselectAlbumName = when { + notSameAlbum && lock -> currentSettings.wallpaperSettings.lockAlbumName + notSameAlbum && home -> currentSettings.wallpaperSettings.homeAlbumName + else -> null + }, shuffle = currentSettings.scheduleSettings.shuffle ) ) - - val shouldSchedule = (home && !currentSettings.wallpaperSettings.lockAlbumName.isNullOrEmpty()) || + val shouldSchedule = + (home && !currentSettings.wallpaperSettings.lockAlbumName.isNullOrEmpty()) || (lock && !currentSettings.wallpaperSettings.homeAlbumName.isNullOrEmpty()) || - (lock && home) + (lock && home) if (shouldSchedule) { job = scope.scheduleWallpaperUpdate( @@ -238,7 +236,8 @@ fun PaperizeApp( refreshNextTime = true, changeImmediate = true, cancelImmediate = true, - firstLaunch = true + firstLaunch = true, + delay = 500L ) } }, diff --git a/app/src/main/java/com/anthonyla/paperize/feature/wallpaper/presentation/album/AlbumsViewModel.kt b/app/src/main/java/com/anthonyla/paperize/feature/wallpaper/presentation/album/AlbumsViewModel.kt index 5502571..8c099a4 100644 --- a/app/src/main/java/com/anthonyla/paperize/feature/wallpaper/presentation/album/AlbumsViewModel.kt +++ b/app/src/main/java/com/anthonyla/paperize/feature/wallpaper/presentation/album/AlbumsViewModel.kt @@ -2,7 +2,6 @@ package com.anthonyla.paperize.feature.wallpaper.presentation.album import android.app.Application import android.content.Context -import androidx.compose.ui.util.fastMap import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.viewModelScope import com.anthonyla.paperize.core.findFirstValidUri diff --git a/app/src/main/java/com/anthonyla/paperize/feature/wallpaper/presentation/settings_screen/SettingsState.kt b/app/src/main/java/com/anthonyla/paperize/feature/wallpaper/presentation/settings_screen/SettingsState.kt index bda777d..04c3767 100644 --- a/app/src/main/java/com/anthonyla/paperize/feature/wallpaper/presentation/settings_screen/SettingsState.kt +++ b/app/src/main/java/com/anthonyla/paperize/feature/wallpaper/presentation/settings_screen/SettingsState.kt @@ -56,4 +56,26 @@ data class SettingsState( val homeGrayscalePercentage: Int = 0, val lockGrayscalePercentage: Int = 0 ) + + data class ServiceSettings( + val enableChanger: Boolean, + val setHome: Boolean, + val setLock: Boolean, + val scaling: ScalingConstants, + val darken: Boolean, + val homeDarkenPercentage: Int, + val lockDarkenPercentage: Int, + val blur: Boolean, + val homeBlurPercentage: Int, + val lockBlurPercentage: Int, + val vignette: Boolean, + val homeVignettePercentage: Int, + val lockVignettePercentage: Int, + val grayscale: Boolean, + val homeGrayscalePercentage: Int, + val lockGrayscalePercentage: Int, + val lockAlbumName: String, + val homeAlbumName: String, + val shuffle: Boolean + ) } \ No newline at end of file diff --git a/app/src/main/java/com/anthonyla/paperize/feature/wallpaper/presentation/settings_screen/SettingsViewModel.kt b/app/src/main/java/com/anthonyla/paperize/feature/wallpaper/presentation/settings_screen/SettingsViewModel.kt index b3bc43d..131ee81 100644 --- a/app/src/main/java/com/anthonyla/paperize/feature/wallpaper/presentation/settings_screen/SettingsViewModel.kt +++ b/app/src/main/java/com/anthonyla/paperize/feature/wallpaper/presentation/settings_screen/SettingsViewModel.kt @@ -419,12 +419,8 @@ class SettingsViewModel @Inject constructor( is SettingsEvent.SetAlbum -> { viewModelScope.launch { - if (event.homeAlbumName != null) { - settingsDataStoreImpl.putString(SettingsConstants.HOME_ALBUM_NAME, event.homeAlbumName) - } - if (event.lockAlbumName != null) { - settingsDataStoreImpl.putString(SettingsConstants.LOCK_ALBUM_NAME, event.lockAlbumName) - } + event.lockAlbumName?.let { settingsDataStoreImpl.putString(SettingsConstants.LOCK_ALBUM_NAME, it) } + event.homeAlbumName?.let { settingsDataStoreImpl.putString(SettingsConstants.HOME_ALBUM_NAME, it) } val enableChanger: Boolean = when { event.homeAlbumName != null && event.lockAlbumName != null -> { true } event.homeAlbumName != null && !_state.value.wallpaperSettings.lockAlbumName.isNullOrEmpty() -> { true } diff --git a/app/src/main/java/com/anthonyla/paperize/feature/wallpaper/presentation/wallpaper_screen/components/PreviewItem.kt b/app/src/main/java/com/anthonyla/paperize/feature/wallpaper/presentation/wallpaper_screen/components/PreviewItem.kt index 717afa3..ef10c35 100644 --- a/app/src/main/java/com/anthonyla/paperize/feature/wallpaper/presentation/wallpaper_screen/components/PreviewItem.kt +++ b/app/src/main/java/com/anthonyla/paperize/feature/wallpaper/presentation/wallpaper_screen/components/PreviewItem.kt @@ -1,5 +1,6 @@ package com.anthonyla.paperize.feature.wallpaper.presentation.wallpaper_screen.components +import android.util.Log import androidx.compose.foundation.background import androidx.compose.foundation.border import androidx.compose.foundation.layout.size @@ -21,7 +22,9 @@ import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.unit.IntSize import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.times +import androidx.core.net.toUri import com.anthonyla.paperize.core.ScalingConstants +import com.anthonyla.paperize.core.decompress import com.anthonyla.paperize.core.isValidUri import com.bumptech.glide.request.RequestOptions import com.skydoves.landscapist.ImageOptions @@ -49,8 +52,9 @@ fun PreviewItem( val screenWidth = configuration.screenWidthDp.dp val screenHeight = configuration.screenHeightDp.dp if (showUri) { + val uri = wallpaperUri.decompress("content://com.android.externalstorage.documents/").toUri() GlideImage( - imageModel = { wallpaperUri }, + imageModel = { uri }, imageOptions = ImageOptions( contentScale = when (scaling) { ScalingConstants.FILL -> ContentScale.FillHeight diff --git a/app/src/main/java/com/anthonyla/paperize/feature/wallpaper/wallpaper_alarmmanager/WallpaperAlarmSchedulerImpl.kt b/app/src/main/java/com/anthonyla/paperize/feature/wallpaper/wallpaper_alarmmanager/WallpaperAlarmSchedulerImpl.kt index 3c79823..cb0b3a7 100644 --- a/app/src/main/java/com/anthonyla/paperize/feature/wallpaper/wallpaper_alarmmanager/WallpaperAlarmSchedulerImpl.kt +++ b/app/src/main/java/com/anthonyla/paperize/feature/wallpaper/wallpaper_alarmmanager/WallpaperAlarmSchedulerImpl.kt @@ -5,6 +5,7 @@ import android.app.PendingIntent import android.content.Context import android.content.Intent import android.os.Build +import android.util.Log import com.anthonyla.paperize.core.Type import com.anthonyla.paperize.feature.wallpaper.wallpaper_service.HomeWallpaperService import com.anthonyla.paperize.feature.wallpaper.wallpaper_service.LockWallpaperService diff --git a/app/src/main/java/com/anthonyla/paperize/feature/wallpaper/wallpaper_alarmmanager/WallpaperReceiver.kt b/app/src/main/java/com/anthonyla/paperize/feature/wallpaper/wallpaper_alarmmanager/WallpaperReceiver.kt index cb7d69e..e78d9e4 100644 --- a/app/src/main/java/com/anthonyla/paperize/feature/wallpaper/wallpaper_alarmmanager/WallpaperReceiver.kt +++ b/app/src/main/java/com/anthonyla/paperize/feature/wallpaper/wallpaper_alarmmanager/WallpaperReceiver.kt @@ -3,6 +3,7 @@ package com.anthonyla.paperize.feature.wallpaper.wallpaper_alarmmanager import android.content.BroadcastReceiver import android.content.Context import android.content.Intent +import android.util.Log import com.anthonyla.paperize.core.SettingsConstants.WALLPAPER_CHANGE_INTERVAL_DEFAULT import com.anthonyla.paperize.core.Type import com.anthonyla.paperize.feature.wallpaper.wallpaper_service.HomeWallpaperService diff --git a/app/src/main/java/com/anthonyla/paperize/feature/wallpaper/wallpaper_service/HomeWallpaperService.kt b/app/src/main/java/com/anthonyla/paperize/feature/wallpaper/wallpaper_service/HomeWallpaperService.kt index 7b7852c..2001b1c 100644 --- a/app/src/main/java/com/anthonyla/paperize/feature/wallpaper/wallpaper_service/HomeWallpaperService.kt +++ b/app/src/main/java/com/anthonyla/paperize/feature/wallpaper/wallpaper_service/HomeWallpaperService.kt @@ -1,6 +1,7 @@ package com.anthonyla.paperize.feature.wallpaper.wallpaper_service import android.app.Notification +import android.app.NotificationManager import android.app.PendingIntent import android.app.Service import android.app.WallpaperManager @@ -12,22 +13,33 @@ import android.os.HandlerThread import android.os.IBinder import android.util.Log import androidx.core.app.NotificationCompat +import androidx.core.net.toUri import com.anthonyla.paperize.R import com.anthonyla.paperize.core.ScalingConstants import com.anthonyla.paperize.core.SettingsConstants import com.anthonyla.paperize.core.Type +import com.anthonyla.paperize.core.decompress +import com.anthonyla.paperize.core.findFirstValidUri import com.anthonyla.paperize.core.getDeviceScreenSize +import com.anthonyla.paperize.core.getFolderMetadata +import com.anthonyla.paperize.core.getWallpaperFromFolder +import com.anthonyla.paperize.core.isDirectory +import com.anthonyla.paperize.core.isValidUri import com.anthonyla.paperize.core.processBitmap import com.anthonyla.paperize.core.retrieveBitmap import com.anthonyla.paperize.data.settings.SettingsDataStore import com.anthonyla.paperize.feature.wallpaper.domain.repository.AlbumRepository import com.anthonyla.paperize.feature.wallpaper.presentation.MainActivity +import com.anthonyla.paperize.feature.wallpaper.presentation.settings_screen.SettingsState import com.anthonyla.paperize.feature.wallpaper.tasker_shortcut.triggerWallpaperTaskerEvent import com.anthonyla.paperize.feature.wallpaper.wallpaper_alarmmanager.WallpaperBootAndChangeReceiver import dagger.hilt.android.AndroidEntryPoint import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.async +import kotlinx.coroutines.awaitAll import kotlinx.coroutines.delay +import kotlinx.coroutines.flow.first import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import java.io.IOException @@ -36,7 +48,6 @@ import java.time.format.DateTimeFormatter import java.time.format.FormatStyle import javax.inject.Inject - /** * Service for changing home screen */ @@ -71,7 +82,6 @@ class HomeWallpaperService: Service() { if (intent != null) { when (intent.action) { Actions.START.toString() -> { - Log.d("PaperizeWallpaperChanger", "Starting home start wallpaper service") homeInterval = intent.getIntExtra("homeInterval", SettingsConstants.WALLPAPER_CHANGE_INTERVAL_DEFAULT) lockInterval = intent.getIntExtra("lockInterval", SettingsConstants.WALLPAPER_CHANGE_INTERVAL_DEFAULT) scheduleSeparately = intent.getBooleanExtra("scheduleSeparately", false) @@ -79,11 +89,9 @@ class HomeWallpaperService: Service() { workerTaskStart() } Actions.UPDATE.toString() -> { - Log.d("PaperizeWallpaperChanger", "Starting home update wallpaper service") workerTaskUpdate() } Actions.REFRESH.toString() -> { - Log.d("PaperizeWallpaperChanger", "Starting home refresh wallpaper service") workerTaskRefresh() } } @@ -99,7 +107,7 @@ class HomeWallpaperService: Service() { private fun workerTaskStart() { CoroutineScope(Dispatchers.Default).launch { - delay(20) + delay(50) changeWallpaper(this@HomeWallpaperService) withContext(Dispatchers.Main) { stopSelf() @@ -125,434 +133,420 @@ class HomeWallpaperService: Service() { } } - /** - * Creates a notification for the wallpaper service - */ - private fun createNotification(nextSetTime: LocalDateTime?): Notification? { - val changeWallpaperIntent = Intent(this, WallpaperBootAndChangeReceiver::class.java) - val pendingChangeWallpaperIntent = PendingIntent.getBroadcast(this, 0, changeWallpaperIntent, PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT) - val formatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT) - if (nextSetTime != null) { - val intent = Intent(this, MainActivity::class.java) - val pendingIntent = PendingIntent.getActivity(this, 3, intent, PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT) - return NotificationCompat.Builder(this, "wallpaper_service_channel") - .setContentTitle(getString(R.string.app_name)) - .setContentText(getString(R.string.next_wallpaper_change, nextSetTime.format(formatter))) - .setSmallIcon(R.drawable.notification_icon) - .setContentIntent(pendingIntent) - .addAction(R.drawable.notification_icon, getString(R.string.change_wallpaper), pendingChangeWallpaperIntent) - .build() + // Creates a notification for the wallpaper service + private fun createNotification(nextSetTime: LocalDateTime?): android.app.Notification? { + nextSetTime?.let { + val changeWallpaperIntent = Intent(this, WallpaperBootAndChangeReceiver::class.java) + val pendingChangeWallpaperIntent = PendingIntent.getBroadcast( + this, + 0, + changeWallpaperIntent, + PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT + ) + val mainActivityIntent = Intent(this, MainActivity::class.java) + val pendingMainActivityIntent = PendingIntent.getActivity( + this, + 3, + mainActivityIntent, + PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT + ) + + val formatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT) + val formattedNextSetTime = nextSetTime.format(formatter) + + // Build the notification + return NotificationCompat.Builder(this, "wallpaper_service_channel").apply { + setContentTitle(getString(R.string.app_name)) + setContentText(getString(R.string.next_wallpaper_change, formattedNextSetTime)) + setSmallIcon(R.drawable.notification_icon) + setContentIntent(pendingMainActivityIntent) + addAction(R.drawable.notification_icon, getString(R.string.change_wallpaper), pendingChangeWallpaperIntent) + priority = NotificationCompat.PRIORITY_DEFAULT + setAutoCancel(true) + }.build() } return null } + private suspend fun getWallpaperSettings(): SettingsState.ServiceSettings { + return SettingsState.ServiceSettings( + enableChanger = settingsDataStoreImpl.getBoolean(SettingsConstants.ENABLE_CHANGER) ?: false, + setHome = settingsDataStoreImpl.getBoolean(SettingsConstants.ENABLE_HOME_WALLPAPER) ?: false, + setLock = settingsDataStoreImpl.getBoolean(SettingsConstants.ENABLE_LOCK_WALLPAPER) ?: false, + scaling = settingsDataStoreImpl.getString(SettingsConstants.WALLPAPER_SCALING)?.let { ScalingConstants.valueOf(it) } ?: ScalingConstants.FILL, + darken = settingsDataStoreImpl.getBoolean(SettingsConstants.DARKEN) ?: false, + homeDarkenPercentage = settingsDataStoreImpl.getInt(SettingsConstants.HOME_DARKEN_PERCENTAGE) ?: 100, + lockDarkenPercentage = settingsDataStoreImpl.getInt(SettingsConstants.LOCK_DARKEN_PERCENTAGE) ?: 100, + blur = settingsDataStoreImpl.getBoolean(SettingsConstants.BLUR) ?: false, + homeBlurPercentage = settingsDataStoreImpl.getInt(SettingsConstants.HOME_BLUR_PERCENTAGE) ?: 0, + lockBlurPercentage = settingsDataStoreImpl.getInt(SettingsConstants.LOCK_BLUR_PERCENTAGE) ?: 0, + vignette = settingsDataStoreImpl.getBoolean(SettingsConstants.VIGNETTE) ?: false, + homeVignettePercentage = settingsDataStoreImpl.getInt(SettingsConstants.HOME_VIGNETTE_PERCENTAGE) ?: 0, + lockVignettePercentage = settingsDataStoreImpl.getInt(SettingsConstants.LOCK_VIGNETTE_PERCENTAGE) ?: 0, + grayscale = settingsDataStoreImpl.getBoolean(SettingsConstants.GRAYSCALE) ?: false, + homeGrayscalePercentage = settingsDataStoreImpl.getInt(SettingsConstants.HOME_GRAYSCALE_PERCENTAGE) ?: 0, + lockGrayscalePercentage = settingsDataStoreImpl.getInt(SettingsConstants.LOCK_GRAYSCALE_PERCENTAGE) ?: 0, + lockAlbumName = settingsDataStoreImpl.getString(SettingsConstants.LOCK_ALBUM_NAME) ?: "", + homeAlbumName = settingsDataStoreImpl.getString(SettingsConstants.HOME_ALBUM_NAME) ?: "", + shuffle = settingsDataStoreImpl.getBoolean(SettingsConstants.SHUFFLE) ?: true + ) + } + /** * Changes the wallpaper to the next wallpaper in the queue of the selected album * If none left, reshuffle the wallpapers and pick the first one */ private suspend fun changeWallpaper(context: Context) { - /*try { - var selectedAlbum = selectedRepository.getSelectedAlbum().first() + try { + var selectedAlbum = albumRepository.getSelectedAlbums().first() if (selectedAlbum.isEmpty()) { onDestroy() return } - else { - val setHome = settingsDataStoreImpl.getBoolean(SettingsConstants.ENABLE_HOME_WALLPAPER) ?: false - val setLock = settingsDataStoreImpl.getBoolean(SettingsConstants.ENABLE_LOCK_WALLPAPER) ?: false - if (!setHome && !setLock) { - onDestroy() - return - } - val scaling = settingsDataStoreImpl.getString(SettingsConstants.WALLPAPER_SCALING)?.let { ScalingConstants.valueOf(it) } ?: ScalingConstants.FILL - val darken = settingsDataStoreImpl.getBoolean(SettingsConstants.DARKEN) ?: false - val homeDarkenPercentage = settingsDataStoreImpl.getInt(SettingsConstants.HOME_DARKEN_PERCENTAGE) ?: 100 - val blur = settingsDataStoreImpl.getBoolean(SettingsConstants.BLUR) ?: false - val homeBlurPercentage = settingsDataStoreImpl.getInt(SettingsConstants.HOME_BLUR_PERCENTAGE) ?: 0 - val vignette = settingsDataStoreImpl.getBoolean(SettingsConstants.VIGNETTE) ?: false - val homeVignettePercentage = settingsDataStoreImpl.getInt(SettingsConstants.HOME_VIGNETTE_PERCENTAGE) ?: 0 - val grayscale = settingsDataStoreImpl.getBoolean(SettingsConstants.GRAYSCALE) ?: false - val homeGrayscalePercentage = settingsDataStoreImpl.getInt(SettingsConstants.HOME_GRAYSCALE_PERCENTAGE) ?: 0 - val homeAlbumName = settingsDataStoreImpl.getString(SettingsConstants.HOME_ALBUM_NAME) ?: "" - val lockAlbumName = settingsDataStoreImpl.getString(SettingsConstants.LOCK_ALBUM_NAME) ?: "" - var homeAlbum = selectedAlbum.find { it.album.initialAlbumName == homeAlbumName } - if (homeAlbum == null) { - onDestroy() - return - } - when { - // Case: Set home and lock screen wallpapers using separate albums (home screen and lock screen album) - setHome && setLock && scheduleSeparately -> { - var wallpaper = homeAlbum.album.homeWallpapersInQueue.firstOrNull() + val settings = getWallpaperSettings() + if (!settings.setHome && !settings.setLock) { + onDestroy() + return + } + var homeAlbum = selectedAlbum.find { it.album.initialAlbumName == settings.homeAlbumName } + if (homeAlbum == null) { + onDestroy() + return + } + when { + // Case: Set home and lock screen wallpapers using separate albums (home screen and lock screen album) + settings.setHome && settings.setLock && scheduleSeparately -> { + var wallpaper = homeAlbum.album.homeWallpapersInQueue.firstOrNull() + if (wallpaper == null) { + val newWallpapers = if (settings.shuffle) homeAlbum.wallpapers.map { it.wallpaperUri }.shuffled() + else homeAlbum.wallpapers.map { it.wallpaperUri } + wallpaper = newWallpapers.firstOrNull() if (wallpaper == null) { - val newWallpapers = homeAlbum.wallpapers.map { it.wallpaperUri }.shuffled() - wallpaper = newWallpapers.firstOrNull() - if (wallpaper == null) { - selectedRepository.cascadeDeleteAlbum(homeAlbum.album.initialAlbumName) - onDestroy() - return - } - else { - val success = isValidUri(context, wallpaper) - settingsDataStoreImpl.putString(SettingsConstants.NEXT_HOME_WALLPAPER, if (newWallpapers.size > 1) newWallpapers[1] else homeAlbum.wallpapers.firstOrNull()?.wallpaperUri ?: "") - if (success) { - selectedRepository.upsertSelectedAlbum(homeAlbum.copy(album = homeAlbum.album.copy(homeWallpapersInQueue = newWallpapers.drop(1)))) - settingsDataStoreImpl.putString(SettingsConstants.CURRENT_HOME_WALLPAPER, wallpaper.toString()) - setWallpaper( - context = context, - wallpaper = wallpaper.toUri(), - darken = darken, - darkenPercent = homeDarkenPercentage, - scaling = scaling, - blur = blur, - blurPercent = homeBlurPercentage, - vignette = vignette, - vignettePercent = homeVignettePercentage, - grayscale = grayscale, - grayscalePercent = homeGrayscalePercentage - ) - } - else { - val wallpaperToDelete = homeAlbum.wallpapers.find { it.wallpaperUri == wallpaper } - if (wallpaperToDelete != null) { - albumRepository.deleteWallpaper(wallpaperToDelete) - selectedRepository.deleteWallpaper(wallpaperToDelete) - selectedRepository.upsertSelectedAlbum( - homeAlbum.copy( - album = homeAlbum.album.copy( - homeWallpapersInQueue = homeAlbum.album.homeWallpapersInQueue.filterNot { it == wallpaper } - ), - wallpapers = homeAlbum.wallpapers.filterNot { it.wallpaperUri == wallpaper } - ) - ) - } - } - } + albumRepository.cascadeDeleteAlbum(homeAlbum.album) + onDestroy() + return } else { val success = isValidUri(context, wallpaper) - settingsDataStoreImpl.putString(SettingsConstants.NEXT_HOME_WALLPAPER, if (homeAlbum.album.homeWallpapersInQueue.size > 1) homeAlbum.album.homeWallpapersInQueue[1] else homeAlbum.wallpapers.firstOrNull()?.wallpaperUri ?: "") - if ((homeInterval % lockInterval == 0) || (lockInterval % homeInterval == 0) && (homeAlbumName == lockAlbumName)) { - delay(1000) - selectedAlbum = selectedRepository.getSelectedAlbum().first() - homeAlbum = selectedAlbum.find { it.album.initialAlbumName == homeAlbumName } - } - if (homeAlbum != null) { - if (success) { - selectedRepository.upsertSelectedAlbum(homeAlbum.copy(album = homeAlbum.album.copy(homeWallpapersInQueue = homeAlbum.album.homeWallpapersInQueue.drop(1)))) - settingsDataStoreImpl.putString(SettingsConstants.CURRENT_HOME_WALLPAPER, wallpaper.toString()) - setWallpaper( - context = context, - wallpaper = wallpaper.toUri(), - darken = darken, - darkenPercent = homeDarkenPercentage, - scaling = scaling, - blur = blur, - blurPercent = homeBlurPercentage, - vignette = vignette, - vignettePercent = homeVignettePercentage, - grayscale = grayscale, - grayscalePercent = homeGrayscalePercentage - ) - } - else { - val wallpaperToDelete = homeAlbum.wallpapers.find { it.wallpaperUri == wallpaper } - if (wallpaperToDelete != null) { - albumRepository.deleteWallpaper(wallpaperToDelete) - selectedRepository.deleteWallpaper(wallpaperToDelete) - selectedRepository.upsertSelectedAlbum( - homeAlbum.copy( - album = homeAlbum.album.copy( - homeWallpapersInQueue = homeAlbum.album.homeWallpapersInQueue.filterNot { it == wallpaper } - ), - wallpapers = homeAlbum.wallpapers.filterNot { it.wallpaperUri == wallpaper } - ) - ) - } - } - } - } - } - // Case: Set home and lock screen wallpapers using the same album (home screen album) - setHome && setLock && !scheduleSeparately -> { - var wallpaper = homeAlbum.album.homeWallpapersInQueue.firstOrNull() - if (wallpaper == null) { - val newWallpapers = homeAlbum.wallpapers.map { it.wallpaperUri }.shuffled() - wallpaper = newWallpapers.firstOrNull() - if (wallpaper == null) { - selectedRepository.cascadeDeleteAlbum(homeAlbum.album.initialAlbumName) - onDestroy() - return - } - else { - val success = isValidUri(context, wallpaper) - settingsDataStoreImpl.putString(SettingsConstants.NEXT_HOME_WALLPAPER, if (homeAlbum.album.homeWallpapersInQueue.size > 1) homeAlbum.album.homeWallpapersInQueue[1] else homeAlbum.wallpapers.firstOrNull()?.wallpaperUri ?: "") - if (success) { - if (newWallpapers.size > 1) { - selectedRepository.upsertSelectedAlbum(homeAlbum.copy(album = homeAlbum.album.copy(homeWallpapersInQueue = newWallpapers.drop(1)))) - } - settingsDataStoreImpl.putString(SettingsConstants.CURRENT_HOME_WALLPAPER, wallpaper.toString()) - setWallpaper( - context = context, - wallpaper = wallpaper.toUri(), - darken = darken, - darkenPercent = homeDarkenPercentage, - scaling = scaling, - blur = blur, - blurPercent = homeBlurPercentage, - vignette = vignette, - vignettePercent = homeVignettePercentage, - grayscale = grayscale, - grayscalePercent = homeGrayscalePercentage - ) - } - else { - val wallpaperToDelete = homeAlbum.wallpapers.find { it.wallpaperUri == wallpaper } - if (wallpaperToDelete != null) { - albumRepository.deleteWallpaper(wallpaperToDelete) - selectedRepository.deleteWallpaper(wallpaperToDelete) - selectedRepository.upsertSelectedAlbum( - homeAlbum.copy( - album = homeAlbum.album.copy( - homeWallpapersInQueue = homeAlbum.album.homeWallpapersInQueue.filterNot { it == wallpaper } - ), - wallpapers = homeAlbum.wallpapers.filterNot { it.wallpaperUri == wallpaper } - ) - ) - } - } - } - } - else { - val success = isValidUri(context, wallpaper) - settingsDataStoreImpl.putString(SettingsConstants.NEXT_HOME_WALLPAPER, if (homeAlbum.album.homeWallpapersInQueue.size > 1) homeAlbum.album.homeWallpapersInQueue[1] else homeAlbum.wallpapers.firstOrNull()?.wallpaperUri ?: "") if (success) { - if (homeAlbum.album.homeWallpapersInQueue.size > 1) { - selectedRepository.upsertSelectedAlbum(homeAlbum.copy(album = homeAlbum.album.copy(homeWallpapersInQueue = homeAlbum.album.homeWallpapersInQueue.drop(1)))) - } - else { - val newWallpapers = homeAlbum.wallpapers.map { it.wallpaperUri }.shuffled() - if (newWallpapers.isNotEmpty()) { - selectedRepository.upsertSelectedAlbum(homeAlbum.copy(album = homeAlbum.album.copy(homeWallpapersInQueue = newWallpapers))) - } - else { - selectedRepository.cascadeDeleteAlbum(homeAlbum.album.initialAlbumName) - onDestroy() - return - } - } settingsDataStoreImpl.putString(SettingsConstants.CURRENT_HOME_WALLPAPER, wallpaper.toString()) + albumRepository.upsertAlbum(homeAlbum.album.copy(homeWallpapersInQueue = newWallpapers.drop(1))) setWallpaper( context = context, - wallpaper = wallpaper.toUri(), - darken = darken, - darkenPercent = homeDarkenPercentage, - scaling = scaling, - blur = blur, - blurPercent = homeBlurPercentage, - vignette = vignette, - vignettePercent = homeVignettePercentage, - grayscale = grayscale, - grayscalePercent = homeGrayscalePercentage + wallpaper = wallpaper.decompress("content://com.android.externalstorage.documents/").toUri(), + darken = settings.darken, + darkenPercent = settings.homeDarkenPercentage, + scaling = settings.scaling, + blur = settings.blur, + blurPercent = settings.homeBlurPercentage, + vignette = settings.vignette, + vignettePercent = settings.homeVignettePercentage, + grayscale = settings.grayscale, + grayscalePercent = settings.homeGrayscalePercentage ) } else { val wallpaperToDelete = homeAlbum.wallpapers.find { it.wallpaperUri == wallpaper } if (wallpaperToDelete != null) { albumRepository.deleteWallpaper(wallpaperToDelete) - selectedRepository.deleteWallpaper(wallpaperToDelete) - selectedRepository.upsertSelectedAlbum( + albumRepository.upsertAlbumWithWallpaperAndFolder( homeAlbum.copy( + wallpapers = homeAlbum.wallpapers.filterNot { it.wallpaperUri == wallpaper }, album = homeAlbum.album.copy( - homeWallpapersInQueue = homeAlbum.album.homeWallpapersInQueue.filterNot { it == wallpaper } - ), - wallpapers = homeAlbum.wallpapers.filterNot { it.wallpaperUri == wallpaper } + homeWallpapersInQueue = homeAlbum.album.homeWallpapersInQueue.filterNot { it == wallpaper }, + lockWallpapersInQueue = homeAlbum.album.lockWallpapersInQueue.filterNot { it == wallpaper } + ) ) ) } } } } - // Case: Set home screen wallpaper (home screen album) - setHome -> { - var wallpaper = homeAlbum.album.homeWallpapersInQueue.firstOrNull() - if (wallpaper == null) { - val newWallpapers = homeAlbum.wallpapers.map { it.wallpaperUri }.shuffled() - wallpaper = newWallpapers.firstOrNull() - if (wallpaper == null) { - selectedRepository.cascadeDeleteAlbum(homeAlbum.album.initialAlbumName) - onDestroy() - return + else { + val success = isValidUri(context, wallpaper) + if ((homeInterval % lockInterval == 0) || (lockInterval % homeInterval == 0) && (settings.homeAlbumName == settings.lockAlbumName)) { + delay(1000) + selectedAlbum = albumRepository.getSelectedAlbums().first() + homeAlbum = selectedAlbum.find { it.album.initialAlbumName == settings.homeAlbumName } + } + if (homeAlbum != null) { + if (success) { + settingsDataStoreImpl.putString(SettingsConstants.CURRENT_HOME_WALLPAPER, wallpaper.toString()) + albumRepository.upsertAlbum(homeAlbum.album.copy(homeWallpapersInQueue = homeAlbum.album.homeWallpapersInQueue.drop(1))) + setWallpaper( + context = context, + wallpaper = wallpaper.decompress("content://com.android.externalstorage.documents/").toUri(), + darken = settings.darken, + darkenPercent = settings.homeDarkenPercentage, + scaling = settings.scaling, + blur = settings.blur, + blurPercent = settings.homeBlurPercentage, + vignette = settings.vignette, + vignettePercent = settings.homeVignettePercentage, + grayscale = settings.grayscale, + grayscalePercent = settings.homeGrayscalePercentage + ) } else { - val success = isValidUri(context, wallpaper) - settingsDataStoreImpl.putString(SettingsConstants.NEXT_HOME_WALLPAPER, if (homeAlbum.album.homeWallpapersInQueue.size > 1) homeAlbum.album.homeWallpapersInQueue[1] else homeAlbum.wallpapers.firstOrNull()?.wallpaperUri ?: "") - settingsDataStoreImpl.putString(SettingsConstants.NEXT_LOCK_WALLPAPER, if (homeAlbum.album.homeWallpapersInQueue.size > 1) homeAlbum.album.homeWallpapersInQueue[1] else homeAlbum.wallpapers.firstOrNull()?.wallpaperUri ?: "") - if (success) { - selectedRepository.upsertSelectedAlbum(homeAlbum.copy(album = homeAlbum.album.copy(homeWallpapersInQueue = newWallpapers.drop(1)))) - settingsDataStoreImpl.putString(SettingsConstants.CURRENT_HOME_WALLPAPER, wallpaper.toString()) - settingsDataStoreImpl.putString(SettingsConstants.CURRENT_LOCK_WALLPAPER, wallpaper.toString()) - setWallpaper( - context = context, - wallpaper = wallpaper.toUri(), - darken = darken, - darkenPercent = homeDarkenPercentage, - scaling = scaling, - blur = blur, - blurPercent = homeBlurPercentage, - vignette = vignette, - vignettePercent = homeVignettePercentage, - grayscale = grayscale, - grayscalePercent = homeGrayscalePercentage - ) - - } - else { - val wallpaperToDelete = homeAlbum.wallpapers.find { it.wallpaperUri == wallpaper } - if (wallpaperToDelete != null) { - albumRepository.deleteWallpaper(wallpaperToDelete) - selectedRepository.deleteWallpaper(wallpaperToDelete) - selectedRepository.upsertSelectedAlbum( - homeAlbum.copy( - album = homeAlbum.album.copy( - homeWallpapersInQueue = homeAlbum.album.homeWallpapersInQueue.filterNot { it == wallpaper } - ), - wallpapers = homeAlbum.wallpapers.filterNot { it.wallpaperUri == wallpaper } + val wallpaperToDelete = homeAlbum.wallpapers.find { it.wallpaperUri == wallpaper } + if (wallpaperToDelete != null) { + albumRepository.deleteWallpaper(wallpaperToDelete) + albumRepository.upsertAlbumWithWallpaperAndFolder( + homeAlbum.copy( + wallpapers = homeAlbum.wallpapers.filterNot { it.wallpaperUri == wallpaper }, + album = homeAlbum.album.copy( + homeWallpapersInQueue = homeAlbum.album.homeWallpapersInQueue.filterNot { it == wallpaper }, + lockWallpapersInQueue = homeAlbum.album.lockWallpapersInQueue.filterNot { it == wallpaper } ) ) - } + ) } } } + } + } + // Case: Set home and lock screen wallpapers using the same album (home screen album) + settings.setHome && settings.setLock && !scheduleSeparately -> { + var wallpaper = homeAlbum.album.homeWallpapersInQueue.firstOrNull() + if (wallpaper == null) { + val newWallpapers = if (settings.shuffle) homeAlbum.wallpapers.map { it.wallpaperUri }.shuffled() + else homeAlbum.wallpapers.map { it.wallpaperUri } + wallpaper = newWallpapers.firstOrNull() + if (wallpaper == null) { + albumRepository.cascadeDeleteAlbum(homeAlbum.album) + onDestroy() + return + } + else { + val success = isValidUri(context, wallpaper) + if (success) { + settingsDataStoreImpl.putString(SettingsConstants.CURRENT_LOCK_WALLPAPER, wallpaper.toString()) + settingsDataStoreImpl.putString(SettingsConstants.CURRENT_HOME_WALLPAPER, wallpaper.toString()) + albumRepository.upsertAlbum(homeAlbum.album.copy(homeWallpapersInQueue = newWallpapers.drop(1))) + setWallpaper( + context = context, + wallpaper = wallpaper.decompress("content://com.android.externalstorage.documents/").toUri(), + darken = settings.darken, + darkenPercent = settings.homeDarkenPercentage, + scaling = settings.scaling, + blur = settings.blur, + blurPercent = settings.homeBlurPercentage, + vignette = settings.vignette, + vignettePercent = settings.homeVignettePercentage, + grayscale = settings.grayscale, + grayscalePercent = settings.homeGrayscalePercentage, + both = true + ) + } + else { + val wallpaperToDelete = homeAlbum.wallpapers.find { it.wallpaperUri == wallpaper } + if (wallpaperToDelete != null) { + albumRepository.deleteWallpaper(wallpaperToDelete) + albumRepository.upsertAlbumWithWallpaperAndFolder( + homeAlbum.copy( + wallpapers = homeAlbum.wallpapers.filterNot { it.wallpaperUri == wallpaper }, + album = homeAlbum.album.copy( + homeWallpapersInQueue = homeAlbum.album.homeWallpapersInQueue.filterNot { it == wallpaper }, + lockWallpapersInQueue = homeAlbum.album.lockWallpapersInQueue.filterNot { it == wallpaper } + ) + ) + ) + } + } + } + } + else { + val success = isValidUri(context, wallpaper) + if (success) { + settingsDataStoreImpl.putString(SettingsConstants.CURRENT_LOCK_WALLPAPER, wallpaper.toString()) + settingsDataStoreImpl.putString(SettingsConstants.CURRENT_HOME_WALLPAPER, wallpaper.toString()) + albumRepository.upsertAlbum(homeAlbum.album.copy(homeWallpapersInQueue = homeAlbum.album.homeWallpapersInQueue.drop(1))) + setWallpaper( + context = context, + wallpaper = wallpaper.decompress("content://com.android.externalstorage.documents/").toUri(), + darken = settings.darken, + darkenPercent = settings.homeDarkenPercentage, + scaling = settings.scaling, + blur = settings.blur, + blurPercent = settings.homeBlurPercentage, + vignette = settings.vignette, + vignettePercent = settings.homeVignettePercentage, + grayscale = settings.grayscale, + grayscalePercent = settings.homeGrayscalePercentage, + both = true + ) + + } + else { + val wallpaperToDelete = homeAlbum.wallpapers.find { it.wallpaperUri == wallpaper } + if (wallpaperToDelete != null) { + albumRepository.deleteWallpaper(wallpaperToDelete) + albumRepository.upsertAlbumWithWallpaperAndFolder( + homeAlbum.copy( + wallpapers = homeAlbum.wallpapers.filterNot { it.wallpaperUri == wallpaper }, + album = homeAlbum.album.copy( + homeWallpapersInQueue = homeAlbum.album.homeWallpapersInQueue.filterNot { it == wallpaper }, + lockWallpapersInQueue = homeAlbum.album.lockWallpapersInQueue.filterNot { it == wallpaper } + ) + ) + ) + } + } + } + } + // Case: Set home screen wallpaper (home screen album) + settings.setHome -> { + var wallpaper = homeAlbum.album.homeWallpapersInQueue.firstOrNull() + if (wallpaper == null) { + val newWallpapers = if (settings.shuffle) homeAlbum.wallpapers.map { it.wallpaperUri }.shuffled() + else homeAlbum.wallpapers.map { it.wallpaperUri } + wallpaper = newWallpapers.firstOrNull() + if (wallpaper == null) { + albumRepository.cascadeDeleteAlbum(homeAlbum.album) + onDestroy() + return + } else { val success = isValidUri(context, wallpaper) - settingsDataStoreImpl.putString(SettingsConstants.NEXT_HOME_WALLPAPER, if (homeAlbum.album.homeWallpapersInQueue.size > 1) homeAlbum.album.homeWallpapersInQueue[1] else homeAlbum.wallpapers.firstOrNull()?.wallpaperUri ?: "") - settingsDataStoreImpl.putString(SettingsConstants.NEXT_LOCK_WALLPAPER, if (homeAlbum.album.homeWallpapersInQueue.size > 1) homeAlbum.album.homeWallpapersInQueue[1] else homeAlbum.wallpapers.firstOrNull()?.wallpaperUri ?: "") if (success) { - selectedRepository.upsertSelectedAlbum(homeAlbum.copy(album = homeAlbum.album.copy(homeWallpapersInQueue = homeAlbum.album.homeWallpapersInQueue.drop(1)))) settingsDataStoreImpl.putString(SettingsConstants.CURRENT_HOME_WALLPAPER, wallpaper.toString()) settingsDataStoreImpl.putString(SettingsConstants.CURRENT_LOCK_WALLPAPER, wallpaper.toString()) + albumRepository.upsertAlbum(homeAlbum.album.copy(homeWallpapersInQueue = newWallpapers.drop(1))) setWallpaper( context = context, - wallpaper = wallpaper.toUri(), - darken = darken, - darkenPercent = homeDarkenPercentage, - scaling = scaling, - blur = blur, - blurPercent = homeBlurPercentage, - vignette = vignette, - vignettePercent = homeVignettePercentage, - grayscale = grayscale, - grayscalePercent = homeGrayscalePercentage + wallpaper = wallpaper.decompress("content://com.android.externalstorage.documents/").toUri(), + darken = settings.darken, + darkenPercent = settings.homeDarkenPercentage, + scaling = settings.scaling, + blur = settings.blur, + blurPercent = settings.homeBlurPercentage, + vignette = settings.vignette, + vignettePercent = settings.homeVignettePercentage, + grayscale = settings.grayscale, + grayscalePercent = settings.homeGrayscalePercentage ) + } else { val wallpaperToDelete = homeAlbum.wallpapers.find { it.wallpaperUri == wallpaper } if (wallpaperToDelete != null) { albumRepository.deleteWallpaper(wallpaperToDelete) - selectedRepository.deleteWallpaper(wallpaperToDelete) - selectedRepository.upsertSelectedAlbum( + albumRepository.upsertAlbumWithWallpaperAndFolder( homeAlbum.copy( + wallpapers = homeAlbum.wallpapers.filterNot { it.wallpaperUri == wallpaper }, album = homeAlbum.album.copy( - homeWallpapersInQueue = homeAlbum.album.homeWallpapersInQueue.filterNot { it == wallpaper } - ), - wallpapers = homeAlbum.wallpapers.filterNot { it.wallpaperUri == wallpaper } + homeWallpapersInQueue = homeAlbum.album.homeWallpapersInQueue.filterNot { it == wallpaper }, + lockWallpapersInQueue = homeAlbum.album.lockWallpapersInQueue.filterNot { it == wallpaper } + ) ) ) } } } } - } - // Run notification - val formatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT) - val homeNextSetTime: LocalDateTime? - var lockNextSetTime = try { - LocalDateTime.parse(settingsDataStoreImpl.getString(SettingsConstants.LOCK_NEXT_SET_TIME)) - } catch (_: Exception) { - LocalDateTime.now() - } - val nextSetTime: LocalDateTime? - val currentTime = LocalDateTime.now() - if (homeInterval == lockInterval) { - homeNextSetTime = currentTime.plusMinutes(homeInterval.toLong()) - lockNextSetTime = homeNextSetTime - nextSetTime = homeNextSetTime - nextSetTime?.let { - settingsDataStoreImpl.putString(SettingsConstants.LAST_SET_TIME, currentTime.format(formatter)) - settingsDataStoreImpl.putString(SettingsConstants.NEXT_SET_TIME, it.format(formatter)) - settingsDataStoreImpl.putString(SettingsConstants.HOME_NEXT_SET_TIME, it.toString()) - settingsDataStoreImpl.putString(SettingsConstants.LOCK_NEXT_SET_TIME, it.toString()) + else { + val success = isValidUri(context, wallpaper) + if (success) { + settingsDataStoreImpl.putString(SettingsConstants.CURRENT_HOME_WALLPAPER, wallpaper.toString()) + settingsDataStoreImpl.putString(SettingsConstants.CURRENT_LOCK_WALLPAPER, wallpaper.toString()) + albumRepository.upsertAlbum(homeAlbum.album.copy(homeWallpapersInQueue = homeAlbum.album.homeWallpapersInQueue.drop(1))) + setWallpaper( + context = context, + wallpaper = wallpaper.decompress("content://com.android.externalstorage.documents/").toUri(), + darken = settings.darken, + darkenPercent = settings.homeDarkenPercentage, + scaling = settings.scaling, + blur = settings.blur, + blurPercent = settings.homeBlurPercentage, + vignette = settings.vignette, + vignettePercent = settings.homeVignettePercentage, + grayscale = settings.grayscale, + grayscalePercent = settings.homeGrayscalePercentage + ) + } + else { + val wallpaperToDelete = homeAlbum.wallpapers.find { it.wallpaperUri == wallpaper } + if (wallpaperToDelete != null) { + albumRepository.deleteWallpaper(wallpaperToDelete) + albumRepository.upsertAlbumWithWallpaperAndFolder( + homeAlbum.copy( + wallpapers = homeAlbum.wallpapers.filterNot { it.wallpaperUri == wallpaper }, + album = homeAlbum.album.copy( + homeWallpapersInQueue = homeAlbum.album.homeWallpapersInQueue.filterNot { it == wallpaper }, + lockWallpapersInQueue = homeAlbum.album.lockWallpapersInQueue.filterNot { it == wallpaper } + ) + ) + ) + } + } } } - else { - homeNextSetTime = currentTime.plusMinutes(homeInterval.toLong()) - nextSetTime = if (homeNextSetTime.isBefore(lockNextSetTime) && homeNextSetTime.isAfter(currentTime)) homeNextSetTime - else if (lockNextSetTime.isAfter(currentTime)) lockNextSetTime - else currentTime.plusMinutes(homeInterval.toLong()) - nextSetTime?.let { - settingsDataStoreImpl.putString(SettingsConstants.LAST_SET_TIME, currentTime.format(formatter)) - settingsDataStoreImpl.putString(SettingsConstants.NEXT_SET_TIME, it.format(formatter)) - settingsDataStoreImpl.putString(SettingsConstants.HOME_NEXT_SET_TIME, homeNextSetTime.toString()) - settingsDataStoreImpl.putString(SettingsConstants.LOCK_NEXT_SET_TIME, lockNextSetTime.toString()) - } - } - val notification = createNotification(nextSetTime) - val notificationManager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager - notification?.let { notificationManager.notify(1, it) } } + + // Run notification + val formatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT) + val currentTime = LocalDateTime.now() + val homeNextSetTime: LocalDateTime = currentTime.plusMinutes(homeInterval.toLong()) + val lockNextSetTime: LocalDateTime = try { + LocalDateTime.parse(settingsDataStoreImpl.getString(SettingsConstants.LOCK_NEXT_SET_TIME)) + } catch (e: Exception) { + currentTime + } + val nextSetTime: LocalDateTime = when { + homeInterval == lockInterval -> homeNextSetTime + homeNextSetTime.isBefore(lockNextSetTime) && homeNextSetTime.isAfter(currentTime) -> homeNextSetTime + lockNextSetTime.isAfter(currentTime) -> lockNextSetTime + else -> homeNextSetTime + } + + nextSetTime.let { + settingsDataStoreImpl.putString(SettingsConstants.LAST_SET_TIME, currentTime.format(formatter)) + settingsDataStoreImpl.putString(SettingsConstants.NEXT_SET_TIME, it.format(formatter)) + settingsDataStoreImpl.putString(SettingsConstants.HOME_NEXT_SET_TIME, homeNextSetTime.toString()) + settingsDataStoreImpl.putString(SettingsConstants.LOCK_NEXT_SET_TIME, lockNextSetTime.toString()) + } + + val notification = createNotification(nextSetTime) + val notificationManager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager + notification?.let { notificationManager.notify(1, it) } } catch (e: Exception) { Log.e("PaperizeWallpaperChanger", "Error in changing wallpaper", e) - }*/ + } } /** * Updates the current wallpaper with current settings */ private suspend fun updateCurrentWallpaper(context: Context) { - /*try { - val selectedAlbum = selectedRepository.getSelectedAlbum().first() + try { + val selectedAlbum = albumRepository.getSelectedAlbums().first() if (selectedAlbum.isEmpty()) { onDestroy() return } - else { - val enableChanger = settingsDataStoreImpl.getBoolean(SettingsConstants.ENABLE_CHANGER) ?: false - val setHome = settingsDataStoreImpl.getBoolean(SettingsConstants.ENABLE_HOME_WALLPAPER) ?: false - val setLock = settingsDataStoreImpl.getBoolean(SettingsConstants.ENABLE_LOCK_WALLPAPER) ?: false - if (!enableChanger || (!setHome && !setLock)) { - onDestroy() - return - } - - val scaling = settingsDataStoreImpl.getString(SettingsConstants.WALLPAPER_SCALING)?.let { ScalingConstants.valueOf(it) } ?: ScalingConstants.FILL - val darken = settingsDataStoreImpl.getBoolean(SettingsConstants.DARKEN) ?: false - val homeDarkenPercentage = settingsDataStoreImpl.getInt(SettingsConstants.HOME_DARKEN_PERCENTAGE) ?: 100 - val blur = settingsDataStoreImpl.getBoolean(SettingsConstants.BLUR) ?: false - val homeBlurPercentage = settingsDataStoreImpl.getInt(SettingsConstants.HOME_BLUR_PERCENTAGE) ?: 0 - val currentHomeWallpaper = settingsDataStoreImpl.getString(SettingsConstants.CURRENT_HOME_WALLPAPER) ?: "" - val vignette = settingsDataStoreImpl.getBoolean(SettingsConstants.VIGNETTE) ?: false - val homeVignettePercentage = settingsDataStoreImpl.getInt(SettingsConstants.HOME_VIGNETTE_PERCENTAGE) ?: 0 - val grayscale = settingsDataStoreImpl.getBoolean(SettingsConstants.GRAYSCALE) ?: false - val homeGrayscalePercentage = settingsDataStoreImpl.getInt(SettingsConstants.HOME_GRAYSCALE_PERCENTAGE) ?: 0 - - setWallpaper( - context = context, - wallpaper = currentHomeWallpaper.toUri(), - darken = darken, - darkenPercent = homeDarkenPercentage, - scaling = scaling, - blur = blur, - blurPercent = homeBlurPercentage, - vignette = vignette, - vignettePercent = homeVignettePercentage, - grayscale = grayscale, - grayscalePercent = homeGrayscalePercentage - ) + val settings = getWallpaperSettings() + if (!settings.enableChanger || (!settings.setHome && !settings.setLock)) { + onDestroy() + return } + + val currentHomeWallpaper = settingsDataStoreImpl.getString(SettingsConstants.CURRENT_HOME_WALLPAPER) ?: "" + setWallpaper( + context = context, + wallpaper = currentHomeWallpaper.decompress("content://com.android.externalstorage.documents/").toUri(), + darken = settings.darken, + darkenPercent = settings.homeDarkenPercentage, + scaling = settings.scaling, + blur = settings.blur, + blurPercent = settings.homeBlurPercentage, + vignette = settings.vignette, + vignettePercent = settings.homeVignettePercentage, + grayscale = settings.grayscale, + grayscalePercent = settings.homeGrayscalePercentage + ) } catch (e: Exception) { Log.e("PaperizeWallpaperChanger", "Error in updating", e) - }*/ + } } /** @@ -560,7 +554,7 @@ class HomeWallpaperService: Service() { */ private fun setWallpaper( context: Context, - wallpaper: Uri, + wallpaper: Uri?, darken: Boolean, darkenPercent: Int, scaling: ScalingConstants, @@ -569,108 +563,133 @@ class HomeWallpaperService: Service() { vignette: Boolean, vignettePercent: Int, grayscale: Boolean, - grayscalePercent: Int + grayscalePercent: Int, + both: Boolean = false ): Boolean { - val wallpaperManager = WallpaperManager.getInstance(context) - try { - val size = getDeviceScreenSize(context) - val bitmap = retrieveBitmap(context, wallpaper, size.width, size.height) - if (bitmap == null) return false - else if (wallpaperManager.isSetWallpaperAllowed) { - processBitmap(size.width, size.height, bitmap, darken, darkenPercent, scaling, blur, blurPercent, vignette, vignettePercent, grayscale, grayscalePercent)?.let { image -> - wallpaperManager.setBitmap(image, null, true, WallpaperManager.FLAG_SYSTEM) - wallpaperManager.forgetLoadedWallpaper() - image.recycle() + wallpaper?.let { + try { + val wallpaperManager = WallpaperManager.getInstance(context) + val size = getDeviceScreenSize(context) + val bitmap = retrieveBitmap(context, wallpaper, size.width, size.height) + if (bitmap == null) return false + else if (wallpaperManager.isSetWallpaperAllowed) { + processBitmap(size.width, size.height, bitmap, darken, darkenPercent, scaling, blur, blurPercent, vignette, vignettePercent, grayscale, grayscalePercent)?.let { image -> + if (both) wallpaperManager.setBitmap(image, null, true, WallpaperManager.FLAG_LOCK) + wallpaperManager.setBitmap(image, null, true, WallpaperManager.FLAG_SYSTEM) + wallpaperManager.forgetLoadedWallpaper() + image.recycle() + } + bitmap.recycle() + context.triggerWallpaperTaskerEvent() + return true } - bitmap.recycle() - context.triggerWallpaperTaskerEvent() - return true + else return false + } catch (e: Exception) { + Log.e("PaperizeWallpaperChanger", "Error setting wallpaper", e) + return false } - else return false - } catch (e: IOException) { - Log.e("PaperizeWallpaperChanger", "Error setting wallpaper", e) - return false } + return false } /** * Refreshes the album by deleting invalid wallpapers and updating folder cover uri and wallpapers uri- */ private fun refreshAlbum(context: Context) { - /*CoroutineScope(Dispatchers.IO).launch { + CoroutineScope(Dispatchers.IO).launch { try { - var albumWithWallpapers = albumRepository.getAlbumsWithWallpaperAndFolder().first() - albumWithWallpapers.forEach { albumWithWallpaper -> - // Delete wallpaper if the URI is invalid - val invalidWallpapers = albumWithWallpaper.wallpapers.filterNot { wallpaper -> - val file = DocumentFileCompat.fromSingleUri(context, wallpaper.wallpaperUri.toUri()) - file?.exists() == true - } - if (invalidWallpapers.isNotEmpty()) { - albumRepository.deleteWallpaperList(invalidWallpapers) + val albumWithWallpapers = albumRepository.getAlbumsWithWallpaperAndFolder().first() + albumWithWallpapers.forEach { album -> + // Remove invalid wallpapers + val validWallpapers = async { + album.wallpapers + .asSequence() + .filter { isValidUri(context, it.wallpaperUri) } + .mapIndexed { index, wallpaper -> wallpaper.copy(order = index) } + .toList() } - // Update folder cover uri and wallpapers uri - albumWithWallpaper.folders.forEach { folder -> - try { - DocumentFileCompat.fromTreeUri(context, folder.folderUri.toUri())?.let { folderDirectory -> - if (!folderDirectory.isDirectory()) { - albumRepository.deleteFolder(folder) - } else { - val wallpapers = getWallpaperFromFolder(folder.folderUri, context) - val folderCoverFile = folder.coverUri?.let { DocumentFileCompat.fromSingleUri(context, it.toUri()) } - val folderCover = folderCoverFile?.takeIf { it.exists() }?.uri?.toString() ?: wallpapers.randomOrNull() - albumRepository.updateFolder(folder.copy(coverUri = folderCover, wallpapers = wallpapers)) - } - } - } catch (_: Exception) { - DocumentFile.fromTreeUri(context, folder.folderUri.toUri())?.let { folderDirectory -> - if (!folderDirectory.isDirectory) { - albumRepository.deleteFolder(folder) - } else { - val wallpapers = getWallpaperFromFolder(folder.folderUri, context) - val folderCoverFile = folder.coverUri?.let { DocumentFileCompat.fromSingleUri(context, it.toUri()) } - val folderCover = folderCoverFile?.takeIf { it.exists() }?.uri?.toString() ?: wallpapers.randomOrNull() - albumRepository.updateFolder(folder.copy(coverUri = folderCover, wallpapers = wallpapers)) - } - } - } - - } - - // Delete empty albums - if (albumWithWallpaper.wallpapers.isEmpty() && albumWithWallpaper.folders.all { it.wallpapers.isEmpty() }) { - albumRepository.deleteAlbum(albumWithWallpaper.album) - } - } - - // Update selected album - albumWithWallpapers = albumRepository.getAlbumsWithWallpaperAndFolder().first() - val selectedAlbum = selectedRepository.getSelectedAlbum().first().firstOrNull() - if (selectedAlbum != null) { - albumWithWallpapers.find { it.album.initialAlbumName == selectedAlbum.album.initialAlbumName } - ?.let { foundAlbum -> - val albumNameHashCode = foundAlbum.album.initialAlbumName.hashCode() - val wallpapers: List = - foundAlbum.wallpapers + foundAlbum.folders.flatMap { folder -> - folder.wallpapers.map { wallpaper -> - Wallpaper( - initialAlbumName = foundAlbum.album.initialAlbumName, - wallpaperUri = wallpaper, - key = wallpaper.hashCode() + albumNameHashCode, + // Remove invalid folders and inner wallpapers + val validFolders = async { + album.folders + .asSequence() + .filterNot { isDirectory(context, it.folderUri) } + .map { folder -> + async { + val metadata = getFolderMetadata(folder.folderUri, context) + if (metadata.lastModified != folder.dateModified) { + val existingWallpapers = folder.wallpapers + .asSequence() + .filter { isValidUri(context, it.wallpaperUri) } + .mapIndexed { index, wallpaper -> wallpaper.copy(order = index) } + .toList() + val newWallpapers = + getWallpaperFromFolder(folder.folderUri, context) + .asSequence() + .filterNot { new -> existingWallpapers.any { it.wallpaperUri == new.wallpaperUri } } + .mapIndexed { index, wallpaper -> + wallpaper.copy( + initialAlbumName = album.album.initialAlbumName, + order = existingWallpapers.size + 1 + index, + key = album.album.initialAlbumName.hashCode() + + folder.folderUri.hashCode() + + wallpaper.wallpaperUri.hashCode() + ) + }.toList() + val combinedWallpapers = existingWallpapers + newWallpapers + folder.copy( + coverUri = combinedWallpapers.firstOrNull()?.wallpaperUri ?: "", + wallpapers = combinedWallpapers, + dateModified = metadata.lastModified, + folderName = metadata.filename ) } + else { folder } } - val wallpapersUri = wallpapers.map { it.wallpaperUri }.toSet() - if (wallpapersUri.isEmpty()) { - selectedRepository.deleteAll() - onDestroy() } - } ?: run { onDestroy() } + .toList() + .awaitAll() + } + + val folders = validFolders.await() + val wallpapers = validWallpapers.await() + if (folders.isNotEmpty() || wallpapers.isNotEmpty()) { + val settings = getWallpaperSettings() + val coverUri = findFirstValidUri(context, folders, wallpapers) + val allValidWallpaperUri = (folders.flatMap { it.wallpapers } + wallpapers).sortedBy { it.order }.map{ it.wallpaperUri }.toSet() + val validatedHomeQueue = album.album.homeWallpapersInQueue.filter { allValidWallpaperUri.contains(it) } + val validatedLockQueue = album.album.lockWallpapersInQueue.filter { allValidWallpaperUri.contains(it) } + val newUris = allValidWallpaperUri - (validatedHomeQueue + validatedLockQueue).toSet() + val finalHomeQueue = if (settings.shuffle) { + validatedHomeQueue + newUris.shuffled() + } else { + allValidWallpaperUri.filter { it in validatedHomeQueue || it in newUris } + } + val finalLockQueue = if (settings.shuffle) { + validatedLockQueue + newUris.shuffled() + } else { + allValidWallpaperUri.filter { it in validatedLockQueue || it in newUris } + } + + albumRepository.upsertAlbumWithWallpaperAndFolder( + album.copy( + album = album.album.copy( + coverUri = coverUri, + homeWallpapersInQueue = finalHomeQueue, + lockWallpapersInQueue = finalLockQueue + ), + wallpapers = wallpapers, + folders = folders + ) + ) + } + else { + albumRepository.cascadeDeleteAlbum(album.album) + } } } catch (e: Exception) { Log.e("PaperizeWallpaperChanger", "Error refreshing album", e) } - }*/ + } } } \ No newline at end of file diff --git a/app/src/main/java/com/anthonyla/paperize/feature/wallpaper/wallpaper_service/LockWallpaperService.kt b/app/src/main/java/com/anthonyla/paperize/feature/wallpaper/wallpaper_service/LockWallpaperService.kt index 4ef5a48..799acd9 100644 --- a/app/src/main/java/com/anthonyla/paperize/feature/wallpaper/wallpaper_service/LockWallpaperService.kt +++ b/app/src/main/java/com/anthonyla/paperize/feature/wallpaper/wallpaper_service/LockWallpaperService.kt @@ -1,6 +1,6 @@ package com.anthonyla.paperize.feature.wallpaper.wallpaper_service -import android.app.Notification +import android.app.NotificationManager import android.app.PendingIntent import android.app.Service import android.app.WallpaperManager @@ -12,21 +12,28 @@ import android.os.HandlerThread import android.os.IBinder import android.util.Log import androidx.core.app.NotificationCompat +import androidx.core.net.toUri import com.anthonyla.paperize.R import com.anthonyla.paperize.core.ScalingConstants import com.anthonyla.paperize.core.SettingsConstants import com.anthonyla.paperize.core.Type +import com.anthonyla.paperize.core.decompress import com.anthonyla.paperize.core.getDeviceScreenSize +import com.anthonyla.paperize.core.isValidUri import com.anthonyla.paperize.core.processBitmap import com.anthonyla.paperize.core.retrieveBitmap import com.anthonyla.paperize.data.settings.SettingsDataStore import com.anthonyla.paperize.feature.wallpaper.domain.repository.AlbumRepository import com.anthonyla.paperize.feature.wallpaper.presentation.MainActivity +import com.anthonyla.paperize.feature.wallpaper.presentation.settings_screen.SettingsState import com.anthonyla.paperize.feature.wallpaper.tasker_shortcut.triggerWallpaperTaskerEvent +import com.anthonyla.paperize.feature.wallpaper.util.navigation.Notification import com.anthonyla.paperize.feature.wallpaper.wallpaper_alarmmanager.WallpaperBootAndChangeReceiver import dagger.hilt.android.AndroidEntryPoint import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.delay +import kotlinx.coroutines.flow.first import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import java.io.IOException @@ -51,8 +58,7 @@ class LockWallpaperService: Service() { enum class Actions { START, - UPDATE, - REFRESH + UPDATE } override fun onBind(p0: Intent?): IBinder? { @@ -69,7 +75,6 @@ class LockWallpaperService: Service() { if (intent != null) { when (intent.action) { Actions.START.toString() -> { - Log.d("PaperizeWallpaperChanger", "Starting lock start wallpaper service") homeInterval = intent.getIntExtra("homeInterval", SettingsConstants.WALLPAPER_CHANGE_INTERVAL_DEFAULT) lockInterval = intent.getIntExtra("lockInterval", SettingsConstants.WALLPAPER_CHANGE_INTERVAL_DEFAULT) scheduleSeparately = intent.getBooleanExtra("scheduleSeparately", false) @@ -77,13 +82,8 @@ class LockWallpaperService: Service() { workerTaskStart() } Actions.UPDATE.toString() -> { - Log.d("PaperizeWallpaperChanger", "Starting lock update wallpaper service") workerTaskUpdate() } - Actions.REFRESH.toString() -> { - Log.d("PaperizeWallpaperChanger", "Starting lock refresh wallpaper service") - workerTaskRefresh() - } } } return START_NOT_STICKY @@ -117,277 +117,222 @@ class LockWallpaperService: Service() { } } - private fun workerTaskRefresh() { - workerHandler.post { - CoroutineScope(Dispatchers.Default).launch { - refreshAlbum(this@LockWallpaperService) - withContext(Dispatchers.Main) { - stopSelf() - } - } - } - } + // Creates a notification for the wallpaper service + private fun createNotification(nextSetTime: LocalDateTime?): android.app.Notification? { + nextSetTime?.let { + val changeWallpaperIntent = Intent(this, WallpaperBootAndChangeReceiver::class.java) + val pendingChangeWallpaperIntent = PendingIntent.getBroadcast( + this, + 0, + changeWallpaperIntent, + PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT + ) + val mainActivityIntent = Intent(this, MainActivity::class.java) + val pendingMainActivityIntent = PendingIntent.getActivity( + this, + 3, + mainActivityIntent, + PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT + ) - /** - * Creates a notification for the wallpaper service - */ - private fun createNotification(nextSetTime: LocalDateTime?): Notification? { - val changeWallpaperIntent = Intent(this, WallpaperBootAndChangeReceiver::class.java) - val pendingChangeWallpaperIntent = PendingIntent.getBroadcast(this, 0, changeWallpaperIntent, PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT) - val formatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT) - if (nextSetTime != null) { - val intent = Intent(this, MainActivity::class.java) - val pendingIntent = PendingIntent.getActivity(this, 3, intent, PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT) - return NotificationCompat.Builder(this, "wallpaper_service_channel") - .setContentTitle(getString(R.string.app_name)) - .setContentText(getString(R.string.next_wallpaper_change, nextSetTime.format(formatter))) - .setSmallIcon(R.drawable.notification_icon) - .setContentIntent(pendingIntent) - .addAction(R.drawable.notification_icon, getString(R.string.change_wallpaper), pendingChangeWallpaperIntent) - .build() + val formatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT) + val formattedNextSetTime = nextSetTime.format(formatter) + + // Build the notification + return NotificationCompat.Builder(this, "wallpaper_service_channel").apply { + setContentTitle(getString(R.string.app_name)) + setContentText(getString(R.string.next_wallpaper_change, formattedNextSetTime)) + setSmallIcon(R.drawable.notification_icon) + setContentIntent(pendingMainActivityIntent) + addAction(R.drawable.notification_icon, getString(R.string.change_wallpaper), pendingChangeWallpaperIntent) + priority = NotificationCompat.PRIORITY_DEFAULT + setAutoCancel(true) + }.build() } return null } + + private suspend fun getWallpaperSettings(): SettingsState.ServiceSettings { + return SettingsState.ServiceSettings( + enableChanger = settingsDataStoreImpl.getBoolean(SettingsConstants.ENABLE_CHANGER) ?: false, + setHome = settingsDataStoreImpl.getBoolean(SettingsConstants.ENABLE_HOME_WALLPAPER) ?: false, + setLock = settingsDataStoreImpl.getBoolean(SettingsConstants.ENABLE_LOCK_WALLPAPER) ?: false, + scaling = settingsDataStoreImpl.getString(SettingsConstants.WALLPAPER_SCALING)?.let { ScalingConstants.valueOf(it) } ?: ScalingConstants.FILL, + darken = settingsDataStoreImpl.getBoolean(SettingsConstants.DARKEN) ?: false, + homeDarkenPercentage = settingsDataStoreImpl.getInt(SettingsConstants.HOME_DARKEN_PERCENTAGE) ?: 100, + lockDarkenPercentage = settingsDataStoreImpl.getInt(SettingsConstants.LOCK_DARKEN_PERCENTAGE) ?: 100, + blur = settingsDataStoreImpl.getBoolean(SettingsConstants.BLUR) ?: false, + homeBlurPercentage = settingsDataStoreImpl.getInt(SettingsConstants.HOME_BLUR_PERCENTAGE) ?: 0, + lockBlurPercentage = settingsDataStoreImpl.getInt(SettingsConstants.LOCK_BLUR_PERCENTAGE) ?: 0, + vignette = settingsDataStoreImpl.getBoolean(SettingsConstants.VIGNETTE) ?: false, + homeVignettePercentage = settingsDataStoreImpl.getInt(SettingsConstants.HOME_VIGNETTE_PERCENTAGE) ?: 0, + lockVignettePercentage = settingsDataStoreImpl.getInt(SettingsConstants.LOCK_VIGNETTE_PERCENTAGE) ?: 0, + grayscale = settingsDataStoreImpl.getBoolean(SettingsConstants.GRAYSCALE) ?: false, + homeGrayscalePercentage = settingsDataStoreImpl.getInt(SettingsConstants.HOME_GRAYSCALE_PERCENTAGE) ?: 0, + lockGrayscalePercentage = settingsDataStoreImpl.getInt(SettingsConstants.LOCK_GRAYSCALE_PERCENTAGE) ?: 0, + lockAlbumName = settingsDataStoreImpl.getString(SettingsConstants.LOCK_ALBUM_NAME) ?: "", + homeAlbumName = settingsDataStoreImpl.getString(SettingsConstants.HOME_ALBUM_NAME) ?: "", + shuffle = settingsDataStoreImpl.getBoolean(SettingsConstants.SHUFFLE) ?: true + ) + } + /** * Changes the wallpaper to the next wallpaper in the queue of the selected album * If none left, reshuffle the wallpapers and pick the first one */ private suspend fun changeWallpaper(context: Context) { - /*try { - val selectedAlbum = selectedRepository.getSelectedAlbum().first() + try { + val selectedAlbum = albumRepository.getSelectedAlbums().first() if (selectedAlbum.isEmpty()) { onDestroy() return } - else { - val setHome = settingsDataStoreImpl.getBoolean(SettingsConstants.ENABLE_HOME_WALLPAPER) ?: false - val setLock = settingsDataStoreImpl.getBoolean(SettingsConstants.ENABLE_LOCK_WALLPAPER) ?: false - if (!setHome && !setLock) { - onDestroy() - return - } - val scaling = settingsDataStoreImpl.getString(SettingsConstants.WALLPAPER_SCALING)?.let { ScalingConstants.valueOf(it) } ?: ScalingConstants.FILL - val darken = settingsDataStoreImpl.getBoolean(SettingsConstants.DARKEN) ?: false - val homeDarkenPercentage = settingsDataStoreImpl.getInt(SettingsConstants.HOME_DARKEN_PERCENTAGE) ?: 100 - val lockDarkenPercentage = settingsDataStoreImpl.getInt(SettingsConstants.LOCK_DARKEN_PERCENTAGE) ?: 100 - val blur = settingsDataStoreImpl.getBoolean(SettingsConstants.BLUR) ?: false - val homeBlurPercentage = settingsDataStoreImpl.getInt(SettingsConstants.HOME_BLUR_PERCENTAGE) ?: 0 - val lockBlurPercentage = settingsDataStoreImpl.getInt(SettingsConstants.LOCK_BLUR_PERCENTAGE) ?: 0 - val vignette = settingsDataStoreImpl.getBoolean(SettingsConstants.VIGNETTE) ?: false - val homeVignettePercentage = settingsDataStoreImpl.getInt(SettingsConstants.HOME_VIGNETTE_PERCENTAGE) ?: 0 - val lockVignettePercentage = settingsDataStoreImpl.getInt(SettingsConstants.LOCK_VIGNETTE_PERCENTAGE) ?: 0 - val grayscale = settingsDataStoreImpl.getBoolean(SettingsConstants.GRAYSCALE) ?: false - val homeGrayscalePercentage = settingsDataStoreImpl.getInt(SettingsConstants.HOME_GRAYSCALE_PERCENTAGE) ?: 0 - val lockGrayscalePercentage = settingsDataStoreImpl.getInt(SettingsConstants.LOCK_GRAYSCALE_PERCENTAGE) ?: 0 - val lockAlbumName = settingsDataStoreImpl.getString(SettingsConstants.LOCK_ALBUM_NAME) ?: "" - val lockAlbum = selectedAlbum.find { it.album.initialAlbumName == lockAlbumName } - if (lockAlbum == null) { - onDestroy() - return - } - when { - // Case: Set home and lock screen wallpapers using separate albums (home screen and lock screen album) - setHome && setLock && scheduleSeparately -> { - var wallpaper = lockAlbum.album.lockWallpapersInQueue.firstOrNull() + val settings = getWallpaperSettings() + if (!settings.setHome && !settings.setLock) { + onDestroy() + return + } + val lockAlbum = selectedAlbum.find { it.album.initialAlbumName == settings.lockAlbumName } + val homeAlbum = selectedAlbum.find { it.album.initialAlbumName == settings.homeAlbumName } + if (lockAlbum == null || homeAlbum == null) { + onDestroy() + return + } + when { + // Case: Set home and lock screen wallpapers using separate albums (home screen and lock screen album) + settings.setHome && settings.setLock && scheduleSeparately -> { + var wallpaper = lockAlbum.album.lockWallpapersInQueue.firstOrNull() + if (wallpaper == null) { + val newWallpapers = if (settings.shuffle) lockAlbum.totalWallpapers.map { it.wallpaperUri }.shuffled() + else lockAlbum.totalWallpapers.map { it.wallpaperUri } + wallpaper = newWallpapers.firstOrNull() if (wallpaper == null) { - val newWallpapers = lockAlbum.wallpapers.map { it.wallpaperUri }.shuffled() - wallpaper = newWallpapers.firstOrNull() - if (wallpaper == null) { - selectedRepository.cascadeDeleteAlbum(lockAlbum.album.initialAlbumName) - onDestroy() - return - } - else { - val success = isValidUri(context, wallpaper) - settingsDataStoreImpl.putString(SettingsConstants.NEXT_LOCK_WALLPAPER, if (newWallpapers.size > 1) newWallpapers[1] else lockAlbum.wallpapers.firstOrNull()?.wallpaperUri ?: "") - if (success) { - selectedRepository.upsertSelectedAlbum(lockAlbum.copy(album = lockAlbum.album.copy(lockWallpapersInQueue = newWallpapers.drop(1)))) - settingsDataStoreImpl.putString(SettingsConstants.CURRENT_LOCK_WALLPAPER, wallpaper.toString()) - setWallpaper( - context = context, - wallpaper = wallpaper.toUri(), - darken = darken, - darkenPercent = lockDarkenPercentage, - scaling = scaling, - blur = blur, - blurPercent = lockBlurPercentage, - vignette = vignette, - vignettePercent = lockVignettePercentage, - grayscale = grayscale, - grayscalePercent = lockGrayscalePercentage - ) - } - else { - val wallpaperToDelete = lockAlbum.wallpapers.find { it.wallpaperUri == wallpaper } - if (wallpaperToDelete != null) { - albumRepository.deleteWallpaper(wallpaperToDelete) - selectedRepository.deleteWallpaper(wallpaperToDelete) - selectedRepository.upsertSelectedAlbum( - lockAlbum.copy( - album = lockAlbum.album.copy( - lockWallpapersInQueue = lockAlbum.album.lockWallpapersInQueue.filterNot { it == wallpaper } - ), - wallpapers = lockAlbum.wallpapers.filterNot { it.wallpaperUri == wallpaper } - ) - ) - } - } - } - } - else { - val success = isValidUri(context, wallpaper) - settingsDataStoreImpl.putString(SettingsConstants.NEXT_LOCK_WALLPAPER, if (lockAlbum.album.lockWallpapersInQueue.size > 1) lockAlbum.album.lockWallpapersInQueue[1] else lockAlbum.wallpapers.firstOrNull()?.wallpaperUri ?: "") - if (success) { - selectedRepository.upsertSelectedAlbum(lockAlbum.copy(album = lockAlbum.album.copy(lockWallpapersInQueue = lockAlbum.album.lockWallpapersInQueue.drop(1)))) - settingsDataStoreImpl.putString(SettingsConstants.CURRENT_LOCK_WALLPAPER, wallpaper.toString()) - setWallpaper( - context = context, - wallpaper = wallpaper.toUri(), - darken = darken, - darkenPercent = lockDarkenPercentage, - scaling = scaling, - blur = blur, - blurPercent = lockBlurPercentage, - vignette = vignette, - vignettePercent = lockVignettePercentage, - grayscale = grayscale, - grayscalePercent = lockGrayscalePercentage - ) - } - else { - val wallpaperToDelete = lockAlbum.wallpapers.find { it.wallpaperUri == wallpaper } - if (wallpaperToDelete != null) { - albumRepository.deleteWallpaper(wallpaperToDelete) - selectedRepository.deleteWallpaper(wallpaperToDelete) - selectedRepository.upsertSelectedAlbum( - lockAlbum.copy( - album = lockAlbum.album.copy( - lockWallpapersInQueue = lockAlbum.album.lockWallpapersInQueue.filterNot { it == wallpaper } - ), - wallpapers = lockAlbum.wallpapers.filterNot { it.wallpaperUri == wallpaper } - ) - ) - } - } - } - if (homeInterval != lockInterval) { - delay(15000) - val serviceIntent = Intent(context, HomeWallpaperService::class.java).apply { this.action = HomeWallpaperService.Actions.UPDATE.toString() } - context.startService(serviceIntent) - } - } - // Case: Set home and lock screen wallpapers using the same album (home screen album) - setHome && setLock && !scheduleSeparately -> { - val homeAlbumName = settingsDataStoreImpl.getString(SettingsConstants.HOME_ALBUM_NAME) ?: "" - val homeAlbum = selectedAlbum.find { it.album.initialAlbumName == homeAlbumName } - if (homeAlbum == null) { + albumRepository.cascadeDeleteAlbum(lockAlbum.album) onDestroy() return } - val wallpaper = homeAlbum.album.homeWallpapersInQueue.firstOrNull() - if (wallpaper != null) { - val success = isValidUri(context, wallpaper) - settingsDataStoreImpl.putString(SettingsConstants.NEXT_LOCK_WALLPAPER, if (homeAlbum.album.homeWallpapersInQueue.size > 1) homeAlbum.album.homeWallpapersInQueue[1] else homeAlbum.wallpapers.firstOrNull()?.wallpaperUri ?: "") - if (success) { - settingsDataStoreImpl.putString(SettingsConstants.CURRENT_LOCK_WALLPAPER, wallpaper.toString()) - setWallpaper( - context = context, - wallpaper = wallpaper.toUri(), - darken = darken, - darkenPercent = lockDarkenPercentage, - scaling = scaling, - blur = blur, - blurPercent = lockBlurPercentage, - vignette = vignette, - vignettePercent = lockVignettePercentage, - grayscale = grayscale, - grayscalePercent = lockGrayscalePercentage - ) - } - } - } - // Case: Set lock screen wallpaper (lock screen album) - setLock -> { - var wallpaper = lockAlbum.album.lockWallpapersInQueue.firstOrNull() - if (wallpaper == null) { - val newWallpapers = lockAlbum.wallpapers.map { it.wallpaperUri }.shuffled() - wallpaper = newWallpapers.firstOrNull() - if (wallpaper == null) { - selectedRepository.cascadeDeleteAlbum(lockAlbum.album.initialAlbumName) - onDestroy() - return - } - else { - val success = isValidUri(context, wallpaper) - settingsDataStoreImpl.putString(SettingsConstants.NEXT_LOCK_WALLPAPER, if (newWallpapers.size > 1) newWallpapers[1] else lockAlbum.wallpapers.firstOrNull()?.wallpaperUri ?: "") - settingsDataStoreImpl.putString(SettingsConstants.NEXT_HOME_WALLPAPER, if (newWallpapers.size > 1) newWallpapers[1] else lockAlbum.wallpapers.firstOrNull()?.wallpaperUri ?: "") - if (success) { - selectedRepository.upsertSelectedAlbum(lockAlbum.copy(album = lockAlbum.album.copy(lockWallpapersInQueue = newWallpapers.drop(1)))) - settingsDataStoreImpl.putString(SettingsConstants.CURRENT_LOCK_WALLPAPER, wallpaper.toString()) - settingsDataStoreImpl.putString(SettingsConstants.CURRENT_HOME_WALLPAPER, wallpaper.toString()) - setWallpaper( - context = context, - wallpaper = wallpaper.toUri(), - darken = darken, - darkenPercent = homeDarkenPercentage, - scaling = scaling, - blur = blur, - blurPercent = homeBlurPercentage, - vignette = vignette, - vignettePercent = homeVignettePercentage, - grayscale = grayscale, - grayscalePercent = homeGrayscalePercentage - ) - } - else { - val wallpaperToDelete = lockAlbum.wallpapers.find { it.wallpaperUri == wallpaper } - if (wallpaperToDelete != null) { - albumRepository.deleteWallpaper(wallpaperToDelete) - selectedRepository.deleteWallpaper(wallpaperToDelete) - selectedRepository.upsertSelectedAlbum( - lockAlbum.copy( - album = lockAlbum.album.copy( - lockWallpapersInQueue = lockAlbum.album.lockWallpapersInQueue.filterNot { it == wallpaper } - ), - wallpapers = lockAlbum.wallpapers.filterNot { it.wallpaperUri == wallpaper } - ) - ) - } - } - } - } else { val success = isValidUri(context, wallpaper) - settingsDataStoreImpl.putString(SettingsConstants.NEXT_LOCK_WALLPAPER, if (lockAlbum.album.lockWallpapersInQueue.size > 1) lockAlbum.album.lockWallpapersInQueue[1] else lockAlbum.wallpapers.firstOrNull()?.wallpaperUri ?: "") - settingsDataStoreImpl.putString(SettingsConstants.NEXT_HOME_WALLPAPER, if (lockAlbum.album.lockWallpapersInQueue.size > 1) lockAlbum.album.lockWallpapersInQueue[1] else lockAlbum.wallpapers.firstOrNull()?.wallpaperUri ?: "") if (success) { - selectedRepository.upsertSelectedAlbum(lockAlbum.copy(album = lockAlbum.album.copy(lockWallpapersInQueue = lockAlbum.album.lockWallpapersInQueue.drop(1)))) settingsDataStoreImpl.putString(SettingsConstants.CURRENT_LOCK_WALLPAPER, wallpaper.toString()) - settingsDataStoreImpl.putString(SettingsConstants.CURRENT_HOME_WALLPAPER, wallpaper.toString()) + albumRepository.upsertAlbum(lockAlbum.album.copy(lockWallpapersInQueue = newWallpapers.drop(1))) setWallpaper( context = context, - wallpaper = wallpaper.toUri(), - darken = darken, - darkenPercent = homeDarkenPercentage, - scaling = scaling, - blur = blur, - blurPercent = homeBlurPercentage, - vignette = vignette, - vignettePercent = homeVignettePercentage, - grayscale = grayscale, - grayscalePercent = homeGrayscalePercentage + wallpaper = wallpaper.decompress("content://com.android.externalstorage.documents/").toUri(), + darken = settings.darken, + darkenPercent = settings.lockDarkenPercentage, + scaling = settings.scaling, + blur = settings.blur, + blurPercent = settings.lockBlurPercentage, + vignette = settings.vignette, + vignettePercent = settings.lockVignettePercentage, + grayscale = settings.grayscale, + grayscalePercent = settings.lockGrayscalePercentage ) } else { val wallpaperToDelete = lockAlbum.wallpapers.find { it.wallpaperUri == wallpaper } if (wallpaperToDelete != null) { albumRepository.deleteWallpaper(wallpaperToDelete) - selectedRepository.deleteWallpaper(wallpaperToDelete) - selectedRepository.upsertSelectedAlbum( + albumRepository.upsertAlbumWithWallpaperAndFolder( + lockAlbum.copy( + wallpapers = lockAlbum.wallpapers.filterNot { it.wallpaperUri == wallpaper }, + album = lockAlbum.album.copy( + lockWallpapersInQueue = lockAlbum.album.lockWallpapersInQueue.filterNot { it == wallpaper }, + homeWallpapersInQueue = lockAlbum.album.homeWallpapersInQueue.filterNot { it == wallpaper } + ) + ) + ) + } + } + } + } + else { + val success = isValidUri(context, wallpaper) + if (success) { + settingsDataStoreImpl.putString(SettingsConstants.CURRENT_LOCK_WALLPAPER, wallpaper.toString()) + albumRepository.upsertAlbum(lockAlbum.album.copy(lockWallpapersInQueue = lockAlbum.album.lockWallpapersInQueue.drop(1))) + setWallpaper( + context = context, + wallpaper = wallpaper.decompress("content://com.android.externalstorage.documents/").toUri(), + darken = settings.darken, + darkenPercent = settings.lockDarkenPercentage, + scaling = settings.scaling, + blur = settings.blur, + blurPercent = settings.lockBlurPercentage, + vignette = settings.vignette, + vignettePercent = settings.lockVignettePercentage, + grayscale = settings.grayscale, + grayscalePercent = settings.lockGrayscalePercentage + ) + } + else { + val wallpaperToDelete = lockAlbum.wallpapers.find { it.wallpaperUri == wallpaper } + if (wallpaperToDelete != null) { + albumRepository.deleteWallpaper(wallpaperToDelete) + albumRepository.upsertAlbumWithWallpaperAndFolder( + lockAlbum.copy( + album = lockAlbum.album.copy( + lockWallpapersInQueue = lockAlbum.album.lockWallpapersInQueue.filterNot { it == wallpaper }, + homeWallpapersInQueue = lockAlbum.album.homeWallpapersInQueue.filterNot { it == wallpaper } + ), + wallpapers = lockAlbum.wallpapers.filterNot { it.wallpaperUri == wallpaper } + ) + ) + } + } + } + // Refreshing home wallpaper to keep dynamic theming color based on home screen wallpaper + if (homeInterval != lockInterval) { + delay(15000) + val serviceIntent = Intent(context, HomeWallpaperService::class.java).apply { this.action = HomeWallpaperService.Actions.UPDATE.toString() } + context.startService(serviceIntent) + } + } + // Case: Set home and lock screen wallpapers using the same album (home screen album) + settings.setHome && settings.setLock && !scheduleSeparately -> { /* handled by home wallpaper service */ return } + // Case: Set lock screen wallpaper (lock screen album) + settings.setLock -> { + var wallpaper = lockAlbum.album.lockWallpapersInQueue.firstOrNull() + if (wallpaper == null) { + val newWallpapers = if (settings.shuffle) lockAlbum.totalWallpapers.map { it.wallpaperUri }.shuffled() + else lockAlbum.totalWallpapers.map { it.wallpaperUri } + wallpaper = newWallpapers.firstOrNull() + if (wallpaper == null) { + albumRepository.cascadeDeleteAlbum(lockAlbum.album) + onDestroy() + return + } + else { + val success = isValidUri(context, wallpaper) + if (success) { + settingsDataStoreImpl.putString(SettingsConstants.CURRENT_LOCK_WALLPAPER, wallpaper.toString()) + settingsDataStoreImpl.putString(SettingsConstants.CURRENT_HOME_WALLPAPER, wallpaper.toString()) + albumRepository.upsertAlbum(lockAlbum.album.copy(lockWallpapersInQueue = newWallpapers.drop(1))) + setWallpaper( + context = context, + wallpaper = wallpaper.decompress("content://com.android.externalstorage.documents/").toUri(), + darken = settings.darken, + darkenPercent = settings.homeDarkenPercentage, + scaling = settings.scaling, + blur = settings.blur, + blurPercent = settings.homeBlurPercentage, + vignette = settings.vignette, + vignettePercent = settings.homeVignettePercentage, + grayscale = settings.grayscale, + grayscalePercent = settings.homeGrayscalePercentage + ) + } + else { + val wallpaperToDelete = lockAlbum.wallpapers.find { it.wallpaperUri == wallpaper } + if (wallpaperToDelete != null) { + albumRepository.deleteWallpaper(wallpaperToDelete) + albumRepository.upsertAlbumWithWallpaperAndFolder( lockAlbum.copy( album = lockAlbum.album.copy( - lockWallpapersInQueue = lockAlbum.album.lockWallpapersInQueue.filterNot { it == wallpaper } + lockWallpapersInQueue = lockAlbum.album.lockWallpapersInQueue.filterNot { it == wallpaper }, + homeWallpapersInQueue = lockAlbum.album.homeWallpapersInQueue.filterNot { it == wallpaper } ), wallpapers = lockAlbum.wallpapers.filterNot { it.wallpaperUri == wallpaper } ) @@ -396,89 +341,108 @@ class LockWallpaperService: Service() { } } } - } - // Run notification - if (homeInterval != lockInterval || setLock && !setHome) { - val formatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT) - val homeNextSetTime = try { - LocalDateTime.parse(settingsDataStoreImpl.getString(SettingsConstants.HOME_NEXT_SET_TIME)) - } catch (_: Exception) { - LocalDateTime.now() + else { + val success = isValidUri(context, wallpaper) + if (success) { + settingsDataStoreImpl.putString(SettingsConstants.CURRENT_LOCK_WALLPAPER, wallpaper.toString()) + settingsDataStoreImpl.putString(SettingsConstants.CURRENT_HOME_WALLPAPER, wallpaper.toString()) + albumRepository.upsertAlbum(lockAlbum.album.copy(lockWallpapersInQueue = lockAlbum.album.lockWallpapersInQueue.drop(1))) + setWallpaper( + context = context, + wallpaper = wallpaper.decompress("content://com.android.externalstorage.documents/").toUri(), + darken = settings.darken, + darkenPercent = settings.homeDarkenPercentage, + scaling = settings.scaling, + blur = settings.blur, + blurPercent = settings.homeBlurPercentage, + vignette = settings.vignette, + vignettePercent = settings.homeVignettePercentage, + grayscale = settings.grayscale, + grayscalePercent = settings.homeGrayscalePercentage + ) + } else { + val wallpaperToDelete = lockAlbum.wallpapers.find { it.wallpaperUri == wallpaper } + if (wallpaperToDelete != null) { + albumRepository.deleteWallpaper(wallpaperToDelete) + albumRepository.upsertAlbumWithWallpaperAndFolder( + lockAlbum.copy( + album = lockAlbum.album.copy( + lockWallpapersInQueue = lockAlbum.album.lockWallpapersInQueue.filterNot { it == wallpaper }, + homeWallpapersInQueue = lockAlbum.album.homeWallpapersInQueue.filterNot { it == wallpaper } + ), + wallpapers = lockAlbum.wallpapers.filterNot { it.wallpaperUri == wallpaper } + ) + ) + + } + } } - val lockNextSetTime: LocalDateTime? - val nextSetTime: LocalDateTime? - val currentTime = LocalDateTime.now() - lockNextSetTime = currentTime.plusMinutes(lockInterval.toLong()) - nextSetTime = if (lockNextSetTime.isBefore(homeNextSetTime) && lockNextSetTime.isAfter(currentTime)) lockNextSetTime - else if (homeNextSetTime.isAfter(currentTime)) homeNextSetTime - else currentTime.plusMinutes(lockInterval.toLong()) - nextSetTime?.let { - settingsDataStoreImpl.putString(SettingsConstants.LAST_SET_TIME, currentTime.format(formatter)) - settingsDataStoreImpl.putString(SettingsConstants.NEXT_SET_TIME, it.format(formatter)) - settingsDataStoreImpl.putString(SettingsConstants.HOME_NEXT_SET_TIME, homeNextSetTime.toString()) - settingsDataStoreImpl.putString(SettingsConstants.LOCK_NEXT_SET_TIME, lockNextSetTime.toString()) - } - val notification = createNotification(nextSetTime) - val notificationManager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager - notification?.let { notificationManager.notify(1, it) } } } + + // Run notification + if (homeInterval != lockInterval || (settings.setLock && !settings.setHome)) { + val formatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT) + val homeNextSetTime = try { + LocalDateTime.parse(settingsDataStoreImpl.getString(SettingsConstants.HOME_NEXT_SET_TIME)) + } catch (_: Exception) { + LocalDateTime.now() + } + val currentTime = LocalDateTime.now() + val lockNextSetTime = currentTime.plusMinutes(lockInterval.toLong()) + val nextSetTime = when { + lockNextSetTime.isBefore(homeNextSetTime) && lockNextSetTime.isAfter(currentTime) -> lockNextSetTime + homeNextSetTime.isAfter(currentTime) -> homeNextSetTime + else -> lockNextSetTime + } + nextSetTime?.let { + settingsDataStoreImpl.putString(SettingsConstants.LAST_SET_TIME, currentTime.format(formatter)) + settingsDataStoreImpl.putString(SettingsConstants.NEXT_SET_TIME, it.format(formatter)) + settingsDataStoreImpl.putString(SettingsConstants.LOCK_NEXT_SET_TIME, lockNextSetTime.toString()) + settingsDataStoreImpl.putString(SettingsConstants.HOME_NEXT_SET_TIME, homeNextSetTime.toString()) + } + val notification = createNotification(nextSetTime) + val notificationManager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager + notification?.let { notificationManager.notify(1, it) } + } } catch (e: Exception) { Log.e("PaperizeWallpaperChanger", "Error in changing wallpaper", e) - }*/ + } } /** * Updates the current wallpaper with current settings */ private suspend fun updateCurrentWallpaper(context: Context) { - /*try { - val selectedAlbum = selectedRepository.getSelectedAlbum().first() + try { + val selectedAlbum = albumRepository.getSelectedAlbums().first() if (selectedAlbum.isEmpty()) { onDestroy() return } - else { - val enableChanger = settingsDataStoreImpl.getBoolean(SettingsConstants.ENABLE_CHANGER) ?: false - val setHome = settingsDataStoreImpl.getBoolean(SettingsConstants.ENABLE_HOME_WALLPAPER) ?: false - val setLock = settingsDataStoreImpl.getBoolean(SettingsConstants.ENABLE_LOCK_WALLPAPER) ?: false - if (!enableChanger || (!setHome && !setLock)) { - onDestroy() - return - } - - val scaling = settingsDataStoreImpl.getString(SettingsConstants.WALLPAPER_SCALING)?.let { ScalingConstants.valueOf(it) } ?: ScalingConstants.FILL - val darken = settingsDataStoreImpl.getBoolean(SettingsConstants.DARKEN) ?: false - val homeDarkenPercentage = settingsDataStoreImpl.getInt(SettingsConstants.HOME_DARKEN_PERCENTAGE) ?: 100 - val lockDarkenPercentage = settingsDataStoreImpl.getInt(SettingsConstants.LOCK_DARKEN_PERCENTAGE) ?: 100 - val blur = settingsDataStoreImpl.getBoolean(SettingsConstants.BLUR) ?: false - val homeBlurPercentage = settingsDataStoreImpl.getInt(SettingsConstants.HOME_BLUR_PERCENTAGE) ?: 0 - val lockBlurPercentage = settingsDataStoreImpl.getInt(SettingsConstants.LOCK_BLUR_PERCENTAGE) ?: 0 - val vignette = settingsDataStoreImpl.getBoolean(SettingsConstants.VIGNETTE) ?: false - val homeVignettePercentage = settingsDataStoreImpl.getInt(SettingsConstants.HOME_VIGNETTE_PERCENTAGE) ?: 0 - val lockVignettePercentage = settingsDataStoreImpl.getInt(SettingsConstants.LOCK_VIGNETTE_PERCENTAGE) ?: 0 - val grayscale = settingsDataStoreImpl.getBoolean(SettingsConstants.GRAYSCALE) ?: false - val homeGrayscalePercentage = settingsDataStoreImpl.getInt(SettingsConstants.HOME_GRAYSCALE_PERCENTAGE) ?: 0 - val lockGrayscalePercentage = settingsDataStoreImpl.getInt(SettingsConstants.LOCK_GRAYSCALE_PERCENTAGE) ?: 0 - val currentLockWallpaper = settingsDataStoreImpl.getString(SettingsConstants.CURRENT_LOCK_WALLPAPER) ?: "" - - setWallpaper( - context = context, - wallpaper = currentLockWallpaper.toUri(), - darken = darken, - darkenPercent = if (!setHome) homeDarkenPercentage else lockDarkenPercentage, - scaling = scaling, - blur = blur, - blurPercent = if (!setHome) homeBlurPercentage else lockBlurPercentage, - vignette = vignette, - vignettePercent = if (!setHome) homeVignettePercentage else lockVignettePercentage, - grayscale = grayscale, - grayscalePercent = if (!setHome) homeGrayscalePercentage else lockGrayscalePercentage - ) + val settings = getWallpaperSettings() + if (!settings.enableChanger || (!settings.setHome && !settings.setLock)) { + onDestroy() + return } + + val currentLockWallpaper = settingsDataStoreImpl.getString(SettingsConstants.CURRENT_LOCK_WALLPAPER) ?: "" + setWallpaper( + context = context, + wallpaper = currentLockWallpaper.decompress("content://com.android.externalstorage.documents/").toUri(), + darken = settings.darken, + darkenPercent = if (!settings.setHome) settings.homeDarkenPercentage else settings.lockDarkenPercentage, + scaling = settings.scaling, + blur = settings.blur, + blurPercent = if (!settings.setHome) settings.homeBlurPercentage else settings.lockBlurPercentage, + vignette = settings.vignette, + vignettePercent = if (!settings.setHome) settings.homeVignettePercentage else settings.lockVignettePercentage, + grayscale = settings.grayscale, + grayscalePercent = if (!settings.setHome) settings.homeGrayscalePercentage else settings.lockGrayscalePercentage + ) } catch (e: Exception) { Log.e("PaperizeWallpaperChanger", "Error in updating", e) - }*/ + } } /** @@ -486,7 +450,7 @@ class LockWallpaperService: Service() { */ private fun setWallpaper( context: Context, - wallpaper: Uri, + wallpaper: Uri?, darken: Boolean, darkenPercent: Int, scaling: ScalingConstants, @@ -495,108 +459,32 @@ class LockWallpaperService: Service() { vignette: Boolean, vignettePercent: Int, grayscale: Boolean, - grayscalePercent: Int + grayscalePercent: Int, + both: Boolean = false ): Boolean { - val wallpaperManager = WallpaperManager.getInstance(context) - try { - val size = getDeviceScreenSize(context) - val bitmap = retrieveBitmap(context, wallpaper, size.width, size.height) - if (bitmap == null) return false - else if (wallpaperManager.isSetWallpaperAllowed) { - processBitmap(size.width, size.height, bitmap, darken, darkenPercent, scaling, blur, blurPercent, vignette, vignettePercent, grayscale, grayscalePercent)?.let { image -> - wallpaperManager.setBitmap(image, null, true, WallpaperManager.FLAG_LOCK) - wallpaperManager.forgetLoadedWallpaper() - image.recycle() - } - bitmap.recycle() - context.triggerWallpaperTaskerEvent() - return true - } - else return false - } catch (e: IOException) { - Log.e("PaperizeWallpaperChanger", "Error setting wallpaper", e) - return false - } - } - - /** - * Refreshes the album by deleting invalid wallpapers and updating folder cover uri and wallpapers uri- - */ - private fun refreshAlbum(context: Context) { - /*CoroutineScope(Dispatchers.IO).launch { + wallpaper?.let { try { - var albumWithWallpapers = albumRepository.getAlbumsWithWallpaperAndFolder().first() - albumWithWallpapers.forEach { albumWithWallpaper -> - // Delete wallpaper if the URI is invalid - val invalidWallpapers = albumWithWallpaper.wallpapers.filterNot { wallpaper -> - val file = DocumentFileCompat.fromSingleUri(context, wallpaper.wallpaperUri.toUri()) - file?.exists() == true - } - if (invalidWallpapers.isNotEmpty()) { - albumRepository.deleteWallpaperList(invalidWallpapers) - } - - // Update folder cover uri and wallpapers uri - albumWithWallpaper.folders.forEach { folder -> - try { - DocumentFileCompat.fromTreeUri(context, folder.folderUri.toUri())?.let { folderDirectory -> - if (!folderDirectory.isDirectory()) { - albumRepository.deleteFolder(folder) - } else { - val wallpapers = getWallpaperFromFolder(folder.folderUri, context) - val folderCoverFile = folder.coverUri?.let { DocumentFileCompat.fromSingleUri(context, it.toUri()) } - val folderCover = folderCoverFile?.takeIf { it.exists() }?.uri?.toString() ?: wallpapers.randomOrNull() - albumRepository.updateFolder(folder.copy(coverUri = folderCover, wallpapers = wallpapers)) - } - } - } catch (_: Exception) { - DocumentFile.fromTreeUri(context, folder.folderUri.toUri())?.let { folderDirectory -> - if (!folderDirectory.isDirectory) { - albumRepository.deleteFolder(folder) - } else { - val wallpapers = getWallpaperFromFolder(folder.folderUri, context) - val folderCoverFile = folder.coverUri?.let { DocumentFileCompat.fromSingleUri(context, it.toUri()) } - val folderCover = folderCoverFile?.takeIf { it.exists() }?.uri?.toString() ?: wallpapers.randomOrNull() - albumRepository.updateFolder(folder.copy(coverUri = folderCover, wallpapers = wallpapers)) - } - } - } - - } - - // Delete empty albums - if (albumWithWallpaper.wallpapers.isEmpty() && albumWithWallpaper.folders.all { it.wallpapers.isEmpty() }) { - albumRepository.deleteAlbum(albumWithWallpaper.album) + val wallpaperManager = WallpaperManager.getInstance(context) + val size = getDeviceScreenSize(context) + val bitmap = retrieveBitmap(context, wallpaper, size.width, size.height) + if (bitmap == null) return false + else if (wallpaperManager.isSetWallpaperAllowed) { + processBitmap(size.width, size.height, bitmap, darken, darkenPercent, scaling, blur, blurPercent, vignette, vignettePercent, grayscale, grayscalePercent)?.let { image -> + if (both) wallpaperManager.setBitmap(image, null, true, WallpaperManager.FLAG_SYSTEM) + wallpaperManager.setBitmap(image, null, true, WallpaperManager.FLAG_LOCK) + wallpaperManager.forgetLoadedWallpaper() + image.recycle() } + bitmap.recycle() + context.triggerWallpaperTaskerEvent() + return true } - - // Update selected album - albumWithWallpapers = albumRepository.getAlbumsWithWallpaperAndFolder().first() - val selectedAlbum = selectedRepository.getSelectedAlbum().first().firstOrNull() - if (selectedAlbum != null) { - albumWithWallpapers.find { it.album.initialAlbumName == selectedAlbum.album.initialAlbumName } - ?.let { foundAlbum -> - val albumNameHashCode = foundAlbum.album.initialAlbumName.hashCode() - val wallpapers: List = - foundAlbum.wallpapers + foundAlbum.folders.flatMap { folder -> - folder.wallpapers.map { wallpaper -> - Wallpaper( - initialAlbumName = foundAlbum.album.initialAlbumName, - wallpaperUri = wallpaper, - key = wallpaper.hashCode() + albumNameHashCode, - ) - } - } - val wallpapersUri = wallpapers.map { it.wallpaperUri }.toSet() - if (wallpapersUri.isEmpty()) { - selectedRepository.deleteAll() - onDestroy() - } - } ?: run { onDestroy() } - } - } catch (e: Exception) { - Log.e("PaperizeWallpaperChanger", "Error refreshing album", e) + else return false + } catch (e: IOException) { + Log.e("PaperizeWallpaperChanger", "Error setting wallpaper", e) + return false } - }*/ + } + return false } } \ No newline at end of file