Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package com.cornellappdev.score.auth

import com.cornellappdev.score.model.OnboardingPreferencesRepository
import javax.inject.Inject
import javax.inject.Singleton
import kotlinx.coroutines.CancellationException
Expand All @@ -11,7 +12,11 @@ import kotlinx.coroutines.sync.withLock
@Singleton
class AuthRepository
@Inject
constructor(private val api: AuthApi, private val storage: SessionStorage) {
constructor(
private val api: AuthApi,
private val storage: SessionStorage,
private val preferences: OnboardingPreferencesRepository,
) {
private val mutex = Mutex()
private val mutableState = MutableStateFlow<AuthState>(AuthState.Loading)
val state = mutableState.asStateFlow()
Expand Down Expand Up @@ -117,6 +122,7 @@ constructor(private val api: AuthApi, private val storage: SessionStorage) {

private suspend fun clearSession() {
storage.clear()
preferences.clearAccountPreferences()
session = null
restored = true
publishState()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,7 @@ private fun HighlightsFilterButton(
fun HighlightsFilterRow(
sportList: List<Sport>,
onFilterSelected: (Sport) -> Unit,
selectedSport: Sport? = null,
) {
LazyRow(
modifier = Modifier
Expand All @@ -78,7 +79,7 @@ fun HighlightsFilterRow(
) {
item { Spacer(Modifier.width(12.dp)) }
items(sportList) { item ->
HighlightsFilterButton(item, onFilterSelected)
HighlightsFilterButton(item, onFilterSelected, item == selectedSport)
}
item { Spacer(Modifier.width(12.dp)) }
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import com.apollographql.apollo.api.ApolloResponse
import com.apollographql.apollo.api.Operation
import com.apollographql.apollo.api.http.HttpHeader
import com.cornellappdev.score.auth.AuthRepository
import com.cornellappdev.score.auth.AuthState
import com.example.score.AccountProfileQuery
import com.example.score.AddBookmarkedHighlightMutation
import com.example.score.AddFavoriteTeamMutation
Expand All @@ -28,6 +29,7 @@ constructor(
private val preferences: OnboardingPreferencesRepository,
) {
private val favoritesMutex = Mutex()
private var syncedAccountId: String? = null

suspend fun profile(): ProfileData {
val result = client.query(AccountProfileQuery()).httpHeaders(headers()).execute().checked()
Expand All @@ -43,10 +45,10 @@ constructor(
}
ProfileFavorite(sport, gender)
}
preferences.saveFavoriteSports(favorites.toSet())

return ProfileData(
name = data.me.name.orEmpty(),
favorites = favorites,
favorites = favorites.filter { it.isAvailable },
bookmarks =
data.myBookmarkedHighlights.orEmpty().filterNotNull().mapNotNull {
it.accountHighlight.toHighlight()
Expand All @@ -55,40 +57,66 @@ constructor(
)
}

suspend fun syncFavorites(): ProfileData = favoritesMutex.withLock {
val accountId = (auth.state.value as? AuthState.SignedIn)?.user?.id
?: error("Sign in to sync favorites")
val remote = profile()
check((auth.state.value as? AuthState.SignedIn)?.user?.id == accountId)
if (syncedAccountId == accountId) {
preferences.saveFavoriteSports(remote.favorites.toSet())
return@withLock remote
}
val combined = (preferences.getFavoriteSports() + remote.favorites).filter { it.isAvailable }.toSet()
// Keep the union locally even if the network fails, so the next refresh retries it.
preferences.saveFavoriteSports(combined)
writeFavorites(remote.favorites.toSet(), combined)
syncedAccountId = accountId
remote.copy(favorites = combined.toList())
}

fun resetFavoriteSync() {
syncedAccountId = null
}

// Read the server first so retries and partially completed saves converge to the chosen set.
suspend fun saveFavorites(favorites: Set<ProfileFavorite>) =
favoritesMutex.withLock {
val available = favorites.filter { it.isAvailable }.toSet()
val current = profile().favorites.toSet()
for (favorite in current - favorites) {
val response =
client
.mutation(
RemoveFavoriteTeamMutation(
favorite.backendGender,
favorite.sport.backendName,
)
writeFavorites(current, available)
preferences.saveFavoriteSports(available)
}

private suspend fun writeFavorites(current: Set<ProfileFavorite>, favorites: Set<ProfileFavorite>) {
for (favorite in current - favorites) {
val response =
client
.mutation(
RemoveFavoriteTeamMutation(
favorite.backendGender,
favorite.sport.backendName,
)
.httpHeaders(headers())
.execute()
.checked()
check(response.data?.removeFavoriteTeam?.success == true)
}
for (favorite in favorites - current) {
val response =
client
.mutation(
AddFavoriteTeamMutation(
favorite.backendGender,
favorite.sport.backendName,
)
)
.httpHeaders(headers())
.execute()
.checked()
check(response.data?.removeFavoriteTeam?.success == true)
}
for (favorite in favorites - current) {
val response =
client
.mutation(
AddFavoriteTeamMutation(
favorite.backendGender,
favorite.sport.backendName,
)
.httpHeaders(headers())
.execute()
.checked()
check(response.data?.addFavoriteTeam?.success == true)
}
preferences.saveFavoriteSports(favorites)
)
.httpHeaders(headers())
.execute()
.checked()
check(response.data?.addFavoriteTeam?.success == true)
}
}

suspend fun highlights(): List<HighlightData> =
client
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,16 +6,20 @@ import dagger.hilt.android.qualifiers.ApplicationContext
import javax.inject.Inject
import javax.inject.Singleton
import androidx.core.content.edit
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow

@Singleton
class OnboardingPreferencesRepository @Inject constructor(
@ApplicationContext context: Context
class OnboardingPreferencesRepository internal constructor(
private val preferences: SharedPreferences
) {
private val preferences: SharedPreferences = context.getSharedPreferences(
PREFERENCES_NAME,
Context.MODE_PRIVATE
@Inject constructor(@ApplicationContext context: Context) : this(
context.getSharedPreferences(PREFERENCES_NAME, Context.MODE_PRIVATE)
)

private val mutableFavorites = MutableStateFlow(getFavoriteSports())
val favorites = mutableFavorites.asStateFlow()

fun isOnboardingCompleted(): Boolean =
preferences.getBoolean(KEY_ONBOARDING_COMPLETED, false)

Expand All @@ -30,14 +34,17 @@ class OnboardingPreferencesRepository @Inject constructor(
?: preferences.getStringSet("favorite_sports", emptySet()))
.orEmpty()
.mapNotNull { ProfileFavorite.fromStorageKey(it) }
.filter { it.isAvailable }
.toSet()

fun getFavoriteSportNames(): Set<String> = getFavoriteSports().map { it.sport.name }.toSet()

fun saveFavoriteSports(favorites: Set<ProfileFavorite>) {
val available = favorites.filter { it.isAvailable }.toSet()
preferences.edit {
putStringSet(KEY_ONBOARDING_FAVORITE_SPORTS, favorites.map { it.storageKey }.toSet())
putStringSet(KEY_ONBOARDING_FAVORITE_SPORTS, available.map { it.storageKey }.toSet())
}
mutableFavorites.value = available
}

fun getProfilePicture(): String? =
Expand All @@ -55,6 +62,7 @@ class OnboardingPreferencesRepository @Inject constructor(
remove("favorite_sports")
remove(KEY_ONBOARDING_PROFILE_PICTURE)
}
mutableFavorites.value = emptySet()
}

private companion object {
Expand Down
21 changes: 21 additions & 0 deletions app/src/main/java/com/cornellappdev/score/model/Profile.kt
Original file line number Diff line number Diff line change
Expand Up @@ -24,3 +24,24 @@ data class ProfileFavorite(val sport: Sport, val gender: GenderDivision) {
}
}
}

val availableFavoriteSports = setOf(
Sport.BASKETBALL, Sport.ICE_HOCKEY, Sport.LACROSSE, Sport.SOCCER,
Sport.FIELD_HOCKEY, Sport.BASEBALL, Sport.FOOTBALL
)

val ProfileFavorite.isAvailable: Boolean
get() = sport in availableFavoriteSports &&
gender in listOf(GenderDivision.MALE, GenderDivision.FEMALE) &&
(sport.gender == GenderDivision.ALL || sport.gender == gender)

fun favoriteSelections(
selections: List<SportSelection>, gender: GenderDivision, favorites: Set<ProfileFavorite>
): List<SportSelection> = selections.filter {
gender != GenderDivision.FAVORITES || favorites.isEmpty() ||
it is SportSelection.All ||
(it is SportSelection.SportSelect && favorites.any { favorite -> favorite.sport == it.sport })
}

fun Set<ProfileFavorite>.matchesTeam(sport: String, gender: String): Boolean =
any { it.sport.displayName == sport && it.gender.displayName == gender }
12 changes: 11 additions & 1 deletion app/src/main/java/com/cornellappdev/score/nav/ScoreNavHost.kt
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
package com.cornellappdev.score.nav

import GameScoreSummaryScreenDetail
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.setValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.hilt.lifecycle.viewmodel.compose.hiltViewModel
Expand Down Expand Up @@ -36,14 +41,19 @@ fun ScoreNavHost(
// everytime you switch tabs.
val mainScreenViewModelStoreOwner = checkNotNull(LocalViewModelStoreOwner.current)

var welcomeDismissed by rememberSaveable(welcomeName) { mutableStateOf(false) }

NavHost(
navController = navController,
startDestination = Home
) {
composable<Home> {
DisposableEffect(Unit) {
onDispose { welcomeDismissed = true }
}
CompositionLocalProvider(LocalViewModelStoreOwner provides mainScreenViewModelStoreOwner) {
HomeScreen(
welcomeName = welcomeName,
welcomeName = welcomeName.takeUnless { welcomeDismissed },
navigateToGameDetails = {
navController.navigate(ScoreScreens.GameDetailsPage(it))
},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -161,18 +161,18 @@ val tabs = listOf(
selectedIcon = R.drawable.ic_schedule_filled,
screen = ScoreScreens.Home,
),
NavItem(
label = "Scores",
unselectedIcon = R.drawable.ic_scores,
selectedIcon = R.drawable.ic_scores_filled,
screen = ScoreScreens.ScoresScreen,
),
NavItem(
label = "Highlights",
unselectedIcon = R.drawable.ic_nav_star,
selectedIcon = R.drawable.ic_nav_star_filled,
screen = ScoreScreens.HighlightsScreen,
),
NavItem(
label = "Scores",
unselectedIcon = R.drawable.ic_scores,
selectedIcon = R.drawable.ic_scores_filled,
screen = ScoreScreens.ScoresScreen,
),
NavItem(
label = "Profile",
unselectedIcon = R.drawable.profile_person,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Icon
import androidx.compose.material3.Text
import com.cornellappdev.score.model.isAvailable
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
Expand Down Expand Up @@ -64,10 +65,10 @@ internal val favoriteSportComparator = compareBy<ProfileFavorite>(
internal fun selectedFavoritesFirst(favorites: List<ProfileFavorite>): Comparator<ProfileFavorite> =
compareBy<ProfileFavorite> { it !in favorites }.then(favoriteSportComparator)

// Use the complete icon catalog, independent of sports with games in the current season.
internal val favoriteSportOptions = Sport.entries.flatMap { sport ->
// The profile design includes both golf divisions, unlike the schedule catalog.
val divisions = if (sport.gender == GenderDivision.ALL || sport == Sport.GOLF) {
// Only offer supported teams.
internal val favoriteSportOptions = Sport.entries.filter { it in com.cornellappdev.score.model.availableFavoriteSports }.flatMap { sport ->
// Shared sports have separate men’s and women’s teams.
val divisions = if (sport.gender == GenderDivision.ALL) {
listOf(GenderDivision.MALE, GenderDivision.FEMALE)
} else listOf(sport.gender)
divisions.map { ProfileFavorite(sport, it) }
Expand All @@ -81,7 +82,7 @@ fun EditFavoriteSportsScreen(
modifier: Modifier = Modifier
) {
var gender by rememberSaveable { mutableStateOf(GenderDivision.ALL) }
val options = (favorites + favoriteSportOptions).distinct()
val options = (favorites + favoriteSportOptions).filter { it.isAvailable }.distinct()
.filter { gender == GenderDivision.ALL || it.gender == gender }
.sortedWith(selectedFavoritesFirst(favorites))

Expand Down
Loading