-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathActivityListViewModel.kt
More file actions
199 lines (167 loc) · 7.57 KB
/
Copy pathActivityListViewModel.kt
File metadata and controls
199 lines (167 loc) · 7.57 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
package to.bitkit.viewmodels
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.synonym.bitkitcore.Activity
import com.synonym.bitkitcore.ActivityFilter
import com.synonym.bitkitcore.PaymentType
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.collections.immutable.ImmutableList
import kotlinx.collections.immutable.ImmutableSet
import kotlinx.collections.immutable.persistentListOf
import kotlinx.collections.immutable.persistentSetOf
import kotlinx.collections.immutable.toImmutableList
import kotlinx.collections.immutable.toImmutableSet
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.FlowPreview
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.debounce
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import to.bitkit.di.BgDispatcher
import to.bitkit.ext.isReplacedSentTransaction
import to.bitkit.ext.isTransfer
import to.bitkit.models.PubkyProfile
import to.bitkit.repositories.ActivityRepo
import to.bitkit.repositories.PubkyRepo
import to.bitkit.ui.screens.wallets.activity.components.ActivityTab
import to.bitkit.utils.Logger
import javax.inject.Inject
@Suppress("TooManyFunctions")
@HiltViewModel
class ActivityListViewModel @Inject constructor(
@BgDispatcher private val bgDispatcher: CoroutineDispatcher,
private val activityRepo: ActivityRepo,
pubkyRepo: PubkyRepo,
) : ViewModel() {
private val _filteredActivities = MutableStateFlow<ImmutableList<Activity>?>(null)
val filteredActivities = _filteredActivities.asStateFlow()
private val _lightningActivities = MutableStateFlow<ImmutableList<Activity>?>(null)
val lightningActivities = _lightningActivities.asStateFlow()
private val _onchainActivities = MutableStateFlow<ImmutableList<Activity>?>(null)
val onchainActivities = _onchainActivities.asStateFlow()
private val _latestActivities = MutableStateFlow<ImmutableList<Activity>?>(null)
val latestActivities = _latestActivities.asStateFlow()
val contacts: StateFlow<ImmutableList<PubkyProfile>> =
pubkyRepo.contacts.map { it.toImmutableList() }.stateInScope(persistentListOf())
val availableTags: StateFlow<ImmutableList<String>> =
activityRepo.state.map { it.tags }.stateInScope(persistentListOf())
private val _filters = MutableStateFlow(ActivityFilters())
// individual filters for UI
val searchText: StateFlow<String> = _filters.map { it.searchText }.stateInScope("")
val startDate: StateFlow<Long?> = _filters.map { it.startDate }.stateInScope(null)
val endDate: StateFlow<Long?> = _filters.map { it.endDate }.stateInScope(null)
val selectedTags: StateFlow<ImmutableSet<String>> = _filters.map { it.tags.toImmutableSet() }.stateInScope(
persistentSetOf()
)
val selectedTab: StateFlow<ActivityTab> = _filters.map { it.tab }.stateInScope(ActivityTab.ALL)
fun setSearchText(text: String) = _filters.update { it.copy(searchText = text) }
fun setTab(tab: ActivityTab) = _filters.update { it.copy(tab = tab) }
fun toggleTag(tag: String) = _filters.update {
val newTags = if (tag in it.tags) it.tags - tag else it.tags + tag
it.copy(tags = newTags)
}
init {
observeActivities()
observeFilters()
resync()
}
fun resync() = viewModelScope.launch {
activityRepo.syncActivities()
}
private fun observeActivities() = viewModelScope.launch {
activityRepo.activitiesChanged.collect {
refreshActivityState()
}
}
private fun observeFilters() = viewModelScope.launch {
@OptIn(FlowPreview::class)
combine(
_filters.map { it.searchText }.debounce(300),
_filters.map { it.copy(searchText = "") },
activityRepo.activitiesChanged,
) { debouncedSearch, filtersWithoutSearch, _ ->
fetchFilteredActivities(filtersWithoutSearch.copy(searchText = debouncedSearch))
}.collect { activities ->
_filteredActivities.update { activities?.toImmutableList() }
}
}
private suspend fun refreshActivityState() {
val all = activityRepo.getActivities(filter = ActivityFilter.ALL).getOrNull() ?: emptyList()
val filtered = filterOutReplacedSentTransactions(all)
_latestActivities.update { filtered.take(SIZE_LATEST).toImmutableList() }
_lightningActivities.update { filtered.filterIsInstance<Activity.Lightning>().toImmutableList() }
_onchainActivities.update { filtered.filterIsInstance<Activity.Onchain>().toImmutableList() }
}
private suspend fun fetchFilteredActivities(filters: ActivityFilters): List<Activity>? {
val txType = when (filters.tab) {
ActivityTab.SENT -> PaymentType.SENT
ActivityTab.RECEIVED -> PaymentType.RECEIVED
else -> null
}
val activities = activityRepo.getActivities(
filter = ActivityFilter.ALL,
txType = txType,
tags = filters.tags.takeIf { it.isNotEmpty() }?.toList(),
search = filters.searchText.takeIf { it.isNotEmpty() },
minDate = filters.startDate?.let { it / 1000 }?.toULong(),
maxDate = filters.endDate?.let { it / 1000 }?.toULong(),
).getOrElse {
Logger.error("Failed to filter activities", it, context = TAG)
return null
}
val filteredByTab = when (filters.tab) {
ActivityTab.OTHER -> activities.filter { it.isTransfer() }
ActivityTab.SENT, ActivityTab.RECEIVED -> activities.filterNot { it.isTransfer() }
else -> activities
}
return filterOutReplacedSentTransactions(filteredByTab)
}
private suspend fun filterOutReplacedSentTransactions(activities: List<Activity>): List<Activity> {
val txIdsInBoostTxIds = activityRepo.getTxIdsInBoostTxIds()
return activities.filterNot { it.isReplacedSentTransaction(txIdsInBoostTxIds) }
}
fun updateAvailableTags() {
viewModelScope.launch {
activityRepo.getAllAvailableTags()
}
}
fun setDateRange(startDate: Long?, endDate: Long?) = _filters.update {
it.copy(startDate = startDate, endDate = endDate)
}
fun clearDateRange() = _filters.update {
it.copy(startDate = null, endDate = null)
}
fun clearFilters() = _filters.update { ActivityFilters() }
fun generateRandomTestData(count: Int) = viewModelScope.launch(bgDispatcher) {
activityRepo.generateTestData(count)
}
fun removeAllActivities() = viewModelScope.launch(bgDispatcher) {
activityRepo.removeAllActivities()
}
suspend fun isCpfpChildTransaction(txId: String): Boolean {
return activityRepo.isCpfpChildTransaction(txId)
}
private fun <T> Flow<T>.stateInScope(
initialValue: T,
started: SharingStarted = SharingStarted.WhileSubscribed(MS_TIMEOUT_SUB),
): StateFlow<T> = stateIn(viewModelScope, started, initialValue)
companion object {
private const val TAG = "ActivityListViewModel"
private const val SIZE_LATEST = 4
private const val MS_TIMEOUT_SUB = 5000L
}
}
data class ActivityFilters(
val tab: ActivityTab = ActivityTab.ALL,
val tags: Set<String> = emptySet(),
val searchText: String = "",
val startDate: Long? = null,
val endDate: Long? = null,
)