|
| 1 | +/* |
| 2 | + * Copyright (c) 2025 RevenueCat, Inc. |
| 3 | + * |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | + * you may not use this file except in compliance with the License. |
| 6 | + * You may obtain a copy of the License at |
| 7 | + * |
| 8 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | + * |
| 10 | + * Unless required by applicable law or agreed to in writing, software |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + * See the License for the specific language governing permissions and |
| 14 | + * limitations under the License. |
| 15 | + */ |
| 16 | +package com.revenuecat.catpaywalls.core.data |
| 17 | + |
| 18 | +import androidx.datastore.core.DataStore |
| 19 | +import androidx.datastore.preferences.core.Preferences |
| 20 | +import androidx.datastore.preferences.core.edit |
| 21 | +import androidx.datastore.preferences.core.stringPreferencesKey |
| 22 | +import androidx.datastore.preferences.core.stringSetPreferencesKey |
| 23 | +import kotlinx.coroutines.flow.Flow |
| 24 | +import kotlinx.coroutines.flow.map |
| 25 | +import kotlinx.datetime.TimeZone |
| 26 | +import kotlinx.datetime.toLocalDateTime |
| 27 | +import kotlin.time.Clock |
| 28 | +import kotlin.time.ExperimentalTime |
| 29 | + |
| 30 | +@OptIn(ExperimentalTime::class) |
| 31 | +internal class ReadingTrackerRepositoryImpl( |
| 32 | + private val dataStore: DataStore<Preferences>, |
| 33 | + private val today: () -> String = { |
| 34 | + Clock.System.now().toLocalDateTime(TimeZone.currentSystemDefault()).date.toString() |
| 35 | + }, |
| 36 | +) : ReadingTrackerRepository { |
| 37 | + |
| 38 | + override val todayReadCount: Flow<Int> = dataStore.data.map { prefs -> |
| 39 | + val today = today() |
| 40 | + val lastReset = prefs[LAST_RESET_DATE_KEY] |
| 41 | + if (lastReset != today) 0 else prefs[READ_ARTICLES_KEY]?.size ?: 0 |
| 42 | + } |
| 43 | + |
| 44 | + override suspend fun recordArticleRead(articleTitle: String) { |
| 45 | + dataStore.edit { prefs -> |
| 46 | + val today = today() |
| 47 | + val lastReset = prefs[LAST_RESET_DATE_KEY] |
| 48 | + if (lastReset != today) { |
| 49 | + prefs[LAST_RESET_DATE_KEY] = today |
| 50 | + prefs[READ_ARTICLES_KEY] = setOf(articleTitle) |
| 51 | + } else { |
| 52 | + val current = prefs[READ_ARTICLES_KEY] ?: emptySet() |
| 53 | + prefs[READ_ARTICLES_KEY] = current + articleTitle |
| 54 | + } |
| 55 | + } |
| 56 | + } |
| 57 | + |
| 58 | + private companion object { |
| 59 | + val LAST_RESET_DATE_KEY = stringPreferencesKey("last_reset_date") |
| 60 | + val READ_ARTICLES_KEY = stringSetPreferencesKey("read_articles_today") |
| 61 | + } |
| 62 | +} |
0 commit comments