Skip to content

Commit

Permalink
update user on change
Browse files Browse the repository at this point in the history
  • Loading branch information
DatL4g committed Apr 28, 2024
1 parent 9985941 commit 2d88038
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 10 deletions.
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package dev.datlag.aniflow.anilist.model

import dev.datlag.aniflow.anilist.ViewerMutation
import dev.datlag.aniflow.anilist.ViewerQuery
import kotlinx.serialization.Serializable

Expand All @@ -19,6 +20,14 @@ data class User(
displayAdultContent = query.options?.displayAdultContent ?: false
)

constructor(mutation: ViewerMutation.UpdateUser) : this(
id = mutation.id,
name = mutation.name,
avatar = mutation.avatar.let(::Avatar),
banner = mutation.bannerImage?.ifBlank { null },
displayAdultContent = mutation.options?.displayAdultContent ?: false
)

@Serializable
data class Avatar(
val medium: String? = null,
Expand All @@ -28,5 +37,10 @@ data class User(
medium = query?.medium?.ifBlank { null },
large = query?.large?.ifBlank { null }
)

constructor(mutation: ViewerMutation.Avatar?) : this(
medium = mutation?.medium?.ifBlank { null },
large = mutation?.large?.ifBlank { null }
)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -24,19 +24,35 @@ class UserHelper(
) {

val isLoggedIn: Flow<Boolean> = userSettings.isAniListLoggedIn.distinctUntilChanged()
val user: Flow<User?> = isLoggedIn.transform { loggedIn ->

private val changedUser: MutableStateFlow<User?> = MutableStateFlow(null)
private val userQuery = client.query(ViewerQuery()).toFlow()
private val defaultUser = isLoggedIn.transform { loggedIn ->
if (loggedIn) {
emitAll(
client.query(ViewerQuery()).toFlow().map {
it.data?.Viewer?.let(::User)?.also { user ->
appSettings.setAdultContent(user.displayAdultContent)
}
userQuery.map {
it.data?.Viewer?.let(::User)
}
)
} else {
emit(null)
}
}
private val latestUser = defaultUser.transform { default ->
emit(default)
emitAll(changedUser.filterNotNull().map { changed ->
changedUser.update { null }
changed
})
}

val user = latestUser.transform { user ->
emit(
user?.also {
appSettings.setAdultContent(it.displayAdultContent)
}
)
}

suspend fun login(): Boolean {
if (isLoggedIn.safeFirstOrNull() == true) {
Expand All @@ -60,11 +76,13 @@ class UserHelper(

suspend fun updateAdultSetting(value: Boolean) {
appSettings.setAdultContent(value)
client.mutation(
ViewerMutation(
adult = Optional.present(value)
)
).execute()
changedUser.emit(
client.mutation(
ViewerMutation(
adult = Optional.present(value)
)
).execute().data?.UpdateUser?.let(::User)
)
}

private suspend fun updateStoredToken(tokenResponse: AccessTokenResponse) {
Expand Down

0 comments on commit 2d88038

Please sign in to comment.