-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathActivityRepo.kt
More file actions
720 lines (638 loc) · 27.2 KB
/
ActivityRepo.kt
File metadata and controls
720 lines (638 loc) · 27.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
package to.bitkit.repositories
import androidx.annotation.VisibleForTesting
import com.synonym.bitkitcore.Activity
import com.synonym.bitkitcore.ActivityFilter
import com.synonym.bitkitcore.ActivityTags
import com.synonym.bitkitcore.ClosedChannelDetails
import com.synonym.bitkitcore.IcJitEntry
import com.synonym.bitkitcore.LightningActivity
import com.synonym.bitkitcore.OnchainActivity
import com.synonym.bitkitcore.PaymentState
import com.synonym.bitkitcore.PaymentType
import com.synonym.bitkitcore.SortDirection
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.TimeoutCancellationException
import kotlinx.coroutines.async
import kotlinx.coroutines.awaitAll
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.withContext
import kotlinx.coroutines.withTimeout
import org.lightningdevkit.ldknode.ChannelDetails
import org.lightningdevkit.ldknode.PaymentDetails
import org.lightningdevkit.ldknode.PaymentDirection
import org.lightningdevkit.ldknode.PaymentKind
import org.lightningdevkit.ldknode.TransactionDetails
import to.bitkit.data.CacheStore
import to.bitkit.data.dto.PendingBoostActivity
import to.bitkit.di.BgDispatcher
import to.bitkit.ext.amountOnClose
import to.bitkit.ext.matchesPaymentId
import to.bitkit.ext.nowMillis
import to.bitkit.ext.nowTimestamp
import to.bitkit.ext.rawId
import to.bitkit.models.ActivityBackupV1
import to.bitkit.services.CoreService
import to.bitkit.utils.Logger
import javax.inject.Inject
import javax.inject.Singleton
import kotlin.time.Clock
import kotlin.time.ExperimentalTime
import com.synonym.bitkitcore.TransactionDetails as BitkitCoreTransactionDetails
private const val SYNC_TIMEOUT_MS = 40_000L
@Suppress("LargeClass", "LongParameterList")
@OptIn(ExperimentalTime::class)
@Singleton
class ActivityRepo @Inject constructor(
@BgDispatcher private val bgDispatcher: CoroutineDispatcher,
private val coreService: CoreService,
private val lightningRepo: LightningRepo,
private val blocktankRepo: BlocktankRepo,
private val cacheStore: CacheStore,
private val transferRepo: TransferRepo,
private val clock: Clock,
) {
val isSyncingLdkNodePayments = MutableStateFlow(false)
private val _state = MutableStateFlow(ActivityState())
val state: StateFlow<ActivityState> = _state
private val _activitiesChanged = MutableStateFlow(0L)
val activitiesChanged: StateFlow<Long> = _activitiesChanged
private fun notifyActivitiesChanged() = _activitiesChanged.update { nowMillis(clock) }
suspend fun resetState() = withContext(bgDispatcher) {
_state.update { ActivityState() }
isSyncingLdkNodePayments.update { false }
notifyActivitiesChanged()
Logger.debug("Activity state reset", context = TAG)
}
suspend fun syncActivities(): Result<Unit> = withContext(bgDispatcher) {
Logger.debug("syncActivities called", context = TAG)
val result = runCatching {
withTimeout(SYNC_TIMEOUT_MS) {
Logger.debug("isSyncingLdkNodePayments = ${isSyncingLdkNodePayments.value}", context = TAG)
isSyncingLdkNodePayments.first { !it }
}
isSyncingLdkNodePayments.update { true }
lightningRepo.getPayments().mapCatching { payments ->
Logger.debug("Got payments with success, syncing activities", context = TAG)
syncLdkNodePayments(payments).getOrThrow()
boostPendingActivities()
transferRepo.syncTransferStates().getOrThrow()
}.onSuccess {
getAllAvailableTags().getOrNull()
}.getOrThrow()
}.onFailure { e ->
if (e is TimeoutCancellationException) {
Logger.warn("syncActivities timeout, forcing reset", context = TAG)
} else {
Logger.error("Failed to sync activities", e, context = TAG)
}
}
isSyncingLdkNodePayments.update { false }
notifyActivitiesChanged()
return@withContext result
}
/**
* Syncs `ldk-node` [PaymentDetails] list to `bitkit-core` [Activity] items.
*/
suspend fun syncLdkNodePayments(payments: List<PaymentDetails>): Result<Unit> = withContext(bgDispatcher) {
return@withContext runCatching {
val channelIdsByTxId = findChannelsForPayments(payments)
coreService.activity.syncLdkNodePaymentsToActivities(payments, channelIdsByTxId = channelIdsByTxId)
notifyActivitiesChanged()
}.onFailure { e ->
Logger.error("Error syncing LDK payments:", e, context = TAG)
}
}
private suspend fun findChannelsForPayments(
payments: List<PaymentDetails>,
): Map<String, String> = withContext(bgDispatcher) {
val channelIdsByTxId = mutableMapOf<String, String>()
payments.filter { it.kind is PaymentKind.Onchain }.forEach { payment ->
val kind = payment.kind as? PaymentKind.Onchain ?: return@forEach
val channelId = findChannelForTransaction(kind.txid, payment.direction)
if (channelId != null) {
channelIdsByTxId[kind.txid] = channelId
}
}
return@withContext channelIdsByTxId
}
private suspend fun findChannelForTransaction(txid: String, direction: PaymentDirection): String? {
return if (direction == PaymentDirection.OUTBOUND) {
findOpenChannelForTransaction(txid)
} else {
findClosedChannelForTransaction(txid)
}
}
private fun findOpenChannelForTransaction(txid: String): String? {
return try {
val channels = lightningRepo.lightningState.value.channels
if (channels.isEmpty()) return null
channels.firstOrNull { channel ->
channel.fundingTxo?.txid == txid
}?.channelId
?: run {
val orders = blocktankRepo.blocktankState.value.orders
val matchingOrder = orders.firstOrNull { order ->
order.payment?.onchain?.transactions?.any { it.txId == txid } == true
} ?: return null
val orderChannel = matchingOrder.channel ?: return null
channels.firstOrNull { channel ->
channel.fundingTxo?.txid == orderChannel.fundingTx.id
}?.channelId
}
} catch (e: Exception) {
Logger.warn("Failed to find open channel for transaction: $txid", e, context = TAG)
null
}
}
private suspend fun findClosedChannelForTransaction(txid: String): String? {
return coreService.activity.findClosedChannelForTransaction(txid, null)
}
suspend fun getOnchainActivityByTxId(txid: String): OnchainActivity? {
return coreService.activity.getOnchainActivityByTxId(txid)
}
/**
* Checks if a transaction is inbound (received) by looking up the payment direction.
*/
suspend fun isReceivedTransaction(txid: String): Boolean = withContext(bgDispatcher) {
lightningRepo.getPayments().getOrNull()?.let { payments ->
payments.firstOrNull { payment ->
(payment.kind as? PaymentKind.Onchain)?.txid == txid
}
}?.direction == PaymentDirection.INBOUND
}
/**
* Checks if a transaction was replaced (RBF) by checking if the activity exists but `doesExist=false`.
*/
suspend fun wasTransactionReplaced(txid: String): Boolean = withContext(bgDispatcher) {
val onchainActivity = getOnchainActivityByTxId(txid) ?: return@withContext false
return@withContext !onchainActivity.doesExist
}
suspend fun handleOnchainTransactionReceived(
txid: String,
details: TransactionDetails,
) {
coreService.activity.handleOnchainTransactionReceived(txid, details)
notifyActivitiesChanged()
}
suspend fun handleOnchainTransactionConfirmed(
txid: String,
details: TransactionDetails,
) {
coreService.activity.handleOnchainTransactionConfirmed(txid, details)
notifyActivitiesChanged()
}
suspend fun handleOnchainTransactionReplaced(txid: String, conflicts: List<String>) {
coreService.activity.handleOnchainTransactionReplaced(txid, conflicts)
notifyActivitiesChanged()
}
suspend fun handleOnchainTransactionReorged(txid: String) {
coreService.activity.handleOnchainTransactionReorged(txid)
notifyActivitiesChanged()
}
suspend fun handleOnchainTransactionEvicted(txid: String) {
coreService.activity.handleOnchainTransactionEvicted(txid)
notifyActivitiesChanged()
}
suspend fun handlePaymentEvent(paymentHash: String) {
coreService.activity.handlePaymentEvent(paymentHash)
notifyActivitiesChanged()
}
suspend fun shouldShowReceivedSheet(txid: String, value: ULong): Boolean {
return coreService.activity.shouldShowReceivedSheet(txid, value)
}
suspend fun isActivitySeen(activityId: String): Boolean {
return coreService.activity.isActivitySeen(activityId)
}
suspend fun markActivityAsSeen(activityId: String) {
coreService.activity.markActivityAsSeen(activityId)
notifyActivitiesChanged()
}
suspend fun markOnchainActivityAsSeen(txid: String) {
coreService.activity.markOnchainActivityAsSeen(txid)
notifyActivitiesChanged()
}
suspend fun getTransactionDetails(txid: String): Result<BitkitCoreTransactionDetails?> = runCatching {
coreService.activity.getTransactionDetails(txid)
}
suspend fun getBoostTxDoesExist(boostTxIds: List<String>): Map<String, Boolean> {
return coreService.activity.getBoostTxDoesExist(boostTxIds)
}
suspend fun isCpfpChildTransaction(txId: String): Boolean {
return coreService.activity.isCpfpChildTransaction(txId)
}
suspend fun getTxIdsInBoostTxIds(): Set<String> {
return coreService.activity.getTxIdsInBoostTxIds()
}
/**
* Gets a specific activity by payment hash or txID with retry logic
*/
suspend fun findActivityByPaymentId(
paymentHashOrTxId: String,
type: ActivityFilter,
txType: PaymentType?,
retry: Boolean = true,
): Result<Activity> = withContext(bgDispatcher) {
if (paymentHashOrTxId.isEmpty()) {
return@withContext Result.failure(
IllegalArgumentException("paymentHashOrTxId is empty")
)
}
return@withContext try {
suspend fun findActivity(): Activity? = getActivities(
filter = type,
txType = txType,
limit = 10u
).getOrNull()?.firstOrNull { it.matchesPaymentId(paymentHashOrTxId) }
var activity = findActivity()
if (activity == null && retry) {
Logger.warn(
"activity with paymentHashOrTxId:$paymentHashOrTxId not found, trying again after sync",
context = TAG
)
lightningRepo.sync().onSuccess {
Logger.debug("Syncing LN node SUCCESS", context = TAG)
}
syncActivities().onSuccess {
Logger.debug(
"Sync success, searching again the activity with paymentHashOrTxId:$paymentHashOrTxId",
context = TAG
)
activity = findActivity()
}
}
if (activity != null) {
Result.success(activity)
} else {
Result.failure(IllegalStateException("Activity not found"))
}
} catch (e: Exception) {
Logger.error(
"findActivityByPaymentId error. Parameters:" +
"\n paymentHashOrTxId:$paymentHashOrTxId type:$type txType:$txType",
context = TAG
)
Result.failure(e)
}
}
suspend fun getActivities(
filter: ActivityFilter? = null,
txType: PaymentType? = null,
tags: List<String>? = null,
search: String? = null,
minDate: ULong? = null,
maxDate: ULong? = null,
limit: UInt? = null,
sortDirection: SortDirection? = null,
): Result<List<Activity>> = withContext(bgDispatcher) {
return@withContext runCatching {
coreService.activity.get(filter, txType, tags, search, minDate, maxDate, limit, sortDirection)
}.onFailure { e ->
Logger.error(
"getActivities error. Parameters:" +
"\nfilter:$filter " +
"txType:$txType " +
"tags:$tags " +
"search:$search " +
"minDate:$minDate " +
"maxDate:$maxDate " +
"limit:$limit " +
"sortDirection:$sortDirection",
e = e,
context = TAG
)
}
}
suspend fun getActivity(id: String): Result<Activity?> = withContext(bgDispatcher) {
return@withContext runCatching {
coreService.activity.getActivity(id)
}.onFailure { e ->
Logger.error("getActivity error for ID: $id", e, context = TAG)
}
}
suspend fun getClosedChannels(
sortDirection: SortDirection = SortDirection.ASC,
): Result<List<ClosedChannelDetails>> = withContext(bgDispatcher) {
return@withContext runCatching {
coreService.activity.closedChannels(sortDirection)
}.onFailure { e ->
Logger.error("Error getting closed channels (sortDirection=$sortDirection)", e, context = TAG)
}
}
/**
* Updates an activity
* @param forceUpdate use it if you want update a deleted activity
*/
suspend fun updateActivity(
id: String,
activity: Activity,
forceUpdate: Boolean = false,
): Result<Unit> = withContext(bgDispatcher) {
return@withContext runCatching {
if (id in cacheStore.data.first().deletedActivities && !forceUpdate) {
Logger.debug("Activity $id was deleted", context = TAG)
return@withContext Result.failure(
Exception(
"Activity $id was deleted. If you want update it, set forceUpdate as true"
)
)
}
coreService.activity.update(id, activity)
notifyActivitiesChanged()
}.onFailure { e ->
Logger.error("updateActivity error for ID: $id", e, context = TAG)
}
}
/**
* Updates an activity and marks the old one as removed from mempool (for RBF).
* In case of failure in the update or marking as removed, the data will be cached
* to try again on the next sync.
*/
suspend fun replaceActivity(
id: String,
activityIdToDelete: String,
activity: Activity,
): Result<Unit> = withContext(bgDispatcher) {
return@withContext updateActivity(
id = id,
activity = activity
).fold(
onSuccess = {
Logger.debug(
"Activity $id updated with success. new data: $activity",
context = TAG
)
val tags = coreService.activity.tags(activityIdToDelete)
addTagsToActivity(activityId = id, tags = tags)
Result.success(Unit)
},
onFailure = { e ->
Logger.error(
"Update activity fail. Parameters: id:$id, " +
"activityIdToDelete:$activityIdToDelete activity:$activity",
e = e,
context = TAG
)
Result.failure(e)
}
)
}
private suspend fun boostPendingActivities() = withContext(bgDispatcher) {
cacheStore.data.first().pendingBoostActivities.map { pendingBoostActivity ->
async {
findActivityByPaymentId(
paymentHashOrTxId = pendingBoostActivity.txId,
type = ActivityFilter.ONCHAIN,
txType = PaymentType.SENT
).onSuccess { activityToUpdate ->
Logger.debug("boostPendingActivities = Activity found: ${activityToUpdate.rawId()}", context = TAG)
val newOnChainActivity = activityToUpdate as? Activity.Onchain ?: return@onSuccess
if ((newOnChainActivity.v1.updatedAt ?: 0u) > pendingBoostActivity.updatedAt) {
cacheStore.removeActivityFromPendingBoost(pendingBoostActivity)
return@onSuccess
}
val updatedBoostTxIds = if (pendingBoostActivity.parentTxId != null) {
newOnChainActivity.v1.boostTxIds + pendingBoostActivity.parentTxId
} else {
newOnChainActivity.v1.boostTxIds
}
val updatedActivity = Activity.Onchain(
v1 = newOnChainActivity.v1.copy(
isBoosted = true,
boostTxIds = updatedBoostTxIds,
updatedAt = pendingBoostActivity.updatedAt
)
)
if (pendingBoostActivity.activityToDelete != null) {
replaceActivity(
id = updatedActivity.v1.id,
activity = updatedActivity,
activityIdToDelete = pendingBoostActivity.activityToDelete
).onSuccess {
cacheStore.removeActivityFromPendingBoost(pendingBoostActivity)
}
} else {
updateActivity(
id = updatedActivity.v1.id,
activity = updatedActivity
).onSuccess {
cacheStore.removeActivityFromPendingBoost(pendingBoostActivity)
}
}
}
}
}.awaitAll()
}
suspend fun deleteActivity(id: String): Result<Unit> = withContext(bgDispatcher) {
return@withContext runCatching {
val deleted = coreService.activity.delete(id)
if (deleted) {
cacheStore.addActivityToDeletedList(id)
notifyActivitiesChanged()
} else {
return@withContext Result.failure(Exception("Activity not deleted"))
}
}.onFailure { e ->
Logger.error("deleteActivity error for ID: $id", e, context = TAG)
}
}
suspend fun insertActivity(activity: Activity): Result<Unit> = withContext(bgDispatcher) {
return@withContext runCatching {
if (activity.rawId() in cacheStore.data.first().deletedActivities) {
Logger.debug("Activity ${activity.rawId()} was deleted, skipping", context = TAG)
return@withContext Result.failure(Exception("Activity ${activity.rawId()} was deleted"))
}
coreService.activity.insert(activity)
notifyActivitiesChanged()
}.onFailure { e ->
Logger.error("insertActivity error", e, context = TAG)
}
}
suspend fun upsertActivity(activity: Activity): Result<Unit> = withContext(bgDispatcher) {
return@withContext runCatching {
if (activity.rawId() in cacheStore.data.first().deletedActivities) {
Logger.debug("Activity ${activity.rawId()} was deleted, skipping", context = TAG)
return@withContext Result.failure(Exception("Activity ${activity.rawId()} was deleted"))
}
coreService.activity.upsert(activity)
notifyActivitiesChanged()
}.onFailure { e ->
Logger.error("upsertActivity error", e, context = TAG)
}
}
/**
* Inserts a new activity for a fulfilled (channel ready) CJIT order
*/
suspend fun insertActivityFromCjit(
cjitEntry: IcJitEntry?,
channel: ChannelDetails,
): Result<Unit> = withContext(bgDispatcher) {
runCatching {
requireNotNull(cjitEntry)
val amount = channel.amountOnClose
val now = nowTimestamp().epochSecond.toULong()
return@withContext insertActivity(
Activity.Lightning(
LightningActivity(
id = channel.fundingTxo?.txid.orEmpty(),
txType = PaymentType.RECEIVED,
status = PaymentState.SUCCEEDED,
value = amount,
fee = 0U,
invoice = cjitEntry.invoice.request,
message = "",
timestamp = now,
preimage = null,
createdAt = now,
updatedAt = null,
seenAt = null,
)
)
)
}.onFailure { e ->
Logger.error("insertActivity error", e, context = TAG)
}
}
suspend fun addActivityToPendingBoost(pendingBoostActivity: PendingBoostActivity) = withContext(bgDispatcher) {
cacheStore.addActivityToPendingBoost(pendingBoostActivity)
}
@VisibleForTesting
suspend fun addTagsToActivity(
activityId: String,
tags: List<String>,
): Result<Unit> = withContext(bgDispatcher) {
return@withContext runCatching {
checkNotNull(coreService.activity.getActivity(activityId)) { "Activity with ID $activityId not found" }
val existingTags = coreService.activity.tags(activityId)
val newTags = tags.filter { it.isNotBlank() && it !in existingTags }
if (newTags.isNotEmpty()) {
coreService.activity.appendTags(activityId, newTags).getOrThrow()
notifyActivitiesChanged()
Logger.info("Added ${newTags.size} new tags to activity $activityId", context = TAG)
} else {
Logger.info("No new tags to add to activity $activityId", context = TAG)
}
}.onFailure { e ->
Logger.error("addTagsToActivity error for activity $activityId", e, context = TAG)
}
}
/**
* Adds tags to an activity with business logic validation
*/
suspend fun addTagsToTransaction(
paymentHashOrTxId: String,
type: ActivityFilter,
txType: PaymentType?,
tags: List<String>,
): Result<Unit> = withContext(bgDispatcher) {
if (tags.isEmpty()) return@withContext Result.failure(IllegalArgumentException("No tags selected"))
return@withContext findActivityByPaymentId(
paymentHashOrTxId = paymentHashOrTxId,
type = type,
txType = txType
).mapCatching { activity ->
addTagsToActivity(activity.rawId(), tags = tags).getOrThrow()
}
}
/**
* Removes tags from an activity
*/
suspend fun removeTagsFromActivity(activityId: String, tags: List<String>): Result<Unit> =
withContext(bgDispatcher) {
return@withContext runCatching {
checkNotNull(coreService.activity.getActivity(activityId)) { "Activity with ID $activityId not found" }
coreService.activity.dropTags(activityId, tags)
notifyActivitiesChanged()
Logger.info("Removed ${tags.size} tags from activity $activityId", context = TAG)
}.onFailure { e ->
Logger.error("removeTagsFromActivity error for activity $activityId", e, context = TAG)
}
}
/**
* Gets all tags for an activity
*/
suspend fun getActivityTags(activityId: String): Result<List<String>> = withContext(bgDispatcher) {
return@withContext runCatching {
coreService.activity.tags(activityId)
}.onFailure { e ->
Logger.error("getActivityTags error for activity $activityId", e, context = TAG)
}
}
suspend fun getAllAvailableTags(): Result<List<String>> = withContext(bgDispatcher) {
return@withContext runCatching {
coreService.activity.allPossibleTags()
}.onSuccess { tags ->
_state.update { it.copy(tags = tags) }
}.onFailure { e ->
Logger.error("getAllAvailableTags error", e, context = TAG)
}
}
/**
* Get all [ActivityTags] for backup
*/
suspend fun getAllActivitiesTags(): Result<List<ActivityTags>> = withContext(bgDispatcher) {
return@withContext runCatching {
coreService.activity.getAllActivitiesTags()
}.onFailure { e ->
Logger.error("getAllActivityTags error", e, context = TAG)
}
}
suspend fun restoreFromBackup(payload: ActivityBackupV1): Result<Unit> = withContext(bgDispatcher) {
return@withContext runCatching {
coreService.activity.upsertList(payload.activities)
coreService.activity.upsertTags(payload.activityTags)
coreService.activity.upsertClosedChannelList(payload.closedChannels)
}.onSuccess {
Logger.debug(
"Restored ${payload.activities.size} activities, ${payload.activityTags.size} activity tags, " +
"${payload.closedChannels.size} closed channels",
context = TAG,
)
notifyActivitiesChanged()
}
}
suspend fun markAllUnseenActivitiesAsSeen(): Result<Unit> = withContext(bgDispatcher) {
return@withContext runCatching {
coreService.activity.markAllUnseenActivitiesAsSeen()
notifyActivitiesChanged()
}.onFailure { e ->
Logger.error("Failed to mark all activities as seen: $e", e, context = TAG)
}
}
// MARK: - Development/Testing Methods
/**
* Removes all activities
*/
suspend fun removeAllActivities(): Result<Unit> = withContext(bgDispatcher) {
return@withContext runCatching {
coreService.activity.removeAll()
Logger.info("Removed all activities", context = TAG)
}.onFailure { e ->
Logger.error("removeAllActivities error", e, context = TAG)
}
}
/**
* Generates random test data (regtest only) with business logic
*/
suspend fun generateTestData(count: Int = 100): Result<Unit> = withContext(bgDispatcher) {
return@withContext runCatching {
// Business logic: validate count is reasonable
val validatedCount = count.coerceIn(1, 1000)
if (validatedCount != count) {
Logger.warn("Adjusted test data count from $count to $validatedCount", context = TAG)
}
coreService.activity.generateRandomTestData(validatedCount)
Logger.info("Generated $validatedCount test activities", context = TAG)
}.onFailure { e ->
Logger.error("generateTestData error", e, context = TAG)
}
}
companion object {
private const val TAG = "ActivityRepo"
}
}
data class ActivityState(
val tags: List<String> = emptyList(),
)