Skip to content

Commit

Permalink
Fixed trash
Browse files Browse the repository at this point in the history
  • Loading branch information
Mihai-Cristian Condrea committed Oct 22, 2024
1 parent 67b1dd8 commit effa589
Show file tree
Hide file tree
Showing 8 changed files with 194 additions and 131 deletions.
1 change: 1 addition & 0 deletions app/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,7 @@ dependencies {

// Lifecycle
implementation(libs.kotlinx.coroutines.android)
implementation(libs.kotlinx.serialization.json)
implementation(libs.androidx.lifecycle.runtime.ktx)
implementation(libs.androidx.lifecycle.common.java8)
implementation(libs.androidx.lifecycle.livedata.ktx)
Expand Down
198 changes: 109 additions & 89 deletions app/src/main/kotlin/com/d4rk/cleaner/data/datastore/DataStore.kt

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
Expand Up @@ -150,7 +150,9 @@ class HomeRepository(
* @param onSuccess Callback function to be invoked after successful restore.
*/
suspend fun restoreFromTrash(filesToRestore : Set<File> , onSuccess : () -> Unit) {
println("Cleaner for Android -> restoreFromTrash - normal repo")
withContext(Dispatchers.IO) {
println("Cleaner for Android -> we are on IO")
restoreFromTrash(filesToRestore)
withContext(Dispatchers.Main) {
onSuccess()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import com.d4rk.cleaner.data.datastore.DataStore
import com.d4rk.cleaner.data.model.ui.screens.FileTypesData
import com.d4rk.cleaner.data.model.ui.screens.UiHomeModel
import com.d4rk.cleaner.utils.cleaning.StorageUtils
import kotlinx.coroutines.flow.first
import java.io.File
import java.util.concurrent.TimeUnit
import kotlin.coroutines.resume
Expand Down Expand Up @@ -35,7 +36,7 @@ abstract class HomeRepositoryImplementation(
}
}

fun calculateDaysSince(timestamp: Long): Int {
fun calculateDaysSince(timestamp : Long) : Int {
if (timestamp == 0L) return 0

val currentTime = System.currentTimeMillis()
Expand Down Expand Up @@ -79,11 +80,6 @@ abstract class HomeRepositoryImplementation(
}
}

/**
* Moves the given files to the trash directory.
*
* @param filesToMove The list of files to move to the trash.
*/
suspend fun moveToTrash(filesToMove : List<File>) {
if (! trashDir.exists()) {
trashDir.mkdirs()
Expand All @@ -92,45 +88,94 @@ abstract class HomeRepositoryImplementation(
filesToMove.forEach { file ->
if (file.exists()) {
val originalPath = file.absolutePath
val destination = File(trashDir , "${file.name}_${file.lastModified()}")
val destination = File(trashDir , file.name)

println("Cleaner for Android -> Moving file: ${file.absolutePath} to ${destination.absolutePath}")

if (file.renameTo(destination)) {
dataStore.addTrashFilePath(originalPath)
println("Cleaner for Android -> File moved successfully")
dataStore.addTrashFileOriginalPath(originalPath)
dataStore.addTrashFilePath(originalPath to destination.absolutePath)


MediaScannerConnection.scanFile(
application , arrayOf(
destination.absolutePath , file.absolutePath
) , null , null
)
}
else {
println("Cleaner for Android -> File move failed")
}
}
else {
println("Cleaner for Android -> File does not exist: ${file.absolutePath}")
}
}
}

suspend fun restoreFromTrash(filesToRestore : Set<File>) {
println("Cleaner for Android -> impl logic called")
val originalPaths = dataStore.trashFileOriginalPaths.first()
println("Cleaner for Android -> Original paths from DataStore: $originalPaths")
val trashToOriginalMap =
dataStore.trashFilePaths.first().associate { it.second to it.first }
println("Cleaner for Android -> trashToOriginalMap: $trashToOriginalMap")

filesToRestore.forEach { file ->
println("Cleaner for Android -> Attempting to restore: ${file.absolutePath}")

if (file.exists()) {
dataStore.trashFilePaths.collect { paths ->
val originalPath =
paths.find { it == file.absolutePath.replace(Regex("_\\d+$") , "") }
if (originalPath != null) {
val destinationFile = File(originalPath)
val destinationParent = destinationFile.parentFile

if (destinationParent?.exists() == false) {
destinationParent.mkdirs()
}

if (file.renameTo(destinationFile)) {
MediaScannerConnection.scanFile(
application , arrayOf(
destinationFile.absolutePath , file.absolutePath
) , null , null
)
dataStore.removeTrashFilePath(originalPath)
}
val originalPath = originalPaths.firstOrNull { File(it).name == file.name }
println("Cleaner for Android -> Original path found: $originalPath")

if (originalPath != null) {
val destinationFile = File(originalPath)
val destinationParent = destinationFile.parentFile

if (destinationParent?.exists() == false) {
destinationParent.mkdirs()
}

println("Cleaner for Android -> Restoring to: ${destinationFile.absolutePath}")

if (file.renameTo(destinationFile)) {
println("Cleaner for Android -> File restored successfully")
dataStore.removeTrashFileOriginalPath(originalPath)
dataStore.removeTrashFilePath(originalPath)
MediaScannerConnection.scanFile(
application , arrayOf(
destinationFile.absolutePath , file.absolutePath
) , null , null
)
}
else {
println("Cleaner for Android -> File restore failed. Check if the file already exists or there is a permission issue.") // More informative message
}
}
else {
println("Cleaner for Android -> No original path found for ${file.name}. Restoring to Downloads.")
val downloadsDir =
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
val destinationFile = File(downloadsDir , file.name)

if (file.renameTo(destinationFile)) {
println("Cleaner for Android -> File restored to Downloads successfully")

MediaScannerConnection.scanFile(
application ,
arrayOf(destinationFile.absolutePath , file.absolutePath) ,
null ,
null
)
}
else {
println("Cleaner for Android -> File restore to Downloads failed")
}
}
}
else {
println("Cleaner for Android -> File does not exist in trash: ${file.absolutePath}")
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import com.d4rk.cleaner.ui.screens.main.repository.MainRepository
import com.d4rk.cleaner.ui.screens.startup.StartupActivity
import com.d4rk.cleaner.ui.viewmodel.BaseViewModel
import com.d4rk.cleaner.utils.IntentUtils
import com.d4rk.cleaner.utils.cleaning.StorageUtils
import com.google.android.play.core.appupdate.AppUpdateManager
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
Expand All @@ -25,8 +26,8 @@ class MainViewModel(application : Application) : BaseViewModel(application) {

fun loadTrashSize() {
viewModelScope.launch(coroutineExceptionHandler) {
repository.getTrashSize { trashSize ->
_uiState.update { it.copy(trashSize = trashSize) }
repository.dataStore.trashSize.collect { trashSize ->
_uiState.update { it.copy(trashSize = StorageUtils.formatSize(trashSize)) }
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -74,17 +74,4 @@ class MainRepository(val dataStore : DataStore , application : Application) :
}
}
}

/**
* Retrieves the current trash size from DataStore and formats it.
*/
suspend fun getTrashSize(onSuccess : (String) -> Unit) {
withContext(Dispatchers.IO) {
val size = dataStore.trashSize.first()
val formattedSize = StorageUtils.formatSize(size)
withContext(Dispatchers.Main) {
onSuccess(formattedSize)
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,12 @@ class TrashViewModel(application : Application) : BaseViewModel(application) {
fun restoreFromTrash() {
viewModelScope.launch(coroutineExceptionHandler) {
val filesToRestore = _uiState.value.fileSelectionStates.filter { it.value }.keys
println("Cleaner for Android -> restoreFromTrash() called") // Log the function call

println("Cleaner for Android -> Files to restore: $filesToRestore") // Log the files to restore

showLoading()

repository.restoreFromTrash(filesToRestore) {
loadTrashItems()
}
Expand Down
2 changes: 2 additions & 0 deletions gradle/libs.versions.toml
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ constraintlayoutCompose = "1.0.1"
coreSplashscreen = "1.0.1"
datastoreCore = "1.1.1"
firebaseBom = "33.4.0"
kotlinxSerializationJson = "1.7.3"
lifecycle = "2.8.6"
volley = "1.2.1"
kotlin = "2.0.10"
Expand Down Expand Up @@ -73,6 +74,7 @@ androidx-ui-graphics = { group = "androidx.compose.ui", name = "ui-graphics" }
androidx-ui-tooling = { group = "androidx.compose.ui", name = "ui-tooling" }
androidx-ui-tooling-preview = { group = "androidx.compose.ui", name = "ui-tooling-preview" }
androidx-ui-test-manifest = { group = "androidx.compose.ui", name = "ui-test-manifest", version.ref = "composeUi" }
kotlinx-serialization-json = { module = "org.jetbrains.kotlinx:kotlinx-serialization-json", version.ref = "kotlinxSerializationJson" }
ui-test-junit4 = { module = "androidx.compose.ui:ui-test-junit4", version.ref = "composeUi" }
androidx-material3 = { group = "androidx.compose.material3", name = "material3", version.ref = "composeMaterial3" }
androidx-navigation-compose = { group = "androidx.navigation", name = "navigation-compose", version.ref = "navigationCompose" }
Expand Down

0 comments on commit effa589

Please sign in to comment.