feat: add AppDatabase and move payment caching to db
This commit is contained in:
@@ -1,59 +1,47 @@
|
||||
package com.bitcointxoko.gudariwallet.data
|
||||
|
||||
import android.content.Context
|
||||
import android.content.SharedPreferences
|
||||
import android.util.Log
|
||||
import com.bitcointxoko.gudariwallet.api.GsonProvider
|
||||
import com.bitcointxoko.gudariwallet.api.PaymentDetailResponse
|
||||
import com.bitcointxoko.gudariwallet.api.PaymentRecord
|
||||
import com.bitcointxoko.gudariwallet.data.db.AppDatabase
|
||||
import com.bitcointxoko.gudariwallet.data.db.toDomain
|
||||
import com.bitcointxoko.gudariwallet.data.db.toEntity
|
||||
import com.bitcointxoko.gudariwallet.util.WalletConstants
|
||||
import com.bitcointxoko.gudariwallet.api.SuccessAction
|
||||
import com.bitcointxoko.gudariwallet.api.SuccessActionAdapter
|
||||
import com.google.gson.GsonBuilder
|
||||
import com.google.gson.reflect.TypeToken
|
||||
|
||||
private const val TAG = "PaymentCacheRepository"
|
||||
|
||||
class PaymentCacheRepository(context: Context) {
|
||||
|
||||
private val prefs: SharedPreferences = context.getSharedPreferences(
|
||||
WalletConstants.PAYMENTS_PREFS_NAME, Context.MODE_PRIVATE
|
||||
)
|
||||
private val gson = GsonProvider.gson
|
||||
private val dao = AppDatabase.getInstance(context).paymentDao()
|
||||
|
||||
// ── In-memory detail cache — immutable once confirmed, no TTL needed ──────
|
||||
private val detailCache = mutableMapOf<String, PaymentDetailResponse>()
|
||||
|
||||
// ── Payment list ──────────────────────────────────────────────────────────
|
||||
|
||||
/** Load the persisted first-page list. Returns empty list if nothing cached or cache is stale. */
|
||||
fun loadCachedPayments(): List<PaymentRecord> {
|
||||
val json = prefs.getString(WalletConstants.PAYMENTS_PREFS_KEY, null) ?: return emptyList()
|
||||
val savedAt = prefs.getLong(WalletConstants.PAYMENTS_PREFS_SAVED_AT, 0L)
|
||||
val ageMs = System.currentTimeMillis() - savedAt
|
||||
|
||||
suspend fun loadCachedPayments(): List<PaymentRecord> {
|
||||
val savedAt = dao.getLatestSavedAt() ?: run {
|
||||
Log.d(TAG, "PAYMENTS [CACHE MISS] no rows in db")
|
||||
return emptyList()
|
||||
}
|
||||
val ageMs = System.currentTimeMillis() - savedAt
|
||||
if (ageMs > WalletConstants.PAYMENTS_CACHE_TTL_MS) {
|
||||
Log.d(TAG, "PAYMENTS [CACHE STALE] age ${ageMs / 1000}s — ignoring persisted list")
|
||||
return emptyList()
|
||||
}
|
||||
|
||||
return runCatching {
|
||||
val type: java.lang.reflect.Type = object : TypeToken<List<PaymentRecord>>() {}.type
|
||||
val list: List<PaymentRecord> = gson.fromJson(json, type)
|
||||
Log.d(TAG, "PAYMENTS [CACHE HIT ] loaded ${list.size} payments (age ${ageMs / 1000}s)")
|
||||
list
|
||||
}.getOrElse {
|
||||
Log.w(TAG, "PAYMENTS [CACHE ERR ] failed to deserialise: ${it.message}")
|
||||
emptyList()
|
||||
return dao.getAll().map { it.toDomain() }.also {
|
||||
Log.d(TAG, "PAYMENTS [CACHE HIT ] loaded ${it.size} payments (age ${ageMs / 1000}s)")
|
||||
}
|
||||
}
|
||||
|
||||
/** Persist the first page of payments to SharedPreferences. */
|
||||
fun savePayments(payments: List<PaymentRecord>) {
|
||||
/** Persist the first page of payments to the database. */
|
||||
suspend fun savePayments(payments: List<PaymentRecord>) {
|
||||
val now = System.currentTimeMillis()
|
||||
runCatching {
|
||||
prefs.edit()
|
||||
.putString(WalletConstants.PAYMENTS_PREFS_KEY, gson.toJson(payments))
|
||||
.putLong(WalletConstants.PAYMENTS_PREFS_SAVED_AT, System.currentTimeMillis())
|
||||
.apply()
|
||||
dao.deleteAll()
|
||||
dao.insertAll(payments.map { it.toEntity(now) })
|
||||
Log.d(TAG, "PAYMENTS [PERSIST ] saved ${payments.size} payments")
|
||||
}.onFailure {
|
||||
Log.w(TAG, "PAYMENTS [PERSIST ] write failed: ${it.message}")
|
||||
@@ -63,11 +51,10 @@ class PaymentCacheRepository(context: Context) {
|
||||
// ── Payment detail ────────────────────────────────────────────────────────
|
||||
|
||||
/** Returns a cached detail response, or null if not yet fetched this session. */
|
||||
fun getCachedDetail(checkingId: String): PaymentDetailResponse? {
|
||||
return detailCache[checkingId]?.also {
|
||||
fun getCachedDetail(checkingId: String): PaymentDetailResponse? =
|
||||
detailCache[checkingId]?.also {
|
||||
Log.d(TAG, "PAYMENTS [DETAIL HIT] $checkingId")
|
||||
}
|
||||
}
|
||||
|
||||
/** Store a detail response in the in-memory cache. */
|
||||
fun saveDetail(checkingId: String, detail: PaymentDetailResponse) {
|
||||
@@ -76,12 +63,9 @@ class PaymentCacheRepository(context: Context) {
|
||||
}
|
||||
|
||||
/** Clear everything — useful for testing and logout. */
|
||||
fun clearAll() {
|
||||
suspend fun clearAll() {
|
||||
detailCache.clear()
|
||||
prefs.edit()
|
||||
.remove(WalletConstants.PAYMENTS_PREFS_KEY)
|
||||
.remove(WalletConstants.PAYMENTS_PREFS_SAVED_AT)
|
||||
.apply()
|
||||
dao.deleteAll()
|
||||
Log.d(TAG, "PAYMENTS [CLEARED ] cache wiped")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
package com.bitcointxoko.gudariwallet.data.db
|
||||
|
||||
import android.content.Context
|
||||
import androidx.room.Database
|
||||
import androidx.room.Room
|
||||
import androidx.room.RoomDatabase
|
||||
import androidx.room.TypeConverters
|
||||
|
||||
@Database(
|
||||
entities = [PaymentRecordEntity::class],
|
||||
version = 1,
|
||||
exportSchema = false
|
||||
)
|
||||
@TypeConverters(PaymentConverters::class)
|
||||
abstract class AppDatabase : RoomDatabase() {
|
||||
|
||||
abstract fun paymentDao(): PaymentDao
|
||||
|
||||
companion object {
|
||||
@Volatile private var INSTANCE: AppDatabase? = null
|
||||
|
||||
fun getInstance(context: Context): AppDatabase =
|
||||
INSTANCE ?: synchronized(this) {
|
||||
INSTANCE ?: Room.databaseBuilder(
|
||||
context.applicationContext,
|
||||
AppDatabase::class.java,
|
||||
"gudari_wallet.db"
|
||||
).build().also { INSTANCE = it }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package com.bitcointxoko.gudariwallet.data.db
|
||||
|
||||
import androidx.room.TypeConverter
|
||||
import com.bitcointxoko.gudariwallet.api.PaymentExtra
|
||||
import com.bitcointxoko.gudariwallet.api.GsonProvider
|
||||
|
||||
object PaymentConverters {
|
||||
private val gson = GsonProvider.gson
|
||||
|
||||
@TypeConverter
|
||||
@JvmStatic
|
||||
fun fromExtra(extra: PaymentExtra?): String? =
|
||||
extra?.let { gson.toJson(it) }
|
||||
|
||||
@TypeConverter
|
||||
@JvmStatic
|
||||
fun toExtra(json: String?): PaymentExtra? =
|
||||
json?.let { gson.fromJson(it, PaymentExtra::class.java) }
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package com.bitcointxoko.gudariwallet.data.db
|
||||
|
||||
import androidx.room.Dao
|
||||
import androidx.room.Insert
|
||||
import androidx.room.OnConflictStrategy
|
||||
import androidx.room.Query
|
||||
|
||||
@Dao
|
||||
interface PaymentDao {
|
||||
|
||||
@Insert(onConflict = OnConflictStrategy.REPLACE)
|
||||
suspend fun insertAll(payments: List<PaymentRecordEntity>)
|
||||
|
||||
/** Returns all rows ordered by time descending. */
|
||||
@Query("SELECT * FROM payment_records ORDER BY time DESC")
|
||||
suspend fun getAll(): List<PaymentRecordEntity>
|
||||
|
||||
/** Returns the savedAt timestamp of the most recently written row, or null if table is empty. */
|
||||
@Query("SELECT savedAt FROM payment_records ORDER BY savedAt DESC LIMIT 1")
|
||||
suspend fun getLatestSavedAt(): Long?
|
||||
|
||||
@Query("DELETE FROM payment_records")
|
||||
suspend fun deleteAll()
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package com.bitcointxoko.gudariwallet.data.db
|
||||
|
||||
import androidx.room.Entity
|
||||
import androidx.room.PrimaryKey
|
||||
import androidx.room.TypeConverters
|
||||
|
||||
@Entity(tableName = "payment_records")
|
||||
@TypeConverters(PaymentConverters::class)
|
||||
data class PaymentRecordEntity(
|
||||
@PrimaryKey
|
||||
val checkingId: String,
|
||||
val paymentHash: String,
|
||||
val amountMsat: Long,
|
||||
val feeMsat: Long,
|
||||
val memo: String?,
|
||||
val time: String,
|
||||
val status: String,
|
||||
val bolt11: String?,
|
||||
val pending: Boolean,
|
||||
val preimage: String?,
|
||||
val extra: String?, // JSON blob — PaymentExtra serialised by TypeConverter
|
||||
val savedAt: Long // epoch ms — used for TTL check
|
||||
)
|
||||
@@ -0,0 +1,38 @@
|
||||
package com.bitcointxoko.gudariwallet.data.db
|
||||
|
||||
import com.bitcointxoko.gudariwallet.api.PaymentRecord
|
||||
import com.bitcointxoko.gudariwallet.data.db.PaymentRecordEntity
|
||||
|
||||
fun PaymentRecord.toEntity(savedAt: Long): PaymentRecordEntity =
|
||||
PaymentRecordEntity(
|
||||
checkingId = checkingId,
|
||||
paymentHash = paymentHash,
|
||||
amountMsat = amountMsat,
|
||||
feeMsat = feeMsat,
|
||||
memo = memo,
|
||||
time = time,
|
||||
status = status,
|
||||
bolt11 = bolt11,
|
||||
pending = pending,
|
||||
preimage = preimage,
|
||||
extra = extra?.let { com.bitcointxoko.gudariwallet.api.GsonProvider.gson.toJson(it) },
|
||||
savedAt = savedAt
|
||||
)
|
||||
|
||||
fun PaymentRecordEntity.toDomain(): PaymentRecord =
|
||||
PaymentRecord(
|
||||
checkingId = checkingId,
|
||||
paymentHash = paymentHash,
|
||||
amountMsat = amountMsat,
|
||||
feeMsat = feeMsat,
|
||||
memo = memo,
|
||||
time = time,
|
||||
status = status,
|
||||
bolt11 = bolt11,
|
||||
pending = pending,
|
||||
preimage = preimage,
|
||||
extra = extra?.let {
|
||||
com.bitcointxoko.gudariwallet.api.GsonProvider.gson
|
||||
.fromJson(it, com.bitcointxoko.gudariwallet.api.PaymentExtra::class.java)
|
||||
}
|
||||
)
|
||||
Reference in New Issue
Block a user