damus

nostr ios client
git clone git://jb55.com/damus
Log | Files | Refs | README | LICENSE

Referenced.swift (2063B)


      1 //
      2 //  Referenced.swift
      3 //  damus
      4 //
      5 //  Created by William Casarin on 2023-07-28.
      6 //
      7 
      8 import Foundation
      9 
     10 enum Marker: String {
     11     case root
     12     case reply
     13     case mention
     14 
     15     init?(_ tag: TagElem) {
     16         let len = tag.count
     17 
     18         if len == 4, tag.matches_str("root", tag_len: len) {
     19             self = .root
     20         } else if len == 5, tag.matches_str("reply", tag_len: len) {
     21             self = .reply
     22         } else if len == 7, tag.matches_str("mention", tag_len: len) {
     23             self = .mention
     24         } else {
     25             return nil
     26         }
     27     }
     28 }
     29 
     30 struct NoteRef: IdType, TagConvertible, Equatable {
     31     let note_id: NoteId
     32     let relay: String?
     33     let marker: Marker?
     34 
     35     var id: Data {
     36         self.note_id.id
     37     }
     38 
     39     init(note_id: NoteId, relay: String? = nil, marker: Marker? = nil) {
     40         self.note_id = note_id
     41         self.relay = relay
     42         self.marker = marker
     43     }
     44 
     45     static func note_id(_ note_id: NoteId) -> NoteRef {
     46         return NoteRef(note_id: note_id)
     47     }
     48 
     49     init(_ data: Data) {
     50         self.note_id = NoteId(data)
     51         self.relay = nil
     52         self.marker = nil
     53     }
     54 
     55     var tag: [String] {
     56         var t = ["e", self.hex()]
     57         if let marker {
     58             t.append(relay ?? "")
     59             t.append(marker.rawValue)
     60         } else if let relay {
     61             t.append(relay)
     62         }
     63         return t
     64     }
     65 
     66     static func from_tag(tag: TagSequence) -> NoteRef? {
     67         guard tag.count >= 2 else { return nil }
     68 
     69         var i = tag.makeIterator()
     70 
     71         guard let t0 = i.next(),
     72               t0.single_char == "e",
     73               let t1 = i.next(),
     74               let note_id = t1.id().map(NoteId.init)
     75         else {
     76             return nil
     77         }
     78 
     79         var relay: String? = nil
     80         var marker: Marker? = nil
     81 
     82         if tag.count >= 3, let r = i.next() {
     83             relay = r.string()
     84             if tag.count >= 4, let m = i.next() {
     85                 marker = Marker(m)
     86             }
     87         }
     88 
     89         return NoteRef(note_id: note_id, relay: relay, marker: marker)
     90     }
     91 }