-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathActivityListViewModel.swift
More file actions
509 lines (439 loc) · 18.4 KB
/
Copy pathActivityListViewModel.swift
File metadata and controls
509 lines (439 loc) · 18.4 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
import BitkitCore
import Combine
import SwiftUI
enum ActivityTab: CaseIterable, CustomStringConvertible {
case all, sent, received, other
var description: String {
switch self {
case .all:
return t("wallet__activity_tabs__all")
case .sent:
return t("wallet__activity_tabs__sent")
case .received:
return t("wallet__activity_tabs__received")
case .other:
return t("wallet__activity_tabs__other")
}
}
}
@MainActor
class ActivityListViewModel: ObservableObject {
@Published var filteredActivities: [Activity]? = nil
@Published var lightningActivities: [Activity]? = nil
@Published var onchainActivities: [Activity]? = nil
@Published var searchText: String = ""
@Published var startDate: Date?
@Published var endDate: Date?
@Published var selectedTags: Set<String> = []
@Published var selectedTab: ActivityTab = .all
/// Latest activities for home screen
@Published var latestActivities: [Activity]? = nil
/// Grouped activities for display
@Published var groupedActivities: [ActivityGroupItem] = []
private let coreService: CoreService
private let lightningService: LightningService
private let transferService: TransferService
private var searchCancellable: AnyCancellable?
private var dateRangeCancellable: AnyCancellable?
private var tagsCancellable: AnyCancellable?
private var tabCancellable: AnyCancellable?
private var activitiesChangedCancellable: AnyCancellable?
@Published private(set) var availableTags: [String] = []
var activitiesChangedPublisher: AnyPublisher<Void, Never> {
coreService.activity.activitiesChangedPublisher
}
private func updateAvailableTags() async {
do {
availableTags = try await coreService.activity.allPossibleTags()
} catch {
Logger.error(error, context: "Failed to get available tags")
availableTags = []
}
}
init(
coreService: CoreService = .shared,
lightningService: LightningService = .shared,
transferService: TransferService
) {
self.coreService = coreService
self.lightningService = lightningService
self.transferService = transferService
// Setup search text subscription with debounce
searchCancellable =
$searchText
.debounce(for: .milliseconds(300), scheduler: DispatchQueue.main)
.sink { [weak self] _ in
Task { [weak self] in
await self?.updateFilteredActivities()
}
}
// Setup date range subscription
dateRangeCancellable = Publishers.CombineLatest($startDate, $endDate)
.sink { [weak self] _, _ in
Task { [weak self] in
await self?.updateFilteredActivities()
}
}
// Setup tags subscription
tagsCancellable =
$selectedTags
.sink { [weak self] _ in
Task { [weak self] in
await self?.updateFilteredActivities()
}
}
// Setup tab subscription
tabCancellable =
$selectedTab
.sink { [weak self] _ in
Task { [weak self] in
await self?.updateFilteredActivities()
}
}
activitiesChangedCancellable = coreService.activity.activitiesChangedPublisher
.receive(on: DispatchQueue.main)
.sink { [weak self] _ in
Task { [weak self] in
await self?.syncState()
}
}
Task {
await syncState()
}
}
/// Convenience initializer for testing and previews
convenience init(
coreService: CoreService = .shared,
lightningService: LightningService = .shared
) {
let transferService = TransferService(
lightningService: lightningService,
blocktankService: coreService.blocktank
)
self.init(
coreService: coreService,
lightningService: lightningService,
transferService: transferService
)
}
func syncState() async {
do {
// Get latest activities first as that's displayed on the home view
let limitLatest = UInt32(ActivityDisplayConstants.maxHomeActivityItems)
// Fetch extra to account for potential filtering of replaced transactions
let latest = try await coreService.activity.get(filter: .all, limit: limitLatest * 3)
let filtered = await filterOutReplacedSentTransactions(latest)
latestActivities = Array(filtered.prefix(Int(limitLatest)))
// Fetch all activities
await updateFilteredActivities()
lightningActivities = try await coreService.activity.get(filter: .lightning)
let onchain = try await coreService.activity.get(filter: .onchain)
onchainActivities = await filterOutReplacedSentTransactions(onchain)
// Update available tags
await updateAvailableTags()
} catch {
Logger.error(error, context: "Failed to sync activities")
}
}
func clearDateRange() {
startDate = nil
endDate = nil
}
func clearTags() {
selectedTags.removeAll()
}
func resetFilters() {
searchText = ""
startDate = nil
endDate = nil
selectedTags.removeAll()
selectedTab = .all
}
private func updateFilteredActivities() async {
do {
// Convert dates to timestamps if they exist, ensuring start date is start of day and end date is end of day
let minDate = startDate.map {
let startOfDay = Calendar.current.startOfDay(for: $0)
return UInt64(startOfDay.timeIntervalSince1970)
}
let maxDate = endDate.map {
let nextDay = Calendar.current.startOfDay(for: Calendar.current.date(byAdding: .day, value: 1, to: $0) ?? $0)
return UInt64(nextDay.timeIntervalSince1970 - 1)
}
// Apply base filtering
let baseFilteredActivities = try await coreService.activity.get(
filter: .all,
tags: selectedTags.isEmpty ? nil : Array(selectedTags),
search: searchText.isEmpty ? nil : searchText,
minDate: minDate,
maxDate: maxDate
)
// Filter out replaced sent transactions that appear in another transaction's boostTxIds
let filteredOutReplaced = await filterOutReplacedSentTransactions(baseFilteredActivities)
// Apply tab filtering
filteredActivities = filterActivitiesByTab(filteredOutReplaced, selectedTab: selectedTab)
// Update grouped activities
updateGroupedActivities()
} catch {
Logger.error(error, context: "Failed to filter activities")
}
}
private var isSyncingLdkNodePayments: Bool = false
func syncLdkNodePayments() async throws {
guard !isSyncingLdkNodePayments else {
Logger.warn("LDK node payments are already being synced, skipping")
return
}
if let ldkPayments = lightningService.payments {
isSyncingLdkNodePayments = true
do {
try await coreService.activity.syncLdkNodePayments(ldkPayments)
await syncState()
// This ensures pending transfers are marked as settled when channels become ready
do {
try await transferService.syncTransferStates()
Logger.debug("Transfer states synced after LDK payments sync", context: "ActivityListViewModel")
} catch {
Logger.error("Failed to sync transfer states after LDK payments sync", context: error.localizedDescription)
// Don't throw - we don't want to fail the entire sync if transfer sync fails
}
isSyncingLdkNodePayments = false
} catch {
isSyncingLdkNodePayments = false
throw error
}
}
}
// MARK: - Tag Methods
func getActivities(withTag tag: String) async throws -> [Activity] {
try await coreService.activity.get(tags: [tag])
}
/// Find activity by payment hash or transaction ID
func findActivity(byPaymentId paymentId: String) async throws -> Activity {
guard !paymentId.isEmpty else {
throw AppError(message: "Payment ID is empty", debugMessage: nil)
}
let activities = try await coreService.activity.get(filter: .all, limit: 50)
let activity = activities.first { activity in
switch activity {
case let .lightning(ln):
return ln.id == paymentId
case let .onchain(on):
return on.txId == paymentId
}
}
guard let activity else {
throw AppError(
message: "Activity not found",
debugMessage: "Could not find activity for payment ID: \(paymentId)"
)
}
return activity
}
func contactActivities(publicKey: String) async throws -> [Activity] {
try await coreService.activity.get(contact: publicKey, sortDirection: .desc)
}
func setContact(_ contactPublicKey: String, forPaymentId paymentId: String, syncLdkPayments: Bool = true) async throws {
if syncLdkPayments {
try? await syncLdkNodePayments()
}
try await coreService.activity.setContact(contactPublicKey, forActivity: paymentId)
await syncState()
}
func getAllPossibleTags() async throws -> [String] {
try await coreService.activity.allPossibleTags()
}
func appendTags(toActivity activityId: String, tags: [String]) async throws {
try await coreService.activity.appendTags(toActivity: activityId, tags)
// Refresh the activities after adding a tag
await syncState()
}
func removeTag(fromActivity activityId: String, tag: String) async throws {
try await coreService.activity.dropTags(fromActivity: activityId, [tag])
// Refresh the activities after removing a tag
await syncState()
}
func getTagsForActivity(_ activityId: String) async throws -> [String] {
try await coreService.activity.tags(forActivity: activityId)
}
// MARK: - Boost Methods
func boost(activityId: String, feeRate: UInt32) async throws -> String {
do {
let txid = try await coreService.activity.boostOnchainTransaction(activityId: activityId, feeRate: feeRate)
// Refresh the activities after boosting
await syncState()
return txid
} catch {
Logger.error(error, context: "Failed to boost activity \(activityId)")
throw error
}
}
}
// MARK: - Activity Grouping
enum ActivityGroupItem: Hashable {
case header(String)
case activity(Activity)
}
extension ActivityListViewModel {
func groupActivities(_ activities: [Activity]) -> [ActivityGroupItem] {
let calendar = Calendar.current
let now = Date()
// Calculate date boundaries
let beginningOfDay = calendar.startOfDay(for: now)
let beginningOfYesterday = calendar.date(byAdding: .day, value: -1, to: beginningOfDay)!
let beginningOfWeek = calendar.dateInterval(of: .weekOfYear, for: now)?.start ?? now
let beginningOfMonth = calendar.dateInterval(of: .month, for: now)?.start ?? now
let beginningOfYear = calendar.dateInterval(of: .year, for: now)?.start ?? now
// Group activities
var today: [Activity] = []
var yesterday: [Activity] = []
var thisWeek: [Activity] = []
var thisMonth: [Activity] = []
var thisYear: [Activity] = []
var earlier: [Activity] = []
for activity in activities {
let timestamp: UInt64 = switch activity {
case let .lightning(ln):
ln.timestamp
case let .onchain(on):
on.timestamp
}
let activityDate = Date(timeIntervalSince1970: TimeInterval(timestamp))
if activityDate >= beginningOfDay {
today.append(activity)
} else if activityDate >= beginningOfYesterday {
yesterday.append(activity)
} else if activityDate >= beginningOfWeek {
thisWeek.append(activity)
} else if activityDate >= beginningOfMonth {
thisMonth.append(activity)
} else if activityDate >= beginningOfYear {
thisYear.append(activity)
} else {
earlier.append(activity)
}
}
// Build result array using localized headers
var result: [ActivityGroupItem] = []
if !today.isEmpty {
let headerDate =
today.first.map { activity in
let timestamp: UInt64 = switch activity {
case let .lightning(ln): ln.timestamp
case let .onchain(on): on.timestamp
}
return Date(timeIntervalSince1970: TimeInterval(timestamp))
} ?? now
result.append(.header(DateFormatterHelpers.getActivityGroupHeader(for: headerDate)))
result.append(contentsOf: today.map { .activity($0) })
}
if !yesterday.isEmpty {
let headerDate =
yesterday.first.map { activity in
let timestamp: UInt64 = switch activity {
case let .lightning(ln): ln.timestamp
case let .onchain(on): on.timestamp
}
return Date(timeIntervalSince1970: TimeInterval(timestamp))
} ?? beginningOfYesterday
result.append(.header(DateFormatterHelpers.getActivityGroupHeader(for: headerDate)))
result.append(contentsOf: yesterday.map { .activity($0) })
}
if !thisWeek.isEmpty {
let headerDate =
thisWeek.first.map { activity in
let timestamp: UInt64 = switch activity {
case let .lightning(ln): ln.timestamp
case let .onchain(on): on.timestamp
}
return Date(timeIntervalSince1970: TimeInterval(timestamp))
} ?? beginningOfWeek
result.append(.header(DateFormatterHelpers.getActivityGroupHeader(for: headerDate)))
result.append(contentsOf: thisWeek.map { .activity($0) })
}
if !thisMonth.isEmpty {
let headerDate =
thisMonth.first.map { activity in
let timestamp: UInt64 = switch activity {
case let .lightning(ln): ln.timestamp
case let .onchain(on): on.timestamp
}
return Date(timeIntervalSince1970: TimeInterval(timestamp))
} ?? beginningOfMonth
result.append(.header(DateFormatterHelpers.getActivityGroupHeader(for: headerDate)))
result.append(contentsOf: thisMonth.map { .activity($0) })
}
if !thisYear.isEmpty {
let headerDate =
thisYear.first.map { activity in
let timestamp: UInt64 = switch activity {
case let .lightning(ln): ln.timestamp
case let .onchain(on): on.timestamp
}
return Date(timeIntervalSince1970: TimeInterval(timestamp))
} ?? beginningOfYear
result.append(.header(DateFormatterHelpers.getActivityGroupHeader(for: headerDate)))
result.append(contentsOf: thisYear.map { .activity($0) })
}
if !earlier.isEmpty {
let headerDate =
earlier.first.map { activity in
let timestamp: UInt64 = switch activity {
case let .lightning(ln): ln.timestamp
case let .onchain(on): on.timestamp
}
return Date(timeIntervalSince1970: TimeInterval(timestamp))
} ?? Date.distantPast
result.append(.header(DateFormatterHelpers.getActivityGroupHeader(for: headerDate)))
result.append(contentsOf: earlier.map { .activity($0) })
}
return result
}
private func updateGroupedActivities() {
if let activities = filteredActivities {
groupedActivities = groupActivities(activities)
} else {
groupedActivities = []
}
}
/// Filter out replaced sent transactions that appear in another transaction's boostTxIds
private func filterOutReplacedSentTransactions(_ activities: [Activity]) async -> [Activity] {
// Get cached set of txIds that appear in boostTxIds
let txIdsInBoostTxIds = await coreService.activity.getTxIdsInBoostTxIds()
return activities.filter { !$0.isReplacedSentTransaction(txIdsInBoostTxIds: txIdsInBoostTxIds) }
}
/// Filter activities based on the selected tab
private func filterActivitiesByTab(_ activities: [Activity], selectedTab: ActivityTab) -> [Activity] {
switch selectedTab {
case .all:
return activities
case .sent:
return activities.filter { activity in
switch activity {
case let .lightning(ln):
return ln.txType == .sent
case let .onchain(on):
return on.txType == .sent && !on.isTransfer
}
}
case .received:
return activities.filter { activity in
switch activity {
case let .lightning(ln):
return ln.txType == .received
case let .onchain(on):
return on.txType == .received && !on.isTransfer
}
}
case .other:
return activities.filter { activity in
switch activity {
case .lightning:
return false // Lightning activities are never transfers
case let .onchain(on):
return on.isTransfer
}
}
}
}
}