DroidFS/app/src/main/java/sushi/hardcore/droidfs/VolumeManager.kt

64 lines
1.9 KiB
Kotlin
Raw Normal View History

2023-03-07 23:25:17 +01:00
package sushi.hardcore.droidfs
2023-09-06 19:27:41 +02:00
import android.content.Context
2023-05-09 23:13:46 +02:00
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.cancel
2023-09-06 19:27:41 +02:00
import sushi.hardcore.droidfs.content_providers.VolumeProvider
2023-03-07 23:25:17 +01:00
import sushi.hardcore.droidfs.filesystems.EncryptedVolume
2023-09-06 19:27:41 +02:00
class VolumeManager(private val context: Context) {
2023-03-07 23:25:17 +01:00
private var id = 0
private val volumes = HashMap<Int, EncryptedVolume>()
private val volumesData = HashMap<VolumeData, Int>()
2023-05-09 23:13:46 +02:00
private val scopes = HashMap<Int, CoroutineScope>()
2023-03-07 23:25:17 +01:00
fun insert(volume: EncryptedVolume, data: VolumeData): Int {
volumes[id] = volume
volumesData[data] = id
2023-09-06 19:27:41 +02:00
VolumeProvider.notifyRootsChanged(context)
2023-03-07 23:25:17 +01:00
return id++
}
fun isOpen(volume: VolumeData): Boolean {
return volumesData.containsKey(volume)
}
fun getVolumeId(volume: VolumeData): Int? {
return volumesData[volume]
}
fun getVolume(id: Int): EncryptedVolume? {
return volumes[id]
}
2023-09-06 19:27:41 +02:00
fun listVolumes(): List<Pair<Int, VolumeData>> {
return volumesData.map { (data, id) -> Pair(id, data) }
}
2023-05-09 23:13:46 +02:00
fun getCoroutineScope(volumeId: Int): CoroutineScope {
return scopes[volumeId] ?: CoroutineScope(SupervisorJob() + Dispatchers.IO).also { scopes[volumeId] = it }
}
2023-03-07 23:25:17 +01:00
fun closeVolume(id: Int) {
volumes.remove(id)?.let { volume ->
2023-05-09 23:13:46 +02:00
scopes[id]?.cancel()
2023-03-07 23:25:17 +01:00
volume.close()
volumesData.filter { it.value == id }.forEach {
volumesData.remove(it.key)
}
2023-09-06 19:27:41 +02:00
VolumeProvider.notifyRootsChanged(context)
2023-03-07 23:25:17 +01:00
}
}
fun closeAll() {
2023-05-09 23:13:46 +02:00
volumes.forEach {
scopes[it.key]?.cancel()
it.value.close()
}
2023-03-07 23:25:17 +01:00
volumes.clear()
volumesData.clear()
2023-09-06 19:27:41 +02:00
VolumeProvider.notifyRootsChanged(context)
2023-03-07 23:25:17 +01:00
}
}