LocalNotification.swift (2469B)
1 // 2 // LocalNotification.swift 3 // damus 4 // 5 // Created by William Casarin on 2023-04-15. 6 // 7 8 import Foundation 9 10 let NDB_NOTE_JSON_USER_INFO_KEY = "ndb_note_json" 11 12 struct LossyLocalNotification { 13 let type: LocalNotificationType 14 let mention: MentionRef 15 16 func to_user_info() -> [AnyHashable: Any] { 17 return [ 18 "type": self.type.rawValue, 19 "id": self.mention.bech32 20 ] 21 } 22 23 static func from_user_info(user_info: [AnyHashable: Any]) -> LossyLocalNotification? { 24 if let encoded_ndb_note = user_info[NDB_NOTE_JSON_USER_INFO_KEY] as? String { 25 return self.from(json_encoded_ndb_note: encoded_ndb_note) 26 } 27 guard let id = user_info["id"] as? String, 28 let target_id = MentionRef.from_bech32(str: id) else { 29 return nil 30 } 31 let typestr = user_info["type"] as! String 32 let type = LocalNotificationType(rawValue: typestr)! 33 34 return LossyLocalNotification(type: type, mention: target_id) 35 } 36 37 static func from(json_encoded_ndb_note: String) -> LossyLocalNotification? { 38 guard let ndb_note = NdbNote.owned_from_json(json: json_encoded_ndb_note) else { 39 return nil 40 } 41 return self.from(ndb_note: ndb_note) 42 } 43 44 static func from(ndb_note: NdbNote) -> LossyLocalNotification? { 45 guard let known_kind = ndb_note.known_kind, let type = LocalNotificationType.from(nostr_kind: known_kind) else { return nil } 46 let target: MentionRef = .note(ndb_note.id) 47 return LossyLocalNotification(type: type, mention: target) 48 } 49 } 50 51 struct LocalNotification { 52 let type: LocalNotificationType 53 let event: NostrEvent 54 let target: NostrEvent 55 let content: String 56 57 func to_lossy() -> LossyLocalNotification { 58 return LossyLocalNotification(type: self.type, mention: .note(self.target.id)) 59 } 60 } 61 62 enum LocalNotificationType: String { 63 case dm 64 case like 65 case mention 66 case repost 67 case zap 68 case profile_zap 69 70 static func from(nostr_kind: NostrKind) -> Self? { 71 switch nostr_kind { 72 case .text: 73 return .mention 74 case .dm: 75 return .dm 76 case .like: 77 return .like 78 case .longform: 79 return .mention 80 case .zap: 81 return .zap 82 default: 83 return nil 84 } 85 } 86 }