Merge pull request #2842 from Isira-Seneviratne/LocalSubscriptionDao_suspend

Use suspend functions in LocalSubscriptionDao.
This commit is contained in:
Bnyro 2023-01-24 19:53:48 +01:00 committed by GitHub
commit 68f87c56aa
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
8 changed files with 79 additions and 116 deletions

View File

@ -10,55 +10,40 @@ import com.github.libretube.constants.PreferenceKeys
import com.github.libretube.db.DatabaseHolder.Companion.Database
import com.github.libretube.db.obj.LocalSubscription
import com.github.libretube.extensions.TAG
import com.github.libretube.extensions.awaitQuery
import com.github.libretube.extensions.query
import com.github.libretube.util.PreferenceHelper
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withContext
object SubscriptionHelper {
fun subscribe(channelId: String) {
if (PreferenceHelper.getToken() != "") {
CoroutineScope(Dispatchers.IO).launch {
try {
RetrofitInstance.authApi.subscribe(
PreferenceHelper.getToken(),
Subscribe(channelId)
)
} catch (e: Exception) {
Log.e(TAG(), e.toString())
suspend fun subscribe(channelId: String) {
val token = PreferenceHelper.getToken()
if (token.isNotEmpty()) {
try {
withContext(Dispatchers.IO) {
RetrofitInstance.authApi.subscribe(token, Subscribe(channelId))
}
} catch (e: Exception) {
Log.e(TAG(), e.toString())
}
} else {
query {
Database.localSubscriptionDao().insertAll(
LocalSubscription(channelId)
)
}
Database.localSubscriptionDao().insertAll(listOf(LocalSubscription(channelId)))
}
}
fun unsubscribe(channelId: String) {
if (PreferenceHelper.getToken() != "") {
CoroutineScope(Dispatchers.IO).launch {
try {
RetrofitInstance.authApi.unsubscribe(
PreferenceHelper.getToken(),
Subscribe(channelId)
)
} catch (e: Exception) {
Log.e(TAG(), e.toString())
suspend fun unsubscribe(channelId: String) {
val token = PreferenceHelper.getToken()
if (token.isNotEmpty()) {
try {
withContext(Dispatchers.IO) {
RetrofitInstance.authApi.unsubscribe(token, Subscribe(channelId))
}
} catch (e: Exception) {
Log.e(TAG(), e.toString())
}
} else {
query {
Database.localSubscriptionDao().delete(
LocalSubscription(channelId)
)
}
Database.localSubscriptionDao().delete(LocalSubscription(channelId))
}
}
@ -69,8 +54,10 @@ object SubscriptionHelper {
onUnsubscribe: () -> Unit
) {
if (!PreferenceHelper.getBoolean(PreferenceKeys.CONFIRM_UNSUBSCRIBE, false)) {
unsubscribe(channelId)
onUnsubscribe.invoke()
runBlocking {
unsubscribe(channelId)
onUnsubscribe()
}
return
}
@ -78,89 +65,63 @@ object SubscriptionHelper {
.setTitle(R.string.unsubscribe)
.setMessage(context.getString(R.string.confirm_unsubscribe, channelName))
.setPositiveButton(R.string.unsubscribe) { _, _ ->
unsubscribe(channelId)
onUnsubscribe.invoke()
runBlocking {
unsubscribe(channelId)
onUnsubscribe()
}
}
.setNegativeButton(R.string.cancel, null)
.show()
}
suspend fun isSubscribed(channelId: String): Boolean? {
if (PreferenceHelper.getToken() != "") {
val token = PreferenceHelper.getToken()
if (token.isNotEmpty()) {
val isSubscribed = try {
RetrofitInstance.authApi.isSubscribed(
channelId,
PreferenceHelper.getToken()
)
RetrofitInstance.authApi.isSubscribed(channelId, token)
} catch (e: Exception) {
Log.e(TAG(), e.toString())
return null
}
return isSubscribed.subscribed
} else {
return awaitQuery {
Database.localSubscriptionDao().includes(channelId)
}
return Database.localSubscriptionDao().includes(channelId)
}
}
suspend fun importSubscriptions(newChannels: List<String>) {
if (PreferenceHelper.getToken() != "") {
val token = PreferenceHelper.getToken()
if (token.isNotEmpty()) {
try {
val token = PreferenceHelper.getToken()
RetrofitInstance.authApi.importSubscriptions(
false,
token,
newChannels
)
RetrofitInstance.authApi.importSubscriptions(false, token, newChannels)
} catch (e: Exception) {
e.printStackTrace()
}
} else {
val newLocalSubscriptions = mutableListOf<LocalSubscription>()
newChannels.forEach {
newLocalSubscriptions += LocalSubscription(channelId = it)
}
query {
Database.localSubscriptionDao().insertAll(
*newChannels.map { LocalSubscription(it) }.toTypedArray()
)
}
Database.localSubscriptionDao().insertAll(newChannels.map { LocalSubscription(it) })
}
}
private fun getLocalSubscriptions(): List<LocalSubscription> {
return awaitQuery {
Database.localSubscriptionDao().getAll()
}
}
fun getFormattedLocalSubscriptions(): String {
val localSubscriptions = getLocalSubscriptions()
return localSubscriptions.joinToString(",") { it.channelId }
suspend fun getFormattedLocalSubscriptions(): String {
return Database.localSubscriptionDao().getAll()
.joinToString(",") { it.channelId }
}
suspend fun getSubscriptions(): List<Subscription> {
return if (PreferenceHelper.getToken() != "") {
RetrofitInstance.authApi.subscriptions(
PreferenceHelper.getToken()
)
val token = PreferenceHelper.getToken()
return if (token.isNotEmpty()) {
RetrofitInstance.authApi.subscriptions(token)
} else {
RetrofitInstance.authApi.unauthenticatedSubscriptions(
getFormattedLocalSubscriptions()
)
RetrofitInstance.authApi.unauthenticatedSubscriptions(getFormattedLocalSubscriptions())
}
}
suspend fun getFeed(): List<StreamItem> {
return if (PreferenceHelper.getToken() != "") {
RetrofitInstance.authApi.getFeed(
PreferenceHelper.getToken()
)
val token = PreferenceHelper.getToken()
return if (token.isNotEmpty()) {
RetrofitInstance.authApi.getFeed(token)
} else {
RetrofitInstance.authApi.getUnauthenticatedFeed(
getFormattedLocalSubscriptions()
)
RetrofitInstance.authApi.getUnauthenticatedFeed(getFormattedLocalSubscriptions())
}
}
}

View File

@ -10,20 +10,14 @@ import com.github.libretube.db.obj.LocalSubscription
@Dao
interface LocalSubscriptionDao {
@Query("SELECT * FROM localSubscription")
fun getAll(): List<LocalSubscription>
@Query("SELECT * FROM localSubscription WHERE channelId LIKE :channelId LIMIT 1")
fun findById(channelId: String): LocalSubscription
suspend fun getAll(): List<LocalSubscription>
@Insert(onConflict = OnConflictStrategy.REPLACE)
fun insertAll(vararg localSubscriptions: LocalSubscription)
suspend fun insertAll(localSubscriptions: List<LocalSubscription>)
@Delete
fun delete(localSubscription: LocalSubscription)
@Query("DELETE FROM localSubscription")
fun deleteAll()
suspend fun delete(localSubscription: LocalSubscription)
@Query("SELECT EXISTS(SELECT * FROM localSubscription WHERE channelId = :channelId)")
fun includes(channelId: String): Boolean
suspend fun includes(channelId: String): Boolean
}

View File

@ -4,20 +4,25 @@ import android.app.Dialog
import android.os.Bundle
import androidx.annotation.StringRes
import androidx.fragment.app.DialogFragment
import androidx.lifecycle.lifecycleScope
import com.github.libretube.R
import com.github.libretube.db.DatabaseHolder.Companion.Database
import com.github.libretube.extensions.awaitQuery
import com.github.libretube.obj.BackupFile
import com.github.libretube.obj.PreferenceItem
import com.github.libretube.util.PreferenceHelper
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.serialization.json.JsonNull
import kotlinx.serialization.json.JsonPrimitive
class BackupDialog(
private val createBackupFile: (BackupFile) -> Unit
) : DialogFragment() {
sealed class BackupOption(@StringRes val name: Int, val onSelected: (BackupFile) -> Unit) {
sealed class BackupOption(
@StringRes val name: Int,
val onSelected: suspend (BackupFile) -> Unit
) {
object WatchHistory : BackupOption(R.string.watch_history, onSelected = {
it.watchHistory = Database.watchHistoryDao().getAll()
})
@ -83,9 +88,9 @@ class BackupDialog(
.setNegativeButton(R.string.cancel, null)
.setPositiveButton(R.string.backup) { _, _ ->
val backupFile = BackupFile()
awaitQuery {
lifecycleScope.launch(Dispatchers.IO) {
backupOptions.forEachIndexed { index, option ->
if (selected[index]) option.onSelected.invoke(backupFile)
if (selected[index]) option.onSelected(backupFile)
}
}
createBackupFile(backupFile)

View File

@ -8,6 +8,7 @@ import com.google.android.material.button.MaterialButton
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withContext
fun TextView.setupSubscriptionButton(
@ -42,10 +43,12 @@ fun TextView.setupSubscriptionButton(
subscribed = false
}
} else {
SubscriptionHelper.subscribe(channelId)
this.text = context.getString(R.string.unsubscribe)
notificationBell?.visibility = View.VISIBLE
subscribed = true
runBlocking {
SubscriptionHelper.subscribe(channelId)
text = context.getString(R.string.unsubscribe)
notificationBell?.visibility = View.VISIBLE
subscribed = true
}
}
}
}

View File

@ -3,13 +3,13 @@ package com.github.libretube.ui.models
import android.util.Log
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.github.libretube.api.SubscriptionHelper
import com.github.libretube.api.obj.StreamItem
import com.github.libretube.api.obj.Subscription
import com.github.libretube.extensions.TAG
import com.github.libretube.extensions.toID
import com.github.libretube.util.PreferenceHelper
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
@ -27,7 +27,7 @@ class SubscriptionsViewModel : ViewModel() {
}
fun fetchFeed() {
CoroutineScope(Dispatchers.IO).launch {
viewModelScope.launch(Dispatchers.IO) {
val videoFeed = try {
SubscriptionHelper.getFeed()
} catch (e: Exception) {
@ -44,7 +44,7 @@ class SubscriptionsViewModel : ViewModel() {
}
fun fetchSubscriptions() {
CoroutineScope(Dispatchers.IO).launch {
viewModelScope.launch(Dispatchers.IO) {
val subscriptions = try {
SubscriptionHelper.getSubscriptions()
} catch (e: Exception) {

View File

@ -9,9 +9,10 @@ import com.github.libretube.api.JsonHelper
import com.github.libretube.constants.PreferenceKeys
import com.github.libretube.db.DatabaseHolder.Companion.Database
import com.github.libretube.extensions.TAG
import com.github.libretube.extensions.query
import com.github.libretube.obj.BackupFile
import com.github.libretube.obj.PreferenceItem
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.runBlocking
import kotlinx.serialization.json.booleanOrNull
import kotlinx.serialization.json.decodeFromStream
import kotlinx.serialization.json.encodeToStream
@ -48,7 +49,7 @@ class BackupHelper(private val context: Context) {
}
} ?: return
query {
runBlocking(Dispatchers.IO) {
Database.watchHistoryDao().insertAll(
*backupFile.watchHistory.orEmpty().toTypedArray()
)
@ -58,9 +59,7 @@ class BackupHelper(private val context: Context) {
Database.watchPositionDao().insertAll(
*backupFile.watchPositions.orEmpty().toTypedArray()
)
Database.localSubscriptionDao().insertAll(
*backupFile.localSubscriptions.orEmpty().toTypedArray()
)
Database.localSubscriptionDao().insertAll(backupFile.localSubscriptions.orEmpty())
Database.customInstanceDao().insertAll(
*backupFile.customInstances.orEmpty().toTypedArray()
)

View File

@ -84,9 +84,10 @@ class ImportHelper(
*/
fun exportSubscriptions(uri: Uri?) {
if (uri == null) return
runBlocking {
val subs = if (PreferenceHelper.getToken() != "") {
RetrofitInstance.authApi.subscriptions(PreferenceHelper.getToken())
runBlocking(Dispatchers.IO) {
val token = PreferenceHelper.getToken()
val subs = if (token.isNotEmpty()) {
RetrofitInstance.authApi.subscriptions(token)
} else {
RetrofitInstance.authApi.unauthenticatedSubscriptions(
SubscriptionHelper.getFormattedLocalSubscriptions()

View File

@ -45,7 +45,7 @@ square-leakcanary = { group = "com.squareup.leakcanary", name = "leakcanary-andr
lifecycle-viewmodel = { group = "androidx.lifecycle", name = "lifecycle-viewmodel-ktx", version.ref = "lifecycle" }
lifecycle-runtime = { group = "androidx.lifecycle", name = "lifecycle-runtime-ktx", version.ref = "lifecycle" }
lifecycle-livedata = { group = "androidx.lifecycle", name = "lifecycle-livedata-ktx", version.ref = "lifecycle" }
room = { group = "androidx.room", name="room-runtime", version.ref = "room" }
room = { group = "androidx.room", name="room-ktx", version.ref = "room" }
room-compiler = { group = "androidx.room", name = "room-compiler", version.ref = "room" }
kotlinx-serialization = { group = "org.jetbrains.kotlinx", name = "kotlinx-serialization-json", version.ref = "kotlinxSerialization" }
kotlinx-datetime = { group = "org.jetbrains.kotlinx", name = "kotlinx-datetime", version.ref = "kotlinxDatetime" }