Fixed service to check for folder updates if last ran over 24 hours ago

Replaced DocumentFileCompat.fromSingleUri with DocumentFIle.fromSingleUri due to bug in library when calling null URIs
Refactored code for updating album
This commit is contained in:
Anthonyy232 committed 2024-05-27 14:50:55 -07:00
1 parent d52effa343
commit 895af4f865
6 files changed
+202 -72

No files matched your search

@@ -10,28 +10,39 @@ import android.net.Uri
import android.util.Log
import android.util.Size
import androidx.compose.ui.util.fastRoundToInt
import androidx.core.net.toUri
import androidx.documentfile.provider.DocumentFile
import androidx.exifinterface.media.ExifInterface
import com.anthonyla.paperize.feature.wallpaper.domain.model.Folder
import com.anthonyla.paperize.feature.wallpaper.domain.model.Wallpaper
import com.google.android.renderscript.Toolkit
import com.lazygeniouz.dfc.file.DocumentFileCompat
/**
* Get the dimensions of the image from the uri
*/
fun Uri.getImageDimensions(context: Context): Size? {
context.contentResolver.openInputStream(this)?.use { inputStream ->
val exif = ExifInterface(inputStream)
var width = exif.getAttributeInt(ExifInterface.TAG_IMAGE_WIDTH, 0)
var height = exif.getAttributeInt(ExifInterface.TAG_IMAGE_LENGTH, 0)
if (width == 0 || height == 0) {
val options = BitmapFactory.Options().apply {
inJustDecodeBounds = true
try {
context.contentResolver.openInputStream(this)?.use { inputStream ->
val exif = ExifInterface(inputStream)
var width = exif.getAttributeInt(ExifInterface.TAG_IMAGE_WIDTH, 0)
var height = exif.getAttributeInt(ExifInterface.TAG_IMAGE_LENGTH, 0)
if (width == 0 || height == 0) {
val options = BitmapFactory.Options().apply {
inJustDecodeBounds = true
}
BitmapFactory.decodeStream(
context.contentResolver.openInputStream(this),
null,
options
)
width = options.outWidth
height = options.outHeight
}
BitmapFactory.decodeStream(context.contentResolver.openInputStream(this), null, options)
width = options.outWidth
height = options.outHeight
return Size(width, height)
}
return Size(width, height)
}
return null
return null
} catch (e: Exception) { return null }
}
/**
@@ -132,3 +143,51 @@ fun blurBitmap(source: Bitmap, percent: Int): Bitmap {
}
}
/**
* Retrieve wallpaper URIs from a folder directory URI
*/
fun getWallpaperFromFolder(folderUri: String, context: Context): List<String> {
val folderDocumentFile = DocumentFileCompat.fromTreeUri(context, folderUri.toUri())
return listFilesRecursive(folderDocumentFile, context)
}
/**
* Helper function to recursively list files in a directory
*/
fun listFilesRecursive(parent: DocumentFileCompat?, context: Context): List<String> {
val files = mutableListOf<String>()
parent?.listFiles()?.forEach { file ->
if (file.isDirectory()) {
files.addAll(listFilesRecursive(file, context))
} else {
val allowedExtensions = listOf("jpg", "jpeg", "png", "heif", "webp", "JPG", "JPEG", "PNG", "HEIF", "WEBP")
if (file.extension in allowedExtensions) {
files.add(file.uri.toString())
}
}
}
return files
}
/**
* Helper function to find the first valid URI from a list of wallpapers
* It will search through all wallpapers of an album first, and then all wallpapers of every folder of an album
*/
fun findFirstValidUri(context: Context, wallpapers: List<Wallpaper>, folders: List<Folder>): String? {
wallpapers.forEach { wallpaper ->
val file = DocumentFile.fromSingleUri(context, wallpaper.wallpaperUri.toUri())
if (file?.exists() == true) {
return wallpaper.wallpaperUri
}
}
folders.forEach { folder ->
folder.wallpapers.forEach { wallpaper ->
val file = DocumentFile.fromSingleUri(context, wallpaper.toUri())
if (file?.exists() == true) {
return wallpaper
}
}
}
return null
}
@@ -115,11 +115,11 @@ fun PaperizeApp(
)
}
}
val wallpaperUriSet = wallpapers.map { it.wallpaperUri }.toSet()
val wallpapersUri = wallpapers.map { it.wallpaperUri }.toSet()
val newSelectedAlbum = SelectedAlbum(
album = foundAlbum.album.copy(
homeWallpapersInQueue = selectedAlbum.album.homeWallpapersInQueue.filter { it in wallpaperUriSet },
lockWallpapersInQueue = selectedAlbum.album.lockWallpapersInQueue.filter { it in wallpaperUriSet },
homeWallpapersInQueue = selectedAlbum.album.homeWallpapersInQueue.filter { it in wallpapersUri },
lockWallpapersInQueue = selectedAlbum.album.lockWallpapersInQueue.filter { it in wallpapersUri },
currentHomeWallpaper = selectedAlbum.album.currentHomeWallpaper,
currentLockWallpaper = selectedAlbum.album.currentLockWallpaper,
),
@@ -3,8 +3,11 @@ package com.anthonyla.paperize.feature.wallpaper.presentation.album
import android.app.Application
import android.content.Context
import androidx.core.net.toUri
import androidx.documentfile.provider.DocumentFile
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.viewModelScope
import com.anthonyla.paperize.core.findFirstValidUri
import com.anthonyla.paperize.core.getWallpaperFromFolder
import com.anthonyla.paperize.feature.wallpaper.domain.model.Folder
import com.anthonyla.paperize.feature.wallpaper.domain.model.Wallpaper
import com.anthonyla.paperize.feature.wallpaper.domain.repository.AlbumRepository
@@ -99,7 +102,7 @@ class AlbumsViewModel @Inject constructor (
repository.deleteFolder(folder)
} else {
val wallpapers = getWallpaperFromFolder(folder.folderUri, context)
val folderCoverFile = folder.coverUri?.let { DocumentFileCompat.fromSingleUri(context, it.toUri()) }
val folderCoverFile = folder.coverUri?.let { DocumentFile.fromSingleUri(context, it.toUri()) }
val folderCover = folderCoverFile?.takeIf { it.exists() }?.uri?.toString() ?: wallpapers.randomOrNull()
repository.updateFolder(folder.copy(coverUri = folderCover, wallpapers = wallpapers))
}
@@ -109,9 +112,9 @@ class AlbumsViewModel @Inject constructor (
albumWithWallpapers = repository.getAlbumsWithWallpaperAndFolder().first()
albumWithWallpapers.forEach { albumWithWallpaper ->
// Update album cover uri if null or invalid
val albumCoverFile = albumWithWallpaper.album.coverUri?.toUri()?.let { DocumentFileCompat.fromSingleUri(context, it) }
val albumCoverFile = albumWithWallpaper.album.coverUri?.toUri()?.let { DocumentFile.fromSingleUri(context, it) }
if (albumCoverFile == null || !albumCoverFile.exists()) {
val newCoverUri = findFirstValidUri(albumWithWallpaper.wallpapers, albumWithWallpaper.folders)
val newCoverUri = findFirstValidUri(context, albumWithWallpaper.wallpapers, albumWithWallpaper.folders)
repository.updateAlbum(albumWithWallpaper.album.copy(coverUri = newCoverUri))
}
}
@@ -130,53 +133,5 @@ class AlbumsViewModel @Inject constructor (
}
}
}
/**
* Retrieve wallpaper URIs from a folder directory URI
*/
private fun getWallpaperFromFolder(folderUri: String, context: Context): List<String> {
val folderDocumentFile = DocumentFileCompat.fromTreeUri(context, folderUri.toUri())
return listFilesRecursive(folderDocumentFile, context)
}
/**
* Helper function to recursively list files in a directory
*/
private fun listFilesRecursive(parent: DocumentFileCompat?, context: Context): List<String> {
val files = mutableListOf<String>()
parent?.listFiles()?.forEach { file ->
if (file.isDirectory()) {
files.addAll(listFilesRecursive(file, context))
} else {
val allowedExtensions = listOf("jpg", "jpeg", "png", "heif", "webp", "JPG", "JPEG", "PNG", "HEIF", "WEBP")
if (file.extension in allowedExtensions) {
files.add(file.uri.toString())
}
}
}
return files
}
/**
* Helper function to find the first valid URI from a list of wallpapers
* It will search through all wallpapers of an album first, and then all wallpapers of every folder of an album
*/
private fun findFirstValidUri(wallpapers: List<Wallpaper>, folders: List<Folder>): String? {
wallpapers.forEach { wallpaper ->
val file = DocumentFileCompat.fromSingleUri(context, wallpaper.wallpaperUri.toUri())
if (file?.exists() == true) {
return wallpaper.wallpaperUri
}
}
folders.forEach { folder ->
folder.wallpapers.forEach { wallpaper ->
val file = DocumentFileCompat.fromSingleUri(context, wallpaper.toUri())
if (file?.exists() == true) {
return wallpaper
}
}
}
return null
}
}
@@ -38,7 +38,7 @@ class SettingsViewModel @Inject constructor (
val firstSet = async { settingsDataStoreImpl.getBoolean(SettingsConstants.FIRST_SET) ?: false }
val darkMode = async { settingsDataStoreImpl.getBoolean(SettingsConstants.DARK_MODE_TYPE) }
val dynamicTheming = async { settingsDataStoreImpl.getBoolean(SettingsConstants.DYNAMIC_THEME_TYPE) ?: false }
val enableChanger = async { settingsDataStoreImpl.getBoolean(SettingsConstants.ENABLE_CHANGER) ?: false }
val enableChanger = async { settingsDataStoreImpl.getBoolean(SettingsConstants.ENABLE_CHANGER) ?: true }
val setHomeWallpaper = async { settingsDataStoreImpl.getBoolean(SettingsConstants.HOME_WALLPAPER) ?: false }
val setLockWallpaper = async { settingsDataStoreImpl.getBoolean(SettingsConstants.LOCK_WALLPAPER) ?: false }
val homeWallpaperInterval = async { settingsDataStoreImpl.getInt(SettingsConstants.HOME_WALLPAPER_CHANGE_INTERVAL) ?: SettingsConstants.WALLPAPER_CHANGE_INTERVAL_DEFAULT }
@@ -19,6 +19,7 @@ import android.util.DisplayMetrics
import android.util.Log
import androidx.core.app.NotificationCompat
import androidx.core.net.toUri
import androidx.documentfile.provider.DocumentFile
import com.anthonyla.paperize.R
import com.anthonyla.paperize.core.ScalingConstants
import com.anthonyla.paperize.core.SettingsConstants
@@ -28,14 +29,19 @@ import com.anthonyla.paperize.core.darkenBitmap
import com.anthonyla.paperize.core.fillBitmap
import com.anthonyla.paperize.core.fitBitmap
import com.anthonyla.paperize.core.getImageDimensions
import com.anthonyla.paperize.core.getWallpaperFromFolder
import com.anthonyla.paperize.core.stretchBitmap
import com.anthonyla.paperize.data.settings.SettingsDataStore
import com.anthonyla.paperize.feature.wallpaper.domain.model.SelectedAlbum
import com.anthonyla.paperize.feature.wallpaper.domain.model.Wallpaper
import com.anthonyla.paperize.feature.wallpaper.domain.repository.AlbumRepository
import com.anthonyla.paperize.feature.wallpaper.domain.repository.SelectedAlbumRepository
import com.anthonyla.paperize.feature.wallpaper.presentation.MainActivity
import com.lazygeniouz.dfc.file.DocumentFileCompat
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 java.io.IOException
@@ -62,6 +68,7 @@ class WallpaperService: Service() {
private var scheduleSeparately: Boolean = false
private var lastRan1: LocalDateTime? = null
private var lastRan2: LocalDateTime? = null
private var refresherTimer = LocalDateTime.now()
enum class Actions {
START,
@@ -85,6 +92,11 @@ class WallpaperService: Service() {
val self = this
CoroutineScope(Dispatchers.IO).launch {
try {
if (LocalDateTime.now().minusDays(1).isAfter(refresherTimer)) {
refreshAlbum(this@WallpaperService)
refresherTimer = LocalDateTime.now()
delay(5000)
}
changeWallpaper(this@WallpaperService, true)
} catch (e: Exception) {
Log.e("PaperizeWallpaperChanger", "Error in runnableCode", e)
@@ -99,6 +111,11 @@ class WallpaperService: Service() {
val self = this
CoroutineScope(Dispatchers.IO).launch {
try {
if (LocalDateTime.now().minusDays(1).isAfter(refresherTimer)) {
refreshAlbum(this@WallpaperService)
refresherTimer = LocalDateTime.now()
delay(5000)
}
changeWallpaper(this@WallpaperService, false)
} catch (e: Exception) {
Log.e("PaperizeWallpaperChanger", "Error in runnableCode", e)
@@ -125,6 +142,7 @@ class WallpaperService: Service() {
nextSetTime2 = null
lastRan1 = null
lastRan2 = null
refresherTimer = LocalDateTime.now()
if (!scheduleSeparately) {
runnableCode1 = object : Runnable {
@@ -132,6 +150,11 @@ class WallpaperService: Service() {
val self = this
CoroutineScope(Dispatchers.IO).launch {
try {
if (LocalDateTime.now().minusDays(1).isAfter(refresherTimer)) {
refreshAlbum(this@WallpaperService)
refresherTimer = LocalDateTime.now()
delay(5000)
}
changeWallpaper(this@WallpaperService, null)
} catch (e: Exception) {
Log.e("PaperizeWallpaperChanger", "Error in runnableCode", e)
@@ -149,6 +172,11 @@ class WallpaperService: Service() {
val self = this
CoroutineScope(Dispatchers.IO).launch {
try {
if (LocalDateTime.now().minusDays(1).isAfter(refresherTimer)) {
refreshAlbum(this@WallpaperService)
refresherTimer = LocalDateTime.now()
delay(5000)
}
changeWallpaper(this@WallpaperService, true)
} catch (e: Exception) {
Log.e("PaperizeWallpaperChanger", "Error in runnableCode", e)
@@ -164,6 +192,11 @@ class WallpaperService: Service() {
val self = this
CoroutineScope(Dispatchers.IO).launch {
try {
if (LocalDateTime.now().minusDays(1).isAfter(refresherTimer)) {
refreshAlbum(this@WallpaperService)
refresherTimer = LocalDateTime.now()
delay(5000)
}
changeWallpaper(this@WallpaperService, false)
} catch (e: Exception) {
Log.e("PaperizeWallpaperChanger", "Error in runnableCode", e)
@@ -186,7 +219,7 @@ class WallpaperService: Service() {
nextSetTime2 = null
lastRan1 = null
lastRan2 = null
refresherTimer = LocalDateTime.now()
val formatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT)
val currentTime = LocalDateTime.now()
@@ -205,7 +238,6 @@ class WallpaperService: Service() {
}
}
val notification = createNotification()
val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notificationManager.notify(1, notification)
@@ -215,6 +247,11 @@ class WallpaperService: Service() {
val self = this
CoroutineScope(Dispatchers.IO).launch {
try {
if (LocalDateTime.now().minusDays(1).isAfter(refresherTimer)) {
refreshAlbum(this@WallpaperService)
refresherTimer = LocalDateTime.now()
delay(5000)
}
changeWallpaper(this@WallpaperService, null)
} catch (e: Exception) {
Log.e("PaperizeWallpaperChanger", "Error in runnableCode", e)
@@ -232,6 +269,11 @@ class WallpaperService: Service() {
val self = this
CoroutineScope(Dispatchers.IO).launch {
try {
if (LocalDateTime.now().minusDays(1).isAfter(refresherTimer)) {
refreshAlbum(this@WallpaperService)
refresherTimer = LocalDateTime.now()
delay(5000)
}
changeWallpaper(this@WallpaperService, true)
} catch (e: Exception) {
Log.e("PaperizeWallpaperChanger", "Error in runnableCode", e)
@@ -247,6 +289,11 @@ class WallpaperService: Service() {
val self = this
CoroutineScope(Dispatchers.IO).launch {
try {
if (LocalDateTime.now().minusDays(1).isAfter(refresherTimer)) {
refreshAlbum(this@WallpaperService)
refresherTimer = LocalDateTime.now()
delay(5000)
}
changeWallpaper(this@WallpaperService, false)
} catch (e: Exception) {
Log.e("PaperizeWallpaperChanger", "Error in runnableCode", e)
@@ -763,4 +810,73 @@ class WallpaperService: Service() {
return null
}
}
private fun refreshAlbum(context: Context) {
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 = DocumentFile.fromSingleUri(context, wallpaper.wallpaperUri.toUri())
file?.exists() == true
}
if (invalidWallpapers.isNotEmpty()) {
albumRepository.deleteWallpaperList(invalidWallpapers)
}
// Update folder wallpapers
albumWithWallpaper.folders.forEach { folder ->
DocumentFileCompat.fromTreeUri(context, folder.folderUri.toUri())?.let { folderDirectory ->
if (!folderDirectory.isDirectory()) {
albumRepository.deleteFolder(folder)
} else {
val wallpapers = getWallpaperFromFolder(folder.folderUri, context)
albumRepository.updateFolder(folder.copy(wallpapers = wallpapers))
}
}
}
}
// 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<Wallpaper> =
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()
}
else {
val newSelectedAlbum = SelectedAlbum(
album = foundAlbum.album.copy(
homeWallpapersInQueue = wallpapersUri.shuffled(),
lockWallpapersInQueue = wallpapersUri.shuffled(),
currentHomeWallpaper = selectedAlbum.album.currentHomeWallpaper,
currentLockWallpaper = selectedAlbum.album.currentLockWallpaper,
),
wallpapers = wallpapers
)
selectedRepository.upsertSelectedAlbum(newSelectedAlbum)
}
} ?: run { onDestroy() }
}
} catch (e: Exception) {
Log.e("PaperizeWallpaperChanger", "Error refreshing album", e)
}
}
}
}