Added data refresh for onStart and onResume

This commit is contained in:
Anthonyy232 committed 2023-11-05 10:35:54 -08:00
1 parent c6790a4491
commit a9ed63f64b
11 files changed
+198 -60

No files matched your search

@@ -4,6 +4,7 @@ import androidx.room.Dao
import androidx.room.Delete
import androidx.room.Query
import androidx.room.Transaction
import androidx.room.Update
import androidx.room.Upsert
import com.anthonyla.paperize.feature.wallpaper.domain.model.Album
import com.anthonyla.paperize.feature.wallpaper.domain.model.AlbumWithWallpaper
@@ -33,6 +34,16 @@ interface AlbumDao {
@Delete
suspend fun deleteWallpaper(wallpaper: Wallpaper)
@Delete
suspend fun deleteFolder(folder: Folder)
@Update
suspend fun updateAlbum(album: Album)
@Update
suspend fun updateWallpaper(wallpaper: Wallpaper)
@Update
suspend fun updateFolder(folder: Folder)
}
@@ -38,4 +38,17 @@ class AlbumRepositoryImpl(
override suspend fun deleteFolder(folder: Folder) {
dao.deleteFolder(folder)
}
override suspend fun updateAlbum(album: Album) {
dao.updateAlbum(album)
}
override suspend fun updateFolder(folder: Folder) {
dao.updateFolder(folder)
}
override suspend fun updateWallpaper(wallpaper: Wallpaper) {
dao.updateWallpaper(wallpaper)
}
}
@@ -10,8 +10,11 @@ interface AlbumRepository {
fun getAlbumsWithWallpapers(): Flow<List<AlbumWithWallpaper>>
suspend fun upsertAlbum(album: Album)
suspend fun deleteAlbum(album: Album)
suspend fun updateAlbum(album: Album)
suspend fun upsertWallpaper(wallpaper: Wallpaper)
suspend fun deleteWallpaper(wallpaper: Wallpaper)
suspend fun updateWallpaper(wallpaper: Wallpaper)
suspend fun upsertFolder(folder: Folder)
suspend fun deleteFolder(folder: Folder)
suspend fun updateFolder(folder: Folder)
}
@@ -6,9 +6,21 @@ import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.activity.viewModels
import androidx.compose.material3.Surface
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.platform.LocalLifecycleOwner
import androidx.compose.ui.unit.dp
import androidx.core.splashscreen.SplashScreen.Companion.installSplashScreen
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import androidx.lifecycle.LifecycleOwner
import com.anthonyla.paperize.feature.wallpaper.presentation.add_album_screen.AddAlbumViewModel
import com.anthonyla.paperize.feature.wallpaper.presentation.album.AlbumsEvent
import com.anthonyla.paperize.feature.wallpaper.presentation.album.AlbumsViewModel
import com.anthonyla.paperize.feature.wallpaper.presentation.settings.SettingsViewModel
import com.anthonyla.paperize.feature.wallpaper.presentation.themes.PaperizeTheme
@@ -26,6 +38,12 @@ class MainActivity : ComponentActivity() {
enableEdgeToEdge()
super.onCreate(savedInstanceState)
setContent {
val lifecycleEvent = rememberLifecycleEvent()
LaunchedEffect(lifecycleEvent) {
if (lifecycleEvent == Lifecycle.Event.ON_RESUME) {
albumsViewModel.onEvent(AlbumsEvent.RefreshAlbums)
}
}
PaperizeTheme(settingsViewModel.state) {
Surface(tonalElevation = 5.dp) {
PaperizeApp()
@@ -33,4 +51,19 @@ class MainActivity : ComponentActivity() {
}
}
}
}
@Composable
fun rememberLifecycleEvent(lifecycleOwner: LifecycleOwner = LocalLifecycleOwner.current): Lifecycle.Event {
var state by remember { mutableStateOf(Lifecycle.Event.ON_ANY) }
DisposableEffect(lifecycleOwner) {
val observer = LifecycleEventObserver { _, event ->
state = event
}
lifecycleOwner.lifecycle.addObserver(observer)
onDispose {
lifecycleOwner.lifecycle.removeObserver(observer)
}
}
return state
}
@@ -66,10 +66,7 @@ fun PaperizeApp(
route = NavScreens.AddEdit.route.plus("/{initialAlbumName}"),
arguments = listOf(navArgument("initialAlbumName") { type = NavType.StringType }),
enterTransition = {
slideIntoContainer(
AnimatedContentTransitionScope.SlideDirection.Down,
animationSpec = tween(300)
)
fadeIn(animationSpec = tween(300, easing = LinearEasing))
},
exitTransition = {
fadeOut(animationSpec = tween(300, easing = LinearEasing))
@@ -108,6 +105,12 @@ fun PaperizeApp(
},
exitTransition = {
fadeOut(animationSpec = tween(300, easing = LinearEasing))
},
popEnterTransition = {
fadeIn(animationSpec = tween(300, easing = LinearEasing))
},
popExitTransition = {
fadeOut(animationSpec = tween(300, easing = LinearEasing))
}
) { backStackEntry ->
backStackEntry.arguments?.getString("wallpaperUri").let { wallpaper ->
@@ -127,16 +130,16 @@ fun PaperizeApp(
navArgument("wallpapers") { type = NavType.StringType }
),
enterTransition = {
slideIntoContainer(
AnimatedContentTransitionScope.SlideDirection.Left,
animationSpec = tween(300)
)
fadeIn(animationSpec = tween(300, easing = LinearEasing))
},
exitTransition = {
slideOutOfContainer(
AnimatedContentTransitionScope.SlideDirection.Right,
animationSpec = tween(300)
)
fadeOut(animationSpec = tween(300, easing = LinearEasing))
},
popEnterTransition = {
fadeIn(animationSpec = tween(300, easing = LinearEasing))
},
popExitTransition = {
fadeOut(animationSpec = tween(300, easing = LinearEasing))
}
) { backStackEntry ->
val folderUri = backStackEntry.arguments?.getString("folderUri")
@@ -165,16 +168,16 @@ fun PaperizeApp(
navArgument("initialAlbumName") { type = NavType.StringType },
),
enterTransition = {
slideIntoContainer(
AnimatedContentTransitionScope.SlideDirection.Left,
animationSpec = tween(300)
)
fadeIn(animationSpec = tween(300, easing = LinearEasing))
},
exitTransition = {
slideOutOfContainer(
AnimatedContentTransitionScope.SlideDirection.Right,
animationSpec = tween(300)
)
fadeOut(animationSpec = tween(300, easing = LinearEasing))
},
popEnterTransition = {
fadeIn(animationSpec = tween(300, easing = LinearEasing))
},
popExitTransition = {
fadeOut(animationSpec = tween(300, easing = LinearEasing))
}
) { backStackEntry ->
val initialAlbumName = backStackEntry.arguments?.getString("initialAlbumName")
@@ -200,16 +203,16 @@ fun PaperizeApp(
composable(
route = NavScreens.Settings.route,
enterTransition = {
slideIntoContainer(
AnimatedContentTransitionScope.SlideDirection.Down,
animationSpec = tween(300)
)
fadeIn(animationSpec = tween(300, easing = LinearEasing))
},
exitTransition = {
slideOutOfContainer(
AnimatedContentTransitionScope.SlideDirection.Up,
animationSpec = tween(300)
)
fadeOut(animationSpec = tween(300, easing = LinearEasing))
},
popEnterTransition = {
fadeIn(animationSpec = tween(300, easing = LinearEasing))
},
popExitTransition = {
fadeOut(animationSpec = tween(300, easing = LinearEasing))
}
) {
SettingsScreen(onBackClick = { navController.navigateUp() })
@@ -38,24 +38,24 @@ class AddAlbumViewModel @Inject constructor(
when (event) {
is AddAlbumEvent.SaveAlbum -> {
viewModelScope.launch {
val albumCoverUri = when (state.value.isEmpty) {
val albumCoverUri = when (_state.value.isEmpty) {
true -> ""
false -> {
if (state.value.wallpapers.isNotEmpty())
state.value.wallpapers.random().wallpaperUri
if (_state.value.wallpapers.isNotEmpty())
_state.value.wallpapers.random().wallpaperUri
else {
state.value.folders.random().coverUri
_state.value.folders.random().coverUri
}
}
}
val albumWithWallpaper = AlbumWithWallpaper(
album = Album(
initialAlbumName = state.value.initialAlbumName,
displayedAlbumName = state.value.displayedAlbumName,
initialAlbumName = _state.value.initialAlbumName,
displayedAlbumName = _state.value.displayedAlbumName,
coverUri = albumCoverUri
),
wallpapers = state.value.wallpapers,
folders = state.value.folders
wallpapers = _state.value.wallpapers,
folders = _state.value.folders
)
repository.upsertAlbum(albumWithWallpaper.album)
@@ -91,7 +91,7 @@ class AddAlbumViewModel @Inject constructor(
}
is AddAlbumEvent.ReflectAlbumName -> {
if (event.newAlbumName != state.value.initialAlbumName) {
if (event.newAlbumName != _state.value.initialAlbumName) {
viewModelScope.launch {
_state.update { it.copy(
initialAlbumName = event.newAlbumName,
@@ -110,7 +110,7 @@ class AddAlbumViewModel @Inject constructor(
}
is AddAlbumEvent.AddWallpaper -> {
viewModelScope.launch {
if (!state.value.wallpapers.any { it.wallpaperUri == event.wallpaperUri }) {
if (!_state.value.wallpapers.any { it.wallpaperUri == event.wallpaperUri }) {
_state.update { it.copy(
wallpapers = it.wallpapers.plus(
Wallpaper(it.initialAlbumName, event.wallpaperUri)
@@ -122,7 +122,7 @@ class AddAlbumViewModel @Inject constructor(
}
is AddAlbumEvent.DeleteWallpaper -> {
viewModelScope.launch {
val wallpaperToRemove = state.value.wallpapers.find { it.wallpaperUri == event.wallpaperUri }
val wallpaperToRemove = _state.value.wallpapers.find { it.wallpaperUri == event.wallpaperUri }
if (wallpaperToRemove != null) {
_state.update { it.copy(
wallpapers = it.wallpapers.minus(wallpaperToRemove),
@@ -133,7 +133,7 @@ class AddAlbumViewModel @Inject constructor(
}
is AddAlbumEvent.AddFolder -> {
viewModelScope.launch {
if (!state.value.folders.any { it.folderUri == event.directoryUri }) {
if (!_state.value.folders.any { it.folderUri == event.directoryUri }) {
val wallpapers: List<String> = getWallpaperFromFolder(event.directoryUri, context)
val folderName = getFolderNameFromUri(event.directoryUri, context)
_state.update { it.copy(
@@ -153,7 +153,7 @@ class AddAlbumViewModel @Inject constructor(
}
is AddAlbumEvent.DeleteFolder -> {
viewModelScope.launch {
val folderToRemove = state.value.folders.find { it.folderUri == event.directoryUri }
val folderToRemove = _state.value.folders.find { it.folderUri == event.directoryUri }
if (folderToRemove != null) {
_state.update { it.copy(
folders = it.folders.minus(folderToRemove)
@@ -164,10 +164,10 @@ class AddAlbumViewModel @Inject constructor(
}
is AddAlbumEvent.SelectAll -> {
viewModelScope.launch {
if (!state.value.allSelected) {
if (!_state.value.allSelected) {
_state.update { it.copy(
selectedFolders = state.value.folders.map { folder -> folder.folderUri },
selectedWallpapers = state.value.wallpapers.map { wallpaper -> wallpaper.wallpaperUri },
selectedFolders = _state.value.folders.map { folder -> folder.folderUri },
selectedWallpapers = _state.value.wallpapers.map { wallpaper -> wallpaper.wallpaperUri },
selectedCount = it.folders.size + it.wallpapers.size
) }
updateAllSelected()
@@ -186,7 +186,7 @@ class AddAlbumViewModel @Inject constructor(
}
is AddAlbumEvent.SelectFolder -> {
viewModelScope.launch {
if (!state.value.selectedFolders.any { it == event.directoryUri }) {
if (!_state.value.selectedFolders.any { it == event.directoryUri }) {
_state.update { it.copy(
selectedFolders = it.selectedFolders.plus(event.directoryUri),
selectedCount = it.selectedCount + 1
@@ -197,7 +197,7 @@ class AddAlbumViewModel @Inject constructor(
}
is AddAlbumEvent.SelectWallpaper -> {
viewModelScope.launch {
if (!state.value.selectedWallpapers.any { it == event.wallpaperUri }) {
if (!_state.value.selectedWallpapers.any { it == event.wallpaperUri }) {
_state.update { it.copy(
selectedWallpapers = it.selectedWallpapers.plus(event.wallpaperUri),
selectedCount = it.selectedCount + 1
@@ -208,7 +208,7 @@ class AddAlbumViewModel @Inject constructor(
}
is AddAlbumEvent.RemoveFolderFromSelection -> {
viewModelScope.launch {
if (state.value.selectedFolders.find { it == event.directoryUri } != null ) {
if (_state.value.selectedFolders.find { it == event.directoryUri } != null ) {
_state.update { it.copy(
selectedFolders = it.selectedFolders.minus(event.directoryUri),
selectedCount = it.selectedCount - 1
@@ -219,7 +219,7 @@ class AddAlbumViewModel @Inject constructor(
}
is AddAlbumEvent.RemoveWallpaperFromSelection -> {
viewModelScope.launch {
if (state.value.selectedWallpapers.find { it == event.wallpaperUri } != null ) {
if (_state.value.selectedWallpapers.find { it == event.wallpaperUri } != null ) {
_state.update { it.copy(
selectedWallpapers = it.selectedWallpapers.minus(event.wallpaperUri),
selectedCount = it.selectedCount - 1
@@ -1,4 +1,4 @@
package com.anthonyla.paperize.feature.wallpaper.presentation.album
sealed class AlbumsEvent {
data object LoadAlbums: AlbumsEvent()
data object RefreshAlbums: AlbumsEvent()
}
@@ -2,25 +2,28 @@ package com.anthonyla.paperize.feature.wallpaper.presentation.album
import android.app.Application
import android.content.Context
import android.webkit.MimeTypeMap
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.core.net.toUri
import androidx.documentfile.provider.DocumentFile
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.asLiveData
import androidx.lifecycle.viewModelScope
import com.anthonyla.paperize.feature.wallpaper.domain.model.Album
import com.anthonyla.paperize.feature.wallpaper.domain.repository.AlbumRepository
import com.lazygeniouz.dfc.file.DocumentFileCompat
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import javax.inject.Inject
@HiltViewModel
class AlbumsViewModel @Inject constructor(
class AlbumsViewModel @Inject constructor (
application: Application,
private val repository: AlbumRepository
) : AndroidViewModel(application) {
@@ -34,13 +37,66 @@ class AlbumsViewModel @Inject constructor(
)
init {
refreshAlbums()
shouldNotBypassSplashScreen = false
viewModelScope.launch {
updateAlbums()
refreshAlbums()
shouldNotBypassSplashScreen = false
}
}
fun onEvent(event: AlbumsEvent) {
when (event) {
AlbumsEvent.RefreshAlbums -> {
viewModelScope.launch {
updateAlbums()
refreshAlbums()
}
}
}
}
// Verify and remove stale data in Room database
private fun updateAlbums() {
viewModelScope.launch {
val albumWithWallpapers = repository.getAlbumsWithWallpapers().first()
albumWithWallpapers.forEach { albumWithWallpaper ->
if (albumWithWallpaper.album.coverUri != null) {
val albumCoverFile = DocumentFile.fromSingleUri(context, albumWithWallpaper.album.coverUri.toUri())
if (albumCoverFile == null || !albumCoverFile.exists()) {
repository.updateAlbum(albumWithWallpaper.album.copy(coverUri = null))
}
}
// Update wallpaper
albumWithWallpaper.wallpapers.forEach { wallpaper ->
val file = DocumentFile.fromSingleUri(context, wallpaper.wallpaperUri.toUri())
if (file == null || !file.exists()) { repository.deleteWallpaper(wallpaper) }
}
// Update folder cover uri and children uri
albumWithWallpaper.folders.forEach { folder ->
val folderDirectory = DocumentFile.fromTreeUri(context, folder.folderUri.toUri())
if (folderDirectory == null || !folderDirectory.isDirectory) {
repository.deleteFolder(folder)
} else {
val wallpapers = getWallpaperFromFolder(folder.folderUri, context)
var folderCover: String? = null
if (folder.coverUri != null) {
val folderCoverFile = DocumentFile.fromSingleUri(context, folder.coverUri.toUri())
if (folderCoverFile == null || !folderCoverFile.exists()) {
folderCover = folder.wallpapers.randomOrNull()
} else { folderCover = folder.coverUri }
} else {
folderCover = wallpapers.randomOrNull()
}
repository.updateFolder(folder.copy(coverUri = folderCover, wallpapers = wallpapers))
}
}
}
}
}
// Retrieve albums from database into viewModel
private fun refreshAlbums() {
viewModelScope.launch {
repository.getAlbumsWithWallpapers().collect { albumWithWallpapers ->
@@ -48,12 +104,29 @@ class AlbumsViewModel @Inject constructor(
albumWithWallpapers = albumWithWallpapers
) }
}
//verifyAllAlbumAndWallpaper()
}
}
private fun verifyAllAlbumAndWallpaper() {
viewModelScope.launch {
private fun getWallpaperFromFolder(folderUri: String, context: Context): List<String> {
val folderDocumentFile = DocumentFileCompat.fromTreeUri(context, folderUri.toUri())
return listFilesRecursive(folderDocumentFile, context)
}
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 extension = MimeTypeMap.getFileExtensionFromUrl(file.uri.toString())
val allowedExtensions = listOf("jpg", "png", "heif", "webp")
if (extension in allowedExtensions) {
files.add(file.uri.toString())
}
}
}
return files
}
}
@@ -124,7 +124,6 @@ fun AlbumItem(
modifier = Modifier
.aspectRatio(1f)
.clip(RoundedCornerShape(roundedCornerShapeTransition))
.blur(radius = 2.dp)
)
if (selectionMode) {
if (itemSelected) {
@@ -129,7 +129,6 @@ fun FolderItem(
modifier = Modifier
.height(configuration.screenHeightDp.dp / 4.0f)
.clip(RoundedCornerShape(roundedCornerShapeTransition))
.blur(radius = 2.dp)
)
}
if (selectionMode) {
@@ -30,7 +30,12 @@ class SettingsViewModel @Inject constructor (
private var currentGetJob: Job? = null
init { viewModelScope.launch { refreshSettings() } }
init {
viewModelScope.launch {
refreshSettings()
shouldNotBypassSplashScreen = false
}
}
fun onEvent(event: SettingsEvent) {
when (event) {
@@ -66,7 +71,6 @@ class SettingsViewModel @Inject constructor (
false, null -> false
}
) }
shouldNotBypassSplashScreen = false
}
}
}