Zaps.swift (2818B)
1 // 2 // Zaps.swift 3 // damus 4 // 5 // Created by William Casarin on 2023-01-16. 6 // 7 8 import Foundation 9 10 class Zaps { 11 private(set) var zaps: [NoteId: Zapping] 12 let our_pubkey: Pubkey 13 var our_zaps: [NoteId: [Zapping]] 14 15 private(set) var event_counts: [NoteId: Int] 16 private(set) var event_totals: [NoteId: Int64] 17 18 init(our_pubkey: Pubkey) { 19 self.zaps = [:] 20 self.our_pubkey = our_pubkey 21 self.our_zaps = [:] 22 self.event_counts = [:] 23 self.event_totals = [:] 24 } 25 26 func remove_zap(reqid: NoteId) -> Zapping? { 27 var res: Zapping? = nil 28 for kv in our_zaps { 29 let ours = kv.value 30 guard let zap = ours.first(where: { z in z.request.ev.id == reqid }) else { 31 continue 32 } 33 34 res = zap 35 36 our_zaps[kv.key] = ours.filter { z in z.request.ev.id != reqid } 37 38 // counts for note zaps 39 if let note_id = zap.target.note_id { 40 if let count = event_counts[note_id] { 41 event_counts[note_id] = count - 1 42 } 43 if let total = event_totals[note_id] { 44 event_totals[note_id] = total - zap.amount 45 } 46 } 47 48 // we found the request id, we can stop looking 49 break 50 } 51 52 self.zaps.removeValue(forKey: reqid) 53 return res 54 } 55 56 func add_zap(zap: Zapping) { 57 if zaps[zap.request.ev.id] != nil { 58 return 59 } 60 self.zaps[zap.request.ev.id] = zap 61 62 if let zap_id = zap.event?.id { 63 self.zaps[zap_id] = zap 64 } 65 66 // record our zaps for an event 67 if zap.request.ev.pubkey == our_pubkey { 68 switch zap.target { 69 case .note(let note_zap): 70 let note_id = note_zap.note_id 71 if our_zaps[note_id] == nil { 72 our_zaps[note_id] = [zap] 73 } else { 74 insert_uniq_sorted_zap_by_amount(zaps: &(our_zaps[note_id]!), new_zap: zap) 75 } 76 case .profile: 77 break 78 } 79 } 80 81 // don't count tips to self. lame. 82 guard zap.request.ev.pubkey != zap.target.pubkey else { 83 return 84 } 85 86 if let note_id = zap.target.note_id { 87 if event_counts[note_id] == nil { 88 event_counts[note_id] = 0 89 } 90 91 if event_totals[note_id] == nil { 92 event_totals[note_id] = 0 93 } 94 95 event_counts[note_id] = event_counts[note_id]! + 1 96 event_totals[note_id] = event_totals[note_id]! + zap.amount 97 98 notify(.update_stats(note_id: note_id)) 99 } 100 } 101 }