hub: track each game's daily-puzzle streak (#567)
- Commit
18006eb4f8017b5c15b8a046d827b4f594ad3530- Author
- vayun-mathur <[email protected]>
- When
- 2026-08-23 15:00 UTC (3 months ago)
- Parents
6ac0d9a
Diff
games/hub/src/main/java/com/vayunmathur/games/hub/data/GamesHubDatabase.kt
diff --git a/games/hub/src/main/java/com/vayunmathur/games/hub/data/GamesHubDatabase.kt b/games/hub/src/main/java/com/vayunmathur/games/hub/data/GamesHubDatabase.ktindex 58c63dbfad..3095dc99dc 100644--- a/games/hub/src/main/java/com/vayunmathur/games/hub/data/GamesHubDatabase.kt+++ b/games/hub/src/main/java/com/vayunmathur/games/hub/data/GamesHubDatabase.kt@@ -2,17 +2,21 @@ package com.vayunmathur.games.hub.data import androidx.room.Database import androidx.room.RoomDatabase+import androidx.room.migration.Migration import com.vayunmathur.games.hub.data.dao.ActivityDao import com.vayunmathur.games.hub.data.dao.AchievementDao import com.vayunmathur.games.hub.data.dao.GameDao import com.vayunmathur.games.hub.data.dao.ProfileDao import com.vayunmathur.games.hub.data.dao.SessionDao+import com.vayunmathur.games.hub.data.dao.StreakDao import com.vayunmathur.games.hub.data.entities.AchievementDefEntity import com.vayunmathur.games.hub.data.entities.AchievementProgressEntity import com.vayunmathur.games.hub.data.entities.ActivityEventEntity+import com.vayunmathur.games.hub.data.entities.DailyStreakEntity import com.vayunmathur.games.hub.data.entities.HubGameEntity import com.vayunmathur.games.hub.data.entities.PlaySessionEntity import com.vayunmathur.games.hub.data.entities.PlayerProfileEntity+import com.vayunmathur.library.util.DatabaseMigrations const val DB_NAME = "games-hub-db" @@ -23,9 +27,10 @@ const val DB_NAME = "games-hub-db" AchievementProgressEntity::class, PlaySessionEntity::class, PlayerProfileEntity::class,- ActivityEventEntity::class+ ActivityEventEntity::class,+ DailyStreakEntity::class ],- version = 1,+ version = 2, exportSchema = false ) abstract class GamesHubDatabase : RoomDatabase() {@@ -34,4 +39,23 @@ abstract class GamesHubDatabase : RoomDatabase() { abstract fun sessionDao(): SessionDao abstract fun profileDao(): ProfileDao abstract fun activityDao(): ActivityDao+ abstract fun streakDao(): StreakDao++ companion object : DatabaseMigrations {+ override val migrations: List<Migration> = listOf(+ // Per-game daily-puzzle streaks. Schemas aren't exported here, so this DDL is written+ // to byte-match what Room generates for DailyStreakEntity — Room validates it on open.+ Migration(1, 2) { db ->+ db.execSQL(+ "CREATE TABLE IF NOT EXISTS `daily_streaks` (" ++ "`gameId` TEXT NOT NULL, " ++ "`currentStreak` INTEGER NOT NULL, " ++ "`longestStreak` INTEGER NOT NULL, " ++ "`lastCompletedDay` INTEGER NOT NULL, " ++ "`lastUpdated` INTEGER NOT NULL, " ++ "PRIMARY KEY(`gameId`))",+ )+ },+ )+ } }
games/hub/src/main/java/com/vayunmathur/games/hub/data/GamesHubRepository.kt
diff --git a/games/hub/src/main/java/com/vayunmathur/games/hub/data/GamesHubRepository.kt b/games/hub/src/main/java/com/vayunmathur/games/hub/data/GamesHubRepository.ktindex 42bdf7ad11..f5908c5219 100644--- a/games/hub/src/main/java/com/vayunmathur/games/hub/data/GamesHubRepository.kt+++ b/games/hub/src/main/java/com/vayunmathur/games/hub/data/GamesHubRepository.kt@@ -5,6 +5,7 @@ import com.vayunmathur.games.hub.data.dao.AchievementWithProgress import com.vayunmathur.games.hub.data.entities.AchievementDefEntity import com.vayunmathur.games.hub.data.entities.AchievementProgressEntity import com.vayunmathur.games.hub.data.entities.ActivityEventEntity+import com.vayunmathur.games.hub.data.entities.DailyStreakEntity import com.vayunmathur.games.hub.data.entities.HubGameEntity import com.vayunmathur.games.hub.data.entities.PlaySessionEntity import com.vayunmathur.games.hub.data.entities.PlayerProfileEntity@@ -22,6 +23,7 @@ class GamesHubRepository private constructor(context: Context) : private val sessionDao get() = db.sessionDao() private val profileDao get() = db.profileDao() private val activityDao get() = db.activityDao()+ private val streakDao get() = db.streakDao() val database: GamesHubDatabase get() = db @@ -78,6 +80,16 @@ class GamesHubRepository private constructor(context: Context) : fun totalPlaytimeSessionsFlow(): Flow<Long> = sessionDao.flowTotalPlaytimeMs() suspend fun clearSessions() = sessionDao.clearAll() + // ------------------------------------------------------------------+ // StreakDao+ // ------------------------------------------------------------------++ suspend fun upsertStreak(streak: DailyStreakEntity) = streakDao.upsert(streak)+ suspend fun getStreak(gameId: String): DailyStreakEntity? = streakDao.getByGame(gameId)+ fun streakByGameFlow(gameId: String): Flow<DailyStreakEntity?> = streakDao.flowByGame(gameId)+ fun allStreaksFlow(): Flow<List<DailyStreakEntity>> = streakDao.flowAll()+ suspend fun clearStreaks() = streakDao.clearAll()+ // ------------------------------------------------------------------ // ProfileDao // ------------------------------------------------------------------
games/hub/src/main/java/com/vayunmathur/games/hub/data/dao/StreakDao.kt
diff --git a/games/hub/src/main/java/com/vayunmathur/games/hub/data/dao/StreakDao.kt b/games/hub/src/main/java/com/vayunmathur/games/hub/data/dao/StreakDao.ktnew file mode 100644index 0000000000..d7d5dcd205--- /dev/null+++ b/games/hub/src/main/java/com/vayunmathur/games/hub/data/dao/StreakDao.kt@@ -0,0 +1,26 @@+package com.vayunmathur.games.hub.data.dao++import androidx.room.Dao+import androidx.room.Query+import androidx.room.Upsert+import com.vayunmathur.games.hub.data.entities.DailyStreakEntity+import kotlinx.coroutines.flow.Flow++@Dao+interface StreakDao {++ @Upsert+ suspend fun upsert(streak: DailyStreakEntity)++ @Query("SELECT * FROM daily_streaks WHERE gameId = :gameId LIMIT 1")+ suspend fun getByGame(gameId: String): DailyStreakEntity?++ @Query("SELECT * FROM daily_streaks WHERE gameId = :gameId LIMIT 1")+ fun flowByGame(gameId: String): Flow<DailyStreakEntity?>++ @Query("SELECT * FROM daily_streaks")+ fun flowAll(): Flow<List<DailyStreakEntity>>++ @Query("DELETE FROM daily_streaks")+ suspend fun clearAll()+}
games/hub/src/main/java/com/vayunmathur/games/hub/data/entities/DailyStreakEntity.kt
diff --git a/games/hub/src/main/java/com/vayunmathur/games/hub/data/entities/DailyStreakEntity.kt b/games/hub/src/main/java/com/vayunmathur/games/hub/data/entities/DailyStreakEntity.ktnew file mode 100644index 0000000000..df86d72116--- /dev/null+++ b/games/hub/src/main/java/com/vayunmathur/games/hub/data/entities/DailyStreakEntity.kt@@ -0,0 +1,20 @@+package com.vayunmathur.games.hub.data.entities++import androidx.room.Entity+import androidx.room.PrimaryKey++/**+ * A game's daily-puzzle streak, mirrored from the game.+ *+ * One row per game rather than one per day: the game's `DailyChallengeStore` is the source of+ * truth and only retains current/best/last-day, so there is no per-day history to keep.+ */+@Entity(tableName = "daily_streaks")+data class DailyStreakEntity(+ @PrimaryKey val gameId: String,+ val currentStreak: Int = 0,+ val longestStreak: Int = 0,+ /** Epoch day, so a lapsed streak is recognisable without trusting the write time. */+ val lastCompletedDay: Long = 0,+ val lastUpdated: Long = System.currentTimeMillis()+)
games/hub/src/main/java/com/vayunmathur/games/hub/provider/GamesHubProvider.kt
diff --git a/games/hub/src/main/java/com/vayunmathur/games/hub/provider/GamesHubProvider.kt b/games/hub/src/main/java/com/vayunmathur/games/hub/provider/GamesHubProvider.ktindex aabee71362..ad1d5cd3f8 100644--- a/games/hub/src/main/java/com/vayunmathur/games/hub/provider/GamesHubProvider.kt+++ b/games/hub/src/main/java/com/vayunmathur/games/hub/provider/GamesHubProvider.kt@@ -12,6 +12,7 @@ import com.vayunmathur.games.hub.data.GamesHubRepository import com.vayunmathur.games.hub.data.entities.AchievementDefEntity import com.vayunmathur.games.hub.data.entities.AchievementProgressEntity import com.vayunmathur.games.hub.data.entities.ActivityEventEntity+import com.vayunmathur.games.hub.data.entities.DailyStreakEntity import com.vayunmathur.games.hub.data.entities.HubGameEntity import com.vayunmathur.games.hub.data.entities.PlaySessionEntity import com.vayunmathur.sdk.games.GameHubContract@@ -33,6 +34,7 @@ open class GamesHubProvider : ContentProvider() { private const val CODE_LEGACY_ACHIEVEMENT_ITEM = 21 private const val CODE_SESSIONS_BY_GAME = 50 private const val CODE_SESSION_ITEM = 51+ private const val CODE_STREAK_BY_GAME = 60 private val uriMatcher = UriMatcher(UriMatcher.NO_MATCH).apply { addURI(GameHubContract.AUTHORITY, "games", CODE_GAMES)@@ -56,6 +58,9 @@ open class GamesHubProvider : ContentProvider() { addURI(GameHubContract.LEGACY_AUTHORITY, "sessions/*", CODE_SESSIONS_BY_GAME) addURI(GameHubContract.AUTHORITY, "sessions/*/*", CODE_SESSION_ITEM) addURI(GameHubContract.LEGACY_AUTHORITY, "sessions/*/*", CODE_SESSION_ITEM)++ addURI(GameHubContract.AUTHORITY, "streaks/*", CODE_STREAK_BY_GAME)+ addURI(GameHubContract.LEGACY_AUTHORITY, "streaks/*", CODE_STREAK_BY_GAME) } } @@ -181,6 +186,17 @@ open class GamesHubProvider : ContentProvider() { repo.upsertSession(session) uri }+ CODE_STREAK_BY_GAME -> {+ val reported = valuesToStreak(v, uri)+ ensureGameExists(reported.gameId, repo)+ val existing = repo.getStreak(reported.gameId)+ // Never lower a personal best: a reinstall starts the game's store from zero.+ val merged = reported.copy(+ longestStreak = maxOf(reported.longestStreak, existing?.longestStreak ?: 0)+ )+ repo.upsertStreak(merged)+ uri+ } else -> null } } catch (e: Exception) {@@ -309,6 +325,10 @@ open class GamesHubProvider : ContentProvider() { val achId = uri.pathSegments.getOrNull(2) ?: return@runBlocking null cursorFromLegacyAchievementItem(repo.getAchievementDef(gameId, achId), repo.getProgress(gameId, achId)) }+ CODE_STREAK_BY_GAME -> {+ val gameId = uri.pathSegments.getOrNull(1) ?: return@runBlocking null+ cursorFromStreaks(listOfNotNull(repo.getStreak(gameId)))+ } else -> null } } catch (e: Exception) {@@ -420,6 +440,25 @@ open class GamesHubProvider : ContentProvider() { ) } + private fun valuesToStreak(v: ContentValues, uri: Uri): DailyStreakEntity {+ val segGameId = uri.pathSegments.getOrNull(1)+ return DailyStreakEntity(+ gameId = v.getAsString(GameHubContract.Streaks.GAME_ID) ?: segGameId ?: error("gameId missing in streak"),+ currentStreak = v.getAsInteger(GameHubContract.Streaks.CURRENT_STREAK) ?: 0,+ longestStreak = v.getAsInteger(GameHubContract.Streaks.LONGEST_STREAK) ?: 0,+ lastCompletedDay = v.getAsLong(GameHubContract.Streaks.LAST_COMPLETED_DAY) ?: 0L,+ lastUpdated = v.getAsLong(GameHubContract.Streaks.LAST_UPDATED) ?: System.currentTimeMillis()+ )+ }++ private fun cursorFromStreaks(streaks: List<DailyStreakEntity>): MatrixCursor {+ val c = MatrixCursor(arrayOf("game_id", "current_streak", "longest_streak", "last_completed_day", "last_updated"))+ for (s in streaks) {+ c.addRow(arrayOf<Any?>(s.gameId, s.currentStreak, s.longestStreak, s.lastCompletedDay, s.lastUpdated))+ }+ return c+ }+ private fun cursorFromGames(games: List<HubGameEntity>): MatrixCursor { val c = MatrixCursor(arrayOf("game_id", "package_name", "display_name", "description", "version_name", "version_code", "registered_at", "last_seen_at", "last_played_at", "total_playtime_ms", "total_sessions")) for (g in games) {
games/hub/src/main/java/com/vayunmathur/games/hub/ui/components/GameCard.kt
diff --git a/games/hub/src/main/java/com/vayunmathur/games/hub/ui/components/GameCard.kt b/games/hub/src/main/java/com/vayunmathur/games/hub/ui/components/GameCard.ktindex c17d53285d..28db556e46 100644--- a/games/hub/src/main/java/com/vayunmathur/games/hub/ui/components/GameCard.kt+++ b/games/hub/src/main/java/com/vayunmathur/games/hub/ui/components/GameCard.kt@@ -39,6 +39,8 @@ fun GameCard( isInstalled: Boolean, modifier: Modifier = Modifier, achievementProgress: Pair<Int, Int>? = null,+ /** (current, longest) daily-puzzle streak, or null for a game that has none. */+ dailyStreak: Pair<Int, Int>? = null, iconDrawable: Drawable? = null, onClick: () -> Unit, onPlay: () -> Unit@@ -90,6 +92,11 @@ fun GameCard( Text(stringResource(R.string.achievements_2, unlocked, total), style = MaterialTheme.typography.labelSmall) } }+ dailyStreak?.let { (current, longest) ->+ if (current > 0) {+ Text(stringResource(R.string.daily_streak_days, current, longest), style = MaterialTheme.typography.labelSmall)+ }+ } } if (achievementProgress != null && achievementProgress.second > 0) {
games/hub/src/main/java/com/vayunmathur/games/hub/ui/screens/DashboardPage.kt
diff --git a/games/hub/src/main/java/com/vayunmathur/games/hub/ui/screens/DashboardPage.kt b/games/hub/src/main/java/com/vayunmathur/games/hub/ui/screens/DashboardPage.ktindex 392e95637d..3d77287006 100644--- a/games/hub/src/main/java/com/vayunmathur/games/hub/ui/screens/DashboardPage.kt+++ b/games/hub/src/main/java/com/vayunmathur/games/hub/ui/screens/DashboardPage.kt@@ -34,6 +34,7 @@ fun DashboardPage( val profile by viewModel.profileFlow.collectAsStateWithLifecycle() val recentActivity by viewModel.recentActivityFlow.collectAsStateWithLifecycle() val allAchievements by viewModel.allAchievementsFlow.collectAsStateWithLifecycle()+ val dailyStreaks by viewModel.dailyStreaksFlow.collectAsStateWithLifecycle() val sessions by viewModel.sessionsFlow.collectAsStateWithLifecycle() val context = LocalContext.current @@ -67,6 +68,7 @@ fun DashboardPage( recentlyPlayed = recentlyPlayedGames, recentActivity = recentActivity, achievementProgressByGame = achievementProgressByGame,+ dailyStreakByGame = dailyStreaks, installedGameIds = installedGameIds, ), actions = object : DashboardActions {
games/hub/src/main/java/com/vayunmathur/games/hub/ui/screens/DashboardScreen.kt
diff --git a/games/hub/src/main/java/com/vayunmathur/games/hub/ui/screens/DashboardScreen.kt b/games/hub/src/main/java/com/vayunmathur/games/hub/ui/screens/DashboardScreen.ktindex 240a5c7b9f..6ae8ab04f2 100644--- a/games/hub/src/main/java/com/vayunmathur/games/hub/ui/screens/DashboardScreen.kt+++ b/games/hub/src/main/java/com/vayunmathur/games/hub/ui/screens/DashboardScreen.kt@@ -101,6 +101,7 @@ fun DashboardScreen( GameCard( game = game, isInstalled = game.gameId in state.installedGameIds, achievementProgress = state.achievementProgressByGame[game.gameId],+ dailyStreak = state.dailyStreakByGame[game.gameId], iconDrawable = iconFor(game), onClick = { actions.openGame(game.gameId) }, onPlay = { actions.playGame(game) },
games/hub/src/main/java/com/vayunmathur/games/hub/ui/screens/GameDetailScreen.kt
diff --git a/games/hub/src/main/java/com/vayunmathur/games/hub/ui/screens/GameDetailScreen.kt b/games/hub/src/main/java/com/vayunmathur/games/hub/ui/screens/GameDetailScreen.ktindex 7fcac1b753..0ee1b538fe 100644--- a/games/hub/src/main/java/com/vayunmathur/games/hub/ui/screens/GameDetailScreen.kt+++ b/games/hub/src/main/java/com/vayunmathur/games/hub/ui/screens/GameDetailScreen.kt@@ -30,6 +30,7 @@ import com.vayunmathur.games.hub.MainRoute import com.vayunmathur.games.hub.ui.components.AchievementRow import com.vayunmathur.games.hub.ui.components.ActivityItemCard import com.vayunmathur.games.hub.ui.components.StatCard+import com.vayunmathur.games.hub.ui.components.StreakCard import com.vayunmathur.games.hub.util.GameIconResolver import com.vayunmathur.games.hub.util.formatDurationMs import com.vayunmathur.games.hub.util.formatPlaytime@@ -60,6 +61,7 @@ fun GameDetailScreen( val achievements by viewModel.getAchievementsForGameFlow(gameId).collectAsStateWithLifecycle(initialValue = emptyList()) val sessions by viewModel.getSessionsForGameFlow(gameId).collectAsStateWithLifecycle(initialValue = emptyList()) val activity by viewModel.getActivityForGameFlow(gameId).collectAsStateWithLifecycle(initialValue = emptyList())+ val dailyStreak by viewModel.getDailyStreakForGameFlow(gameId).collectAsStateWithLifecycle(initialValue = null) val context = LocalContext.current val iconDrawable: Drawable? = remember(game?.packageName) { game?.packageName?.let { GameIconResolver.resolveAppIcon(context, it) } }@@ -102,6 +104,9 @@ fun GameDetailScreen( StatCard(label = stringResource(com.vayunmathur.games.hub.R.string.sessions), value = "${sessions.size}", modifier = Modifier.weight(1f)) StatCard(label = stringResource(com.vayunmathur.games.hub.R.string.last), value = g.lastPlayedAt?.let { formatRelativeTime(it) } ?: "Never", modifier = Modifier.weight(1f)) } }+ dailyStreak?.takeIf { it.currentStreak > 0 || it.longestStreak > 0 }?.let { streak ->+ item { StreakCard(currentStreak = streak.currentStreak, longestStreak = streak.longestStreak, modifier = Modifier.fillMaxWidth()) }+ } if (achievements.isNotEmpty()) { val unlocked = achievements.count { it.isUnlocked } item { Text(stringResource(R.string.achievements, unlocked, achievements.size), style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.Bold) }
games/hub/src/main/java/com/vayunmathur/games/hub/ui/screens/GamesListPage.kt
diff --git a/games/hub/src/main/java/com/vayunmathur/games/hub/ui/screens/GamesListPage.kt b/games/hub/src/main/java/com/vayunmathur/games/hub/ui/screens/GamesListPage.ktindex ffa2dd17fc..6b3d2e7ec3 100644--- a/games/hub/src/main/java/com/vayunmathur/games/hub/ui/screens/GamesListPage.kt+++ b/games/hub/src/main/java/com/vayunmathur/games/hub/ui/screens/GamesListPage.kt@@ -22,6 +22,7 @@ fun GamesListPage( ) { val games by viewModel.gamesFlow.collectAsStateWithLifecycle() val allAchievements by viewModel.allAchievementsFlow.collectAsStateWithLifecycle()+ val dailyStreaks by viewModel.dailyStreaksFlow.collectAsStateWithLifecycle() val context = LocalContext.current val iconCache = remember { mutableMapOf<String, Drawable?>() }@@ -40,6 +41,7 @@ fun GamesListPage( state = GamesListUiState( games = games, achievementProgressByGame = achievementProgressByGame,+ dailyStreakByGame = dailyStreaks, installedGameIds = installedGameIds, ), actions = object : GamesListActions {
games/hub/src/main/java/com/vayunmathur/games/hub/ui/screens/GamesListScreen.kt
diff --git a/games/hub/src/main/java/com/vayunmathur/games/hub/ui/screens/GamesListScreen.kt b/games/hub/src/main/java/com/vayunmathur/games/hub/ui/screens/GamesListScreen.ktindex aa97854473..6ff3f5cd59 100644--- a/games/hub/src/main/java/com/vayunmathur/games/hub/ui/screens/GamesListScreen.kt+++ b/games/hub/src/main/java/com/vayunmathur/games/hub/ui/screens/GamesListScreen.kt@@ -89,6 +89,7 @@ fun GamesListScreen( GameCard( game = game, isInstalled = game.gameId in state.installedGameIds, achievementProgress = state.achievementProgressByGame[game.gameId],+ dailyStreak = state.dailyStreakByGame[game.gameId], iconDrawable = iconFor(game), onClick = { actions.openGame(game.gameId) }, onPlay = { actions.playGame(game) }
games/hub/src/main/java/com/vayunmathur/games/hub/util/HubUiContract.kt
diff --git a/games/hub/src/main/java/com/vayunmathur/games/hub/util/HubUiContract.kt b/games/hub/src/main/java/com/vayunmathur/games/hub/util/HubUiContract.ktindex 27410c3214..927c61baa9 100644--- a/games/hub/src/main/java/com/vayunmathur/games/hub/util/HubUiContract.kt+++ b/games/hub/src/main/java/com/vayunmathur/games/hub/util/HubUiContract.kt@@ -30,6 +30,8 @@ data class DashboardUiState( val recentActivity: List<ActivityEventEntity> = emptyList(), /** gameId -> (unlocked, total). */ val achievementProgressByGame: Map<String, Pair<Int, Int>> = emptyMap(),+ /** gameId -> (current, longest) daily-puzzle streak. */+ val dailyStreakByGame: Map<String, Pair<Int, Int>> = emptyMap(), /** Games whose package is actually present on the device. */ val installedGameIds: Set<String> = emptySet(), )@@ -39,6 +41,8 @@ data class GamesListUiState( val games: List<HubGameEntity> = emptyList(), /** gameId -> (unlocked, total). */ val achievementProgressByGame: Map<String, Pair<Int, Int>> = emptyMap(),+ /** gameId -> (current, longest) daily-puzzle streak. */+ val dailyStreakByGame: Map<String, Pair<Int, Int>> = emptyMap(), /** Games whose package is actually present on the device. */ val installedGameIds: Set<String> = emptySet(), )
games/hub/src/main/java/com/vayunmathur/games/hub/viewmodel/GameHubViewModel.kt
diff --git a/games/hub/src/main/java/com/vayunmathur/games/hub/viewmodel/GameHubViewModel.kt b/games/hub/src/main/java/com/vayunmathur/games/hub/viewmodel/GameHubViewModel.ktindex 05eba82743..809f022871 100644--- a/games/hub/src/main/java/com/vayunmathur/games/hub/viewmodel/GameHubViewModel.kt+++ b/games/hub/src/main/java/com/vayunmathur/games/hub/viewmodel/GameHubViewModel.kt@@ -8,6 +8,7 @@ import androidx.lifecycle.viewModelScope import com.vayunmathur.games.hub.data.GamesHubRepository import com.vayunmathur.games.hub.data.dao.AchievementWithProgress import com.vayunmathur.games.hub.data.entities.ActivityEventEntity+import com.vayunmathur.games.hub.data.entities.DailyStreakEntity import com.vayunmathur.games.hub.data.entities.HubGameEntity import com.vayunmathur.games.hub.data.entities.PlayerProfileEntity import com.vayunmathur.games.hub.data.entities.PlaySessionEntity@@ -115,6 +116,12 @@ class GameHubViewModel( sessionsFlow.map { StreakCalculator.calculate(it) } .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), StreakCalculator.StreakResult(0, 0)) + /** gameId -> (current, longest) daily-puzzle streak, as pushed by each game. */+ val dailyStreaksFlow: StateFlow<Map<String, Pair<Int, Int>>> =+ repository.allStreaksFlow()+ .map { streaks -> streaks.associate { it.gameId to (it.currentStreak to it.longestStreak) } }+ .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), emptyMap())+ val recentActivityFlow: StateFlow<List<ActivityEventEntity>> = repository.recentActivityFlow(50) .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), emptyList())@@ -178,6 +185,9 @@ class GameHubViewModel( fun getSessionsForGameFlow(gameId: String): Flow<List<PlaySessionEntity>> = repository.sessionsByGameFlow(gameId) + fun getDailyStreakForGameFlow(gameId: String): Flow<DailyStreakEntity?> =+ repository.streakByGameFlow(gameId)+ fun getActivityForGameFlow(gameId: String): Flow<List<ActivityEventEntity>> = repository.activityByGameFlow(gameId, 30) @@ -187,6 +197,7 @@ class GameHubViewModel( repository.clearDefs() repository.clearProgress() repository.clearSessions()+ repository.clearStreaks() repository.clearActivities() } }
games/hub/src/main/res/values/strings.xml
diff --git a/games/hub/src/main/res/values/strings.xml b/games/hub/src/main/res/values/strings.xmlindex fd8ac1beae..fa8b6e0135 100644--- a/games/hub/src/main/res/values/strings.xml+++ b/games/hub/src/main/res/values/strings.xml@@ -52,6 +52,8 @@ <string name="playtime_sessions">Playtime: <xliff:g id="playtime" example="2h 15m">%1$s</xliff:g> • <xliff:g id="sessions" example="5">%2$s</xliff:g> sessions</string> <!-- GameCard: Achievements progress. %1$s = unlocked count e.g. 3, %2$s = total count e.g. 10. Noun with fraction --> <string name="achievements_2">Achievements: <xliff:g id="unlocked" example="3">%1$s</xliff:g>/<xliff:g id="total" example="10">%2$s</xliff:g></string>+ <!-- GameCard: Compact daily-puzzle streak label. %1$s = current streak days e.g. 5, %2$s = longest streak days e.g. 12. Noun phrase -->+ <string name="daily_streak_days">Daily streak: <xliff:g id="current" example="5">%1$s</xliff:g> (best <xliff:g id="best" example="12">%2$s</xliff:g>)</string> <!-- GameDetailScreen: Game not found null state. Sentence --> <string name="game_not_found">Game not found</string> <!-- GameDetailScreen: Section header for achievements with progress. %1$s = unlocked e.g. 3, %2$s = total e.g. 10. Noun -->
games/pipes/src/main/java/com/vayunmathur/games/pipes/platform/PipesViewModel.kt
diff --git a/games/pipes/src/main/java/com/vayunmathur/games/pipes/platform/PipesViewModel.kt b/games/pipes/src/main/java/com/vayunmathur/games/pipes/platform/PipesViewModel.ktindex 4bbe971a62..b370cd5604 100644--- a/games/pipes/src/main/java/com/vayunmathur/games/pipes/platform/PipesViewModel.kt+++ b/games/pipes/src/main/java/com/vayunmathur/games/pipes/platform/PipesViewModel.kt@@ -11,6 +11,7 @@ import com.vayunmathur.games.pipes.data.LevelPack import com.vayunmathur.library.util.LevelStats import com.vayunmathur.library.util.AchievementsManager import com.vayunmathur.library.util.DailyChallengeStore+import com.vayunmathur.library.util.DailyStreakReporter import com.vayunmathur.library.util.DataStoreUtils import com.vayunmathur.library.util.LevelStatsRepository import kotlinx.coroutines.Dispatchers@@ -363,6 +364,7 @@ class PipesViewModel(application: Application) : AndroidViewModel(application), val streak = dailyStore.recordDayCompleted(day) achievementsManager.onProgressUpdated("daily_streak_7", streak.best.toInt()) achievementsManager.onProgressUpdated("daily_streak_30", streak.best.toInt())+ DailyStreakReporter.report(getApplication(), "pipes", streak, day) } } }
games/unblockjam/src/main/java/com/vayunmathur/games/unblockjam/platform/UnblockJamViewModel.kt
diff --git a/games/unblockjam/src/main/java/com/vayunmathur/games/unblockjam/platform/UnblockJamViewModel.kt b/games/unblockjam/src/main/java/com/vayunmathur/games/unblockjam/platform/UnblockJamViewModel.ktindex 6b63dbe452..b4fbdb99ac 100644--- a/games/unblockjam/src/main/java/com/vayunmathur/games/unblockjam/platform/UnblockJamViewModel.kt+++ b/games/unblockjam/src/main/java/com/vayunmathur/games/unblockjam/platform/UnblockJamViewModel.kt@@ -10,6 +10,7 @@ import com.vayunmathur.games.unblockjam.data.LevelPack import com.vayunmathur.library.util.LevelStats import com.vayunmathur.library.util.AchievementsManager import com.vayunmathur.library.util.DailyChallengeStore+import com.vayunmathur.library.util.DailyStreakReporter import com.vayunmathur.library.util.LevelStatsRepository import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.MutableStateFlow@@ -245,6 +246,7 @@ class UnblockJamViewModel(application: Application) : AndroidViewModel(applicati val streak = dailyStore.recordDayCompleted(day) achievementsManager.onProgressUpdated("daily_streak_7", streak.best.toInt()) achievementsManager.onProgressUpdated("daily_streak_30", streak.best.toInt())+ DailyStreakReporter.report(getApplication(), "unblockjam", streak, day) } } }
games/wordmaker/src/main/java/com/vayunmathur/games/wordmaker/platform/WordMakerViewModel.kt
diff --git a/games/wordmaker/src/main/java/com/vayunmathur/games/wordmaker/platform/WordMakerViewModel.kt b/games/wordmaker/src/main/java/com/vayunmathur/games/wordmaker/platform/WordMakerViewModel.ktindex fafdc375ac..0052b9a8a2 100644--- a/games/wordmaker/src/main/java/com/vayunmathur/games/wordmaker/platform/WordMakerViewModel.kt+++ b/games/wordmaker/src/main/java/com/vayunmathur/games/wordmaker/platform/WordMakerViewModel.kt@@ -12,6 +12,7 @@ import com.vayunmathur.games.wordmaker.data.LevelDataStore import com.vayunmathur.games.wordmaker.domain.CompetitiveLevelGenerator import com.vayunmathur.games.wordmaker.domain.Dictionary import com.vayunmathur.library.util.DailyChallengeStore+import com.vayunmathur.library.util.DailyStreakReporter import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.MutableStateFlow@@ -220,7 +221,11 @@ class WordMakerViewModel(application: Application) : AndroidViewModel(applicatio /** Records today's daily as solved, extending the streak. Idempotent within a day. */ fun onDailyWin() {- viewModelScope.launch { dailyStore.recordDayCompleted(_dailyDay.value) }+ viewModelScope.launch {+ val day = _dailyDay.value+ val streak = dailyStore.recordDayCompleted(day)+ DailyStreakReporter.report(getApplication(), "wordmaker", streak, day)+ } } private suspend fun loadCasualLevel(level: Int) {
library/src/main/java/com/vayunmathur/library/util/DailyStreakReporter.kt
diff --git a/library/src/main/java/com/vayunmathur/library/util/DailyStreakReporter.kt b/library/src/main/java/com/vayunmathur/library/util/DailyStreakReporter.ktnew file mode 100644index 0000000000..003fbeafbe--- /dev/null+++ b/library/src/main/java/com/vayunmathur/library/util/DailyStreakReporter.kt@@ -0,0 +1,26 @@+package com.vayunmathur.library.util++import android.content.Context+import com.vayunmathur.sdk.games.DailyStreak+import com.vayunmathur.sdk.games.GameHubClient++/**+ * Forwards a game's daily-puzzle streak to the hub, right where the game already records it.+ *+ * Fail-soft in both directions: [GameHubClient] no-ops when the hub isn't installed, and any+ * other failure is swallowed — a game must never break because the hub is unhappy.+ */+object DailyStreakReporter {++ suspend fun report(context: Context, gameId: String, streak: DailyChallengeStore.Streak, day: Long) {+ try {+ GameHubClient(context, gameId).reportDailyStreak(+ DailyStreak(+ currentStreak = streak.current.toInt(),+ longestStreak = streak.best.toInt(),+ lastCompletedDay = day,+ )+ )+ } catch (_: Exception) { }+ }+}
sdk/games/src/main/java/com/vayunmathur/sdk/games/GameHubClient.kt
diff --git a/sdk/games/src/main/java/com/vayunmathur/sdk/games/GameHubClient.kt b/sdk/games/src/main/java/com/vayunmathur/sdk/games/GameHubClient.ktindex 5608b2d07c..9cd0249c1e 100644--- a/sdk/games/src/main/java/com/vayunmathur/sdk/games/GameHubClient.kt+++ b/sdk/games/src/main/java/com/vayunmathur/sdk/games/GameHubClient.kt@@ -178,6 +178,21 @@ class GameHubClient( try { resolver.update(uri, values, null, null) > 0 } catch (_: Exception) { false } } + /** Pushes the game's current daily-puzzle streak. Fail-soft, like every other call here. */+ suspend fun reportDailyStreak(streak: DailyStreak): Boolean = withContext(Dispatchers.IO) {+ if (!isHubInstalled()) return@withContext false+ val resolver = appContext.contentResolver+ val uri = GameHubContract.buildStreakUri(gameId)+ val values = ContentValues().apply {+ put(GameHubContract.Streaks.GAME_ID, gameId)+ put(GameHubContract.Streaks.CURRENT_STREAK, streak.currentStreak)+ put(GameHubContract.Streaks.LONGEST_STREAK, streak.longestStreak)+ put(GameHubContract.Streaks.LAST_COMPLETED_DAY, streak.lastCompletedDay)+ put(GameHubContract.Streaks.LAST_UPDATED, System.currentTimeMillis())+ }+ try { resolver.insert(uri, values) != null } catch (_: Exception) { false }+ }+ @Deprecated("Use registerAchievements with AchievementDefinition") suspend fun registerAchievementsLegacy(achievements: List<Achievement>) { val defs = achievements.map { AchievementDefinition(it.id, it.name, it.description, iconResName = it.iconResName) }
sdk/games/src/main/java/com/vayunmathur/sdk/games/GameHubContract.kt
diff --git a/sdk/games/src/main/java/com/vayunmathur/sdk/games/GameHubContract.kt b/sdk/games/src/main/java/com/vayunmathur/sdk/games/GameHubContract.ktindex 80b75a7397..da3156a6f8 100644--- a/sdk/games/src/main/java/com/vayunmathur/sdk/games/GameHubContract.kt+++ b/sdk/games/src/main/java/com/vayunmathur/sdk/games/GameHubContract.kt@@ -60,6 +60,18 @@ object GameHubContract { const val DURATION_MS = "duration_ms" } + /**+ * A game's daily-puzzle streak. One row per game, not per day: the game's own+ * `DailyChallengeStore` is the source of truth and only keeps current/best/last-day.+ */+ object Streaks {+ const val GAME_ID = "game_id"+ const val CURRENT_STREAK = "current_streak"+ const val LONGEST_STREAK = "longest_streak"+ const val LAST_COMPLETED_DAY = "last_completed_day"+ const val LAST_UPDATED = "last_updated"+ }+ // Legacy columns (from old SDK) object Legacy { const val ACHIEVEMENT_ID = "achievement_id"@@ -93,6 +105,9 @@ object GameHubContract { fun buildSessionItemUri(gameId: String, sessionId: String): Uri = BASE_URI.buildUpon().appendPath("sessions").appendPath(gameId).appendPath(sessionId).build() + fun buildStreakUri(gameId: String): Uri =+ BASE_URI.buildUpon().appendPath("streaks").appendPath(gameId).build()+ // Legacy URI helpers fun buildLegacyAchievementsUri(gameId: String): Uri = BASE_URI.buildUpon().appendPath("achievements").appendPath(gameId).build()
sdk/games/src/main/java/com/vayunmathur/sdk/games/Models.kt
diff --git a/sdk/games/src/main/java/com/vayunmathur/sdk/games/Models.kt b/sdk/games/src/main/java/com/vayunmathur/sdk/games/Models.ktindex 5c0eb70385..c19d8dbeb9 100644--- a/sdk/games/src/main/java/com/vayunmathur/sdk/games/Models.kt+++ b/sdk/games/src/main/java/com/vayunmathur/sdk/games/Models.kt@@ -46,6 +46,18 @@ data class AchievementProgress( val unlockedAt: Long? = null ) +/**+ * A game's daily-puzzle streak, pushed by the game as source of truth.+ *+ * [lastCompletedDay] is an epoch day, so the hub can tell a live streak from a lapsed one+ * without depending on when the row was written.+ */+data class DailyStreak(+ val currentStreak: Int,+ val longestStreak: Int,+ val lastCompletedDay: Long,+)+ // ──────── Legacy models — kept for backward compatibility ──────── /**