Skip to content
This repository has been archived by the owner on Nov 12, 2024. It is now read-only.

Commit

Permalink
Fix crash from DB having multiple isMe users (#1929)
Browse files Browse the repository at this point in the history
  • Loading branch information
chrisbanes authored Jul 8, 2024
1 parent eac92ae commit f15dd49
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,14 @@
package app.tivi.data.daos

import app.cash.sqldelight.coroutines.asFlow
import app.cash.sqldelight.coroutines.mapToList
import app.cash.sqldelight.coroutines.mapToOneOrNull
import app.tivi.data.Database
import app.tivi.data.models.TraktUser
import app.tivi.util.AppCoroutineDispatchers
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.firstOrNull
import kotlinx.coroutines.flow.map
import me.tatarka.inject.annotations.Inject

@Inject
Expand Down Expand Up @@ -50,7 +53,8 @@ class SqlDelightUserDao(
override fun observeMe(): Flow<TraktUser?> {
return db.usersQueries.getEntryForMe(::TraktUser)
.asFlow()
.mapToOneOrNull(dispatchers.io)
.mapToList(dispatchers.io)
.map { it.firstOrNull() }
}

override fun observeTraktUser(username: String): Flow<TraktUser?> {
Expand All @@ -60,7 +64,11 @@ class SqlDelightUserDao(
}

override fun getUser(username: String): TraktUser? = when (username) {
"me" -> db.usersQueries.getEntryForMe(::TraktUser).executeAsOneOrNull()
"me" -> {
db.usersQueries.getEntryForMe(::TraktUser)
.executeAsList()
.firstOrNull()
}
else -> {
db.usersQueries.getEntryForUsername(username, ::TraktUser)
.executeAsOneOrNull()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ import app.tivi.inject.ApplicationScope
import app.tivi.util.AppCoroutineDispatchers
import app.tivi.util.Logger
import kotlin.time.Duration.Companion.hours
import kotlinx.coroutines.DelicateCoroutinesApi
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
Expand All @@ -19,7 +18,6 @@ import kotlinx.datetime.Clock
import kotlinx.datetime.Instant
import me.tatarka.inject.annotations.Inject

@OptIn(DelicateCoroutinesApi::class)
@ApplicationScope
@Inject
class TraktAuthRepository(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,10 @@ class TraktUsersRepository(
// Make sure we use the current DB id (if present)
transactionRunner {
val localUser = userDao.getUser(user.username)
if (user.isMe && localUser != null && localUser.isMe) {
// If we have a new `isMe` user, delete the current one
userDao.deleteMe()
}
if (localUser != null) {
user = user.copy(id = localUser.id)
}
Expand Down

0 comments on commit f15dd49

Please sign in to comment.