session-ios/SessionMessagingKit/Sending & Receiving/MessageReceiver.swift

69 lines
2.9 KiB
Swift
Raw Normal View History

2020-11-09 00:58:47 +01:00
import SessionUtilitiesKit
2020-11-05 23:17:05 +01:00
internal enum MessageReceiver {
internal enum Error : LocalizedError {
2020-11-06 06:31:56 +01:00
case invalidMessage
case unknownMessage
case unknownEnvelopeType
case noUserPublicKey
case noData
// Shared sender keys
case invalidGroupPublicKey
case noGroupPrivateKey
case sharedSecretGenerationFailed
case selfSend
2020-11-06 06:31:56 +01:00
internal var errorDescription: String? {
2020-11-06 06:31:56 +01:00
switch self {
case .invalidMessage: return "Invalid message."
case .unknownMessage: return "Unknown message type."
case .unknownEnvelopeType: return "Unknown envelope type."
case .noUserPublicKey: return "Couldn't find user key pair."
case .noData: return "Received an empty envelope."
// Shared sender keys
case .invalidGroupPublicKey: return "Invalid group public key."
case .noGroupPrivateKey: return "Missing group private key."
case .sharedSecretGenerationFailed: return "Couldn't generate a shared secret."
case .selfSend: return "Message addressed at self."
2020-11-06 06:31:56 +01:00
}
}
}
internal static func parse(_ data: Data, using transaction: Any) throws -> Message {
// Parse the envelope
let envelope = try MessageWrapper.unwrap(data: data)
// Decrypt the contents
let plaintext: Data
switch envelope.type {
case .unidentifiedSender: (plaintext, _) = try decryptWithSignalProtocol(envelope: envelope, using: transaction)
case .closedGroupCiphertext: (plaintext, _) = try decryptWithSharedSenderKeys(envelope: envelope, using: transaction)
default: throw Error.unknownEnvelopeType
}
// Parse the proto
2020-11-06 04:05:45 +01:00
let proto: SNProtoContent
do {
proto = try SNProtoContent.parseData((plaintext as NSData).removePadding())
2020-11-06 04:05:45 +01:00
} catch {
SNLog("Couldn't parse proto due to error: \(error).")
throw error
2020-11-06 04:05:45 +01:00
}
// Parse the message
2020-11-06 06:31:56 +01:00
let message: Message? = {
if let readReceipt = ReadReceipt.fromProto(proto) { return readReceipt }
if let sessionRequest = SessionRequest.fromProto(proto) { return sessionRequest }
if let typingIndicator = TypingIndicator.fromProto(proto) { return typingIndicator }
if let closedGroupUpdate = ClosedGroupUpdate.fromProto(proto) { return closedGroupUpdate }
if let expirationTimerUpdate = ExpirationTimerUpdate.fromProto(proto) { return expirationTimerUpdate }
if let visibleMessage = VisibleMessage.fromProto(proto) { return visibleMessage }
return nil
}()
if let message = message {
guard message.isValid else { throw Error.invalidMessage }
2020-11-06 06:31:56 +01:00
return message
} else {
2020-11-07 23:03:08 +01:00
throw Error.unknownMessage
2020-11-06 06:31:56 +01:00
}
2020-11-06 04:05:45 +01:00
}
2020-11-05 23:17:05 +01:00
}