ZapsModel.swift (2126B)
1 // 2 // ZapsModel.swift 3 // damus 4 // 5 // Created by William Casarin on 2023-02-10. 6 // 7 8 import Foundation 9 10 class ZapsModel: ObservableObject { 11 let state: DamusState 12 let target: ZapTarget 13 14 let zaps_subid = UUID().description 15 let profiles_subid = UUID().description 16 17 init(state: DamusState, target: ZapTarget) { 18 self.state = state 19 self.target = target 20 } 21 22 var zaps: [Zapping] { 23 return state.events.lookup_zaps(target: target) 24 } 25 26 func subscribe() { 27 var filter = NostrFilter(kinds: [.zap]) 28 switch target { 29 case .profile(let profile_id): 30 filter.pubkeys = [profile_id] 31 case .note(let note_target): 32 filter.referenced_ids = [note_target.note_id] 33 } 34 state.pool.subscribe(sub_id: zaps_subid, filters: [filter], handler: handle_event) 35 } 36 37 func unsubscribe() { 38 state.pool.unsubscribe(sub_id: zaps_subid) 39 } 40 41 @MainActor 42 func handle_event(relay_id: RelayURL, conn_ev: NostrConnectionEvent) { 43 guard case .nostr_event(let resp) = conn_ev else { 44 return 45 } 46 47 guard resp.subid == zaps_subid else { 48 return 49 } 50 51 switch resp { 52 case .ok: 53 break 54 case .notice: 55 break 56 case .eose: 57 let events = state.events.lookup_zaps(target: target).map { $0.request.ev } 58 guard let txn = NdbTxn(ndb: state.ndb) else { return } 59 load_profiles(context: "zaps_model", profiles_subid: profiles_subid, relay_id: relay_id, load: .from_events(events), damus_state: state, txn: txn) 60 case .event(_, let ev): 61 guard ev.kind == 9735, 62 let zapper = state.profiles.lookup_zapper(pubkey: target.pubkey), 63 let zap = Zap.from_zap_event(zap_ev: ev, zapper: zapper, our_privkey: state.keypair.privkey) 64 else { 65 return 66 } 67 68 self.state.add_zap(zap: .zap(zap)) 69 case .auth: 70 break 71 } 72 73 74 75 } 76 }