// // CryptoChatModelRealmMessage.swift // Wallet // // Created by Saveliy Stavitsky on 8/21/20. // Copyright © 2020 List. All rights reserved. // import UIKit import class RealmSwift.Object import struct RealmSwift.Persisted class CryptoChatModelRealmMessage: Object, Codable { @Persisted(primaryKey: true) var id: String @Persisted var from: String @Persisted var to: String @Persisted(indexed: true) var chatName: String @Persisted(indexed: true) var timestamp: Date @Persisted var data: String @Persisted(indexed: true) var searchText: String? @Persisted var isInSyncWithBlockchain: Bool @Persisted var isUnsent: Bool @Persisted(indexed: true) var deleted: Bool override required init() { } // For creating outgoing msgs, because they can't be decrypted init(id: String, from: String, to: String, chatName: String, timestamp: Date, data: String) { super.init() self.id = (try? Data(eosioPublicKey: id).toEosioK1PublicKey) ?? "" self.from = from self.to = to self.chatName = chatName.lowercased() self.timestamp = timestamp // Stored local so can differ from server update when next time load msgs self.data = data self.isInSyncWithBlockchain = false self.isUnsent = false self.searchText = self.plainText?.lowercased() } // For creating incoming msgs, will be decrypted under hood init(msg: CryptoChat.Model.Msg, username: String, privateKey: String, timestamp: Date) { super.init() self.id = (try? Data(eosioPublicKey: msg.ephemPublicKey).toEosioK1PublicKey) ?? "" self.from = msg.from self.to = msg.to self.chatName = msg.to.lowercased() == username.lowercased() ? msg.from.lowercased() : msg.to.lowercased() self.timestamp = timestamp self.data = (try? msg.decrypt(privateKey: privateKey)) ?? "*** Decrypt error ***</plaintext>" self.isInSyncWithBlockchain = true self.searchText = self.plainText?.lowercased() } } // Data decoding into types extension CryptoChatModelRealmMessage { var plainText: String? { data.starts(with: "<plaintext>") ? String(data.dropFirst("<plaintext>".count).dropLast("</plaintext>".count)) : nil } var image: UIImage? { data.starts(with: "<image>") ? UIImage(data: Data(base64Encoded: String(data.dropFirst("<image>".count).dropLast("</image>".count))) ?? Data()) : nil } var qr: UIImage? { data.starts(with: "<qr>") ? String(data.dropFirst("<qr>".count).dropLast("</qr>".count)).generateQRCode(tintColor: .black) : nil } var qrText: String? { data.starts(with: "<qr>") ? String(data.dropFirst("<qr>".count).dropLast("</qr>".count)) : nil } var textDescription: String { plainText ?? qrText ?? data } } extension CryptoChatModelRealmMessage { var time: String { let dateFormat = DateFormatter() dateFormat.dateStyle = .none dateFormat.timeStyle = .short return dateFormat.string(from: timestamp) } var day: String { let dateFormat = DateFormatter() dateFormat.dateStyle = .long dateFormat.timeStyle = .none return dateFormat.string(from: timestamp) } }