session-ios/SessionMessagingKit/Database/Storage+Contacts.swift

58 lines
2.6 KiB
Swift
Raw Normal View History

2020-12-17 06:32:39 +01:00
extension Storage {
private static let contactCollection = "LokiContactCollection"
@objc(getContactWithSessionID:)
2020-12-17 06:32:39 +01:00
public func getContact(with sessionID: String) -> Contact? {
var result: Contact?
Storage.read { transaction in
result = transaction.object(forKey: sessionID, inCollection: Storage.contactCollection) as? Contact
}
if let result = result, result.sessionID == getUserHexEncodedPublicKey() {
result.isTrusted = true // Always trust ourselves
}
2020-12-17 06:32:39 +01:00
return result
}
@objc(setContact:usingTransaction:)
2020-12-17 06:32:39 +01:00
public func setContact(_ contact: Contact, using transaction: Any) {
let oldContact = getContact(with: contact.sessionID)
2021-03-04 01:11:58 +01:00
let transaction = transaction as! YapDatabaseReadWriteTransaction
if contact.sessionID == getUserHexEncodedPublicKey() {
contact.isTrusted = true // Always trust ourselves
}
2021-03-04 01:11:58 +01:00
transaction.setObject(contact, forKey: contact.sessionID, inCollection: Storage.contactCollection)
transaction.addCompletionQueue(DispatchQueue.main) {
// Delete old profile picture if needed
2021-07-22 07:23:35 +02:00
if let oldProfilePictureFileName = oldContact?.profilePictureFileName,
oldProfilePictureFileName != contact.profilePictureFileName {
let path = OWSUserProfile.profileAvatarFilepath(withFilename: oldProfilePictureFileName)
DispatchQueue.global(qos: .default).async {
OWSFileSystem.deleteFileIfExists(path)
}
}
// Post notification
2021-03-04 01:11:58 +01:00
let notificationCenter = NotificationCenter.default
notificationCenter.post(name: .contactUpdated, object: contact.sessionID)
if contact.sessionID == getUserHexEncodedPublicKey() {
notificationCenter.post(name: Notification.Name(kNSNotificationName_LocalProfileDidChange), object: nil)
} else {
2021-03-04 03:50:13 +01:00
let userInfo = [ kNSNotificationKey_ProfileRecipientId : contact.sessionID ]
notificationCenter.post(name: Notification.Name(kNSNotificationName_OtherUsersProfileDidChange), object: nil, userInfo: userInfo)
2021-03-04 01:11:58 +01:00
}
2021-03-01 03:15:54 +01:00
}
2020-12-17 06:32:39 +01:00
}
2020-12-17 23:47:18 +01:00
@objc public func getAllContacts() -> Set<Contact> {
2020-12-17 23:47:18 +01:00
var result: Set<Contact> = []
Storage.read { transaction in
transaction.enumerateRows(inCollection: Storage.contactCollection) { _, object, _, _ in
guard let contact = object as? Contact else { return }
result.insert(contact)
}
}
return result
}
2020-12-17 06:32:39 +01:00
}