2020-10-15 21:00:31 +02:00
package org.mosad.teapod.util
import android.content.Context
2021-05-26 19:46:46 +02:00
import android.net.Uri
2020-11-14 13:10:05 +01:00
import android.util.Log
2020-10-15 21:00:31 +02:00
import com.google.gson.Gson
2020-11-14 13:10:05 +01:00
import com.google.gson.JsonParser
2020-10-15 21:00:31 +02:00
import kotlinx.coroutines.*
import java.io.File
2021-05-26 19:46:46 +02:00
import java.io.FileReader
import java.io.FileWriter
2020-10-15 21:00:31 +02:00
/ * *
2020-10-16 11:23:32 +02:00
* This controller contains the logic for permanently saved data .
* On load , it loads the saved files into the variables
2020-10-15 21:00:31 +02:00
* /
2020-10-16 11:23:32 +02:00
object StorageController {
2020-10-15 21:00:31 +02:00
private const val fileNameMyList = " my_list.json "
2020-10-16 19:56:08 +02:00
val myList = ArrayList < Int > ( ) // a list of saved mediaIds
2020-10-15 21:00:31 +02:00
fun load ( context : Context ) {
2021-05-26 19:46:46 +02:00
loadMyList ( context )
}
fun loadMyList ( context : Context ) {
2020-10-15 21:00:31 +02:00
val file = File ( context . filesDir , fileNameMyList )
if ( ! file . exists ( ) ) runBlocking { saveMyList ( context ) . join ( ) }
2020-11-14 13:10:05 +01:00
try {
myList . clear ( )
myList . addAll ( JsonParser . parseString ( file . readText ( ) ) . asJsonArray . map { it . asInt } . distinct ( ) )
} catch ( ex : Exception ) {
myList . clear ( )
Log . e ( javaClass . name , " Parsing of My-List failed. " )
}
2020-10-15 21:00:31 +02:00
}
fun saveMyList ( context : Context ) : Job {
val file = File ( context . filesDir , fileNameMyList )
2021-06-06 17:54:19 +02:00
return CoroutineScope ( Dispatchers . IO ) . launch {
2020-11-14 13:10:05 +01:00
file . writeText ( Gson ( ) . toJson ( myList . distinct ( ) ) )
2020-10-15 21:00:31 +02:00
}
}
2021-05-26 19:46:46 +02:00
fun exportMyList ( context : Context , uri : Uri ) {
try {
context . contentResolver . openFileDescriptor ( uri , " w " ) ?. use {
FileWriter ( it . fileDescriptor ) . use { writer ->
writer . write ( Gson ( ) . toJson ( myList . distinct ( ) ) )
}
}
} catch ( ex : Exception ) {
Log . e ( javaClass . name , " Exporting my list failed. " , ex )
}
}
/ * *
* import my list from a ( previously exported ) json file
* @param context the current context
* @param uri the uri of the selected file
* @return 0 if import was successfull , else 1
* /
fun importMyList ( context : Context , uri : Uri ) : Int {
try {
val text = context . contentResolver . openFileDescriptor ( uri , " r " ) ?. use {
FileReader ( it . fileDescriptor ) . use { reader ->
reader . readText ( )
}
}
myList . clear ( )
myList . addAll ( JsonParser . parseString ( text ) . asJsonArray . map { it . asInt } . distinct ( ) )
// after the list has been imported also save it
saveMyList ( context )
} catch ( ex : Exception ) {
myList . clear ( )
Log . e ( javaClass . name , " Importing my list failed. " , ex )
return 1
}
return 0
}
2020-10-15 21:00:31 +02:00
}