damus

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

DisplayName.swift (1627B)


      1 //
      2 //  DisplayName.swift
      3 //  damus
      4 //
      5 //  Created by William Casarin on 2023-03-14.
      6 //
      7 
      8 import Foundation
      9 
     10 enum DisplayName: Equatable {
     11     case both(username: String, displayName: String)
     12     case one(String)
     13     
     14     var displayName: String {
     15         switch self {
     16         case .one(let one):
     17             return one
     18         case .both(username: _, displayName: let displayName):
     19             return displayName
     20         }
     21     }
     22     
     23     var username: String {
     24         switch self {
     25         case .one(let one):
     26             return one
     27         case .both(username: let username, displayName: _):
     28             return username
     29         }
     30     }
     31 }
     32 
     33 
     34 func parse_display_name(profile: Profile?, pubkey: Pubkey) -> DisplayName {
     35     if pubkey == ANON_PUBKEY {
     36         return .one(NSLocalizedString("Anonymous", comment: "Placeholder display name of anonymous user."))
     37     }
     38     
     39     guard let profile else {
     40         return .one(abbrev_bech32_pubkey(pubkey: pubkey))
     41     }
     42     
     43     let name = profile.name?.isEmpty == false ? profile.name : nil
     44     let disp_name = profile.display_name?.isEmpty == false ? profile.display_name : nil
     45     
     46     if let name, let disp_name, name != disp_name {
     47         return .both(username: name, displayName: disp_name)
     48     }
     49     
     50     if let one = name ?? disp_name {
     51         return .one(one)
     52     }
     53     
     54     return .one(abbrev_bech32_pubkey(pubkey: pubkey))
     55 }
     56 
     57 func abbrev_bech32_pubkey(pubkey: Pubkey) -> String {
     58     return abbrev_pubkey(String(pubkey.npub.dropFirst(4)))
     59 }
     60 
     61 func abbrev_pubkey(_ pubkey: String, amount: Int = 8) -> String {
     62     return pubkey.prefix(amount) + ":" + pubkey.suffix(amount)
     63 }