Convert BackupHelper and ImportHelper to objects.

This commit is contained in:
Isira Seneviratne 2023-02-03 18:55:12 +05:30
parent c05734d0fe
commit 423c257dd7
3 changed files with 36 additions and 53 deletions

View File

@ -24,20 +24,18 @@ import kotlinx.serialization.json.longOrNull
/** /**
* Backup and restore the preferences * Backup and restore the preferences
*/ */
class BackupHelper(private val context: Context) { object BackupHelper {
/** /**
* Write a [BackupFile] containing the database content as well as the preferences * Write a [BackupFile] containing the database content as well as the preferences
*/ */
@OptIn(ExperimentalSerializationApi::class) @OptIn(ExperimentalSerializationApi::class)
fun createAdvancedBackup(uri: Uri?, backupFile: BackupFile) { fun createAdvancedBackup(context: Context, uri: Uri, backupFile: BackupFile) {
uri?.let { try {
try { context.contentResolver.openOutputStream(uri)?.use { outputStream ->
context.contentResolver.openOutputStream(it)?.use { outputStream -> JsonHelper.json.encodeToStream(backupFile, outputStream)
JsonHelper.json.encodeToStream(backupFile, outputStream)
}
} catch (e: Exception) {
Log.e(TAG(), "Error while writing backup: $e")
} }
} catch (e: Exception) {
Log.e(TAG(), "Error while writing backup: $e")
} }
} }
@ -45,7 +43,7 @@ class BackupHelper(private val context: Context) {
* Restore data from a [BackupFile] * Restore data from a [BackupFile]
*/ */
@OptIn(ExperimentalSerializationApi::class) @OptIn(ExperimentalSerializationApi::class)
fun restoreAdvancedBackup(uri: Uri?) { fun restoreAdvancedBackup(context: Context, uri: Uri?) {
val backupFile = uri?.let { val backupFile = uri?.let {
context.contentResolver.openInputStream(it)?.use { inputStream -> context.contentResolver.openInputStream(it)?.use { inputStream ->
JsonHelper.json.decodeFromStream<BackupFile>(inputStream) JsonHelper.json.decodeFromStream<BackupFile>(inputStream)
@ -79,14 +77,14 @@ class BackupHelper(private val context: Context) {
} }
} }
restorePreferences(backupFile.preferences) restorePreferences(context, backupFile.preferences)
} }
} }
/** /**
* Restore the shared preferences from a backup file * Restore the shared preferences from a backup file
*/ */
private fun restorePreferences(preferences: List<PreferenceItem>?) { private fun restorePreferences(context: Context, preferences: List<PreferenceItem>?) {
if (preferences == null) return if (preferences == null) return
PreferenceManager.getDefaultSharedPreferences(context).edit(commit = true) { PreferenceManager.getDefaultSharedPreferences(context).edit(commit = true) {
// clear the previous settings // clear the previous settings

View File

@ -25,17 +25,15 @@ import kotlinx.serialization.json.decodeFromStream
import kotlinx.serialization.json.encodeToStream import kotlinx.serialization.json.encodeToStream
import okio.use import okio.use
class ImportHelper( object ImportHelper {
private val activity: Activity
) {
/** /**
* Import subscriptions by a file uri * Import subscriptions by a file uri
*/ */
fun importSubscriptions(uri: Uri?) { fun importSubscriptions(activity: Activity, uri: Uri?) {
if (uri == null) return if (uri == null) return
try { try {
val applicationContext = activity.applicationContext val applicationContext = activity.applicationContext
val channels = getChannelsFromUri(uri) val channels = getChannelsFromUri(activity, uri)
CoroutineScope(Dispatchers.IO).launch { CoroutineScope(Dispatchers.IO).launch {
SubscriptionHelper.importSubscriptions(channels) SubscriptionHelper.importSubscriptions(channels)
}.invokeOnCompletion { }.invokeOnCompletion {
@ -56,7 +54,7 @@ class ImportHelper(
/** /**
* Get a list of channel IDs from a file [Uri] * Get a list of channel IDs from a file [Uri]
*/ */
private fun getChannelsFromUri(uri: Uri): List<String> { private fun getChannelsFromUri(activity: Activity, uri: Uri): List<String> {
return when (val fileType = activity.contentResolver.getType(uri)) { return when (val fileType = activity.contentResolver.getType(uri)) {
"application/json", "application/*", "application/octet-stream" -> { "application/json", "application/*", "application/octet-stream" -> {
// NewPipe subscriptions format // NewPipe subscriptions format
@ -85,7 +83,7 @@ class ImportHelper(
* Write the text to the document * Write the text to the document
*/ */
@OptIn(ExperimentalSerializationApi::class) @OptIn(ExperimentalSerializationApi::class)
fun exportSubscriptions(uri: Uri?) { fun exportSubscriptions(activity: Activity, uri: Uri?) {
if (uri == null) return if (uri == null) return
runBlocking(Dispatchers.IO) { runBlocking(Dispatchers.IO) {
val token = PreferenceHelper.getToken() val token = PreferenceHelper.getToken()
@ -112,7 +110,7 @@ class ImportHelper(
* Import Playlists * Import Playlists
*/ */
@OptIn(ExperimentalSerializationApi::class) @OptIn(ExperimentalSerializationApi::class)
fun importPlaylists(uri: Uri?) { fun importPlaylists(activity: Activity, uri: Uri?) {
if (uri == null) return if (uri == null) return
val importPlaylists = mutableListOf<ImportPlaylist>() val importPlaylists = mutableListOf<ImportPlaylist>()
@ -164,7 +162,7 @@ class ImportHelper(
/** /**
* Export Playlists * Export Playlists
*/ */
fun exportPlaylists(uri: Uri?) { fun exportPlaylists(activity: Activity, uri: Uri?) {
if (uri == null) return if (uri == null) return
runBlocking { runBlocking {

View File

@ -1,6 +1,5 @@
package com.github.libretube.ui.preferences package com.github.libretube.ui.preferences
import android.net.Uri
import android.os.Bundle import android.os.Bundle
import androidx.activity.result.ActivityResultLauncher import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts import androidx.activity.result.contract.ActivityResultContracts
@ -38,39 +37,23 @@ class BackupRestoreSettings : BasePreferenceFragment() {
private lateinit var createPlaylistsFile: ActivityResultLauncher<String> private lateinit var createPlaylistsFile: ActivityResultLauncher<String>
override fun onCreate(savedInstanceState: Bundle?) { override fun onCreate(savedInstanceState: Bundle?) {
getSubscriptionsFile = getSubscriptionsFile = registerForActivityResult(ActivityResultContracts.GetContent()) {
registerForActivityResult( ImportHelper.importSubscriptions(requireActivity(), it)
ActivityResultContracts.GetContent()
) { uri ->
ImportHelper(requireActivity()).importSubscriptions(uri)
}
createSubscriptionsFile = registerForActivityResult(
CreateDocument("application/json")
) { uri ->
ImportHelper(requireActivity()).exportSubscriptions(uri)
} }
createSubscriptionsFile = registerForActivityResult(CreateDocument(JSON)) {
getPlaylistsFile = registerForActivityResult(ActivityResultContracts.GetContent()) { uri -> ImportHelper.exportSubscriptions(requireActivity(), it)
ImportHelper(requireActivity()).importPlaylists(uri)
} }
getPlaylistsFile = registerForActivityResult(ActivityResultContracts.GetContent()) {
createPlaylistsFile = registerForActivityResult( ImportHelper.importPlaylists(requireActivity(), it)
CreateDocument("application/json")
) { uri ->
ImportHelper(requireActivity()).exportPlaylists(uri)
} }
createPlaylistsFile = registerForActivityResult(CreateDocument(JSON)) {
getBackupFile = ImportHelper.exportPlaylists(requireActivity(), it)
registerForActivityResult( }
ActivityResultContracts.GetContent() getBackupFile = registerForActivityResult(ActivityResultContracts.GetContent()) {
) { uri: Uri? -> BackupHelper.restoreAdvancedBackup(requireContext(), it)
BackupHelper(requireContext()).restoreAdvancedBackup(uri) }
} createBackupFile = registerForActivityResult(CreateDocument(JSON)) {
BackupHelper.createAdvancedBackup(requireContext(), it, backupFile)
createBackupFile = registerForActivityResult(
CreateDocument("application/json")
) { uri: Uri? ->
BackupHelper(requireContext()).createAdvancedBackup(uri, backupFile)
} }
super.onCreate(savedInstanceState) super.onCreate(savedInstanceState)
@ -116,8 +99,12 @@ class BackupRestoreSettings : BasePreferenceFragment() {
val restoreAdvancedBackup = findPreference<Preference>("restore") val restoreAdvancedBackup = findPreference<Preference>("restore")
restoreAdvancedBackup?.setOnPreferenceClickListener { restoreAdvancedBackup?.setOnPreferenceClickListener {
getBackupFile.launch("application/json") getBackupFile.launch(JSON)
true true
} }
} }
companion object {
private const val JSON = "application/json"
}
} }