session-ios/SessionMessagingKit/Jobs/AttachmentDownloadJob.swift

165 lines
7.5 KiB
Swift
Raw Normal View History

2020-11-20 04:04:56 +01:00
import Foundation
2020-11-09 00:58:47 +01:00
import SessionUtilitiesKit
import SessionSnodeKit
2020-11-20 04:04:56 +01:00
import SignalCoreKit
2020-11-17 06:23:13 +01:00
public final class AttachmentDownloadJob : NSObject, Job, NSCoding { // NSObject/NSCoding conformance is needed for YapDatabase compatibility
2020-11-24 10:09:23 +01:00
public let attachmentID: String
2021-01-14 04:57:32 +01:00
public let tsMessageID: String
public let threadID: String
2020-11-08 03:12:38 +01:00
public var delegate: JobDelegate?
2020-11-17 06:23:13 +01:00
public var id: String?
2020-11-08 03:12:38 +01:00
public var failureCount: UInt = 0
public var isDeferred = false
2020-11-20 04:04:56 +01:00
public enum Error : LocalizedError {
case noAttachment
case invalidURL
2020-11-20 04:04:56 +01:00
public var errorDescription: String? {
switch self {
case .noAttachment: return "No such attachment."
case .invalidURL: return "Invalid file URL."
2020-11-20 04:04:56 +01:00
}
}
}
// MARK: Settings
public class var collection: String { return "AttachmentDownloadJobCollection" }
public static let maxFailureCount: UInt = 20
2020-11-20 04:04:56 +01:00
// MARK: Initialization
public init(attachmentID: String, tsMessageID: String, threadID: String) {
2020-11-20 04:04:56 +01:00
self.attachmentID = attachmentID
2021-01-14 04:57:32 +01:00
self.tsMessageID = tsMessageID
self.threadID = threadID
2020-11-20 04:04:56 +01:00
}
// MARK: Coding
2020-11-20 04:04:56 +01:00
public init?(coder: NSCoder) {
2020-11-23 00:24:40 +01:00
guard let attachmentID = coder.decodeObject(forKey: "attachmentID") as! String?,
2021-01-14 04:57:32 +01:00
let tsMessageID = coder.decodeObject(forKey: "tsIncomingMessageID") as! String?,
let threadID = coder.decodeObject(forKey: "threadID") as! String?,
2021-04-08 01:51:52 +02:00
let id = coder.decodeObject(forKey: "id") as! String? else { return nil }
2020-11-20 04:04:56 +01:00
self.attachmentID = attachmentID
2021-01-14 04:57:32 +01:00
self.tsMessageID = tsMessageID
self.threadID = threadID
2020-11-24 06:18:58 +01:00
self.id = id
self.failureCount = coder.decodeObject(forKey: "failureCount") as! UInt? ?? 0
2021-04-08 01:51:52 +02:00
self.isDeferred = coder.decodeBool(forKey: "isDeferred")
2020-11-20 04:04:56 +01:00
}
2020-11-20 04:04:56 +01:00
public func encode(with coder: NSCoder) {
coder.encode(attachmentID, forKey: "attachmentID")
2021-01-14 04:57:32 +01:00
coder.encode(tsMessageID, forKey: "tsIncomingMessageID")
coder.encode(threadID, forKey: "threadID")
2020-11-24 06:18:58 +01:00
coder.encode(id, forKey: "id")
coder.encode(failureCount, forKey: "failureCount")
coder.encode(isDeferred, forKey: "isDeferred")
2020-11-20 04:04:56 +01:00
}
// MARK: Running
2020-11-20 04:04:56 +01:00
public func execute() {
2021-06-04 00:16:54 +02:00
if let id = id {
JobQueue.currentlyExecutingJobs.insert(id)
}
guard !isDeferred else { return }
2021-02-26 03:42:06 +01:00
if TSAttachment.fetch(uniqueId: attachmentID) is TSAttachmentStream {
// FIXME: It's not clear * how * this happens, but apparently we can get to this point
// from time to time with an already downloaded attachment.
return handleSuccess()
2021-02-26 03:42:06 +01:00
}
guard let pointer = TSAttachment.fetch(uniqueId: attachmentID) as? TSAttachmentPointer else {
return handleFailure(error: Error.noAttachment)
2020-11-20 04:04:56 +01:00
}
2020-12-02 06:25:16 +01:00
let storage = SNMessagingKitConfiguration.shared.storage
2020-12-07 06:00:21 +01:00
storage.write(with: { transaction in
2021-01-14 04:57:32 +01:00
storage.setAttachmentState(to: .downloading, for: pointer, associatedWith: self.tsMessageID, using: transaction)
2020-11-23 00:24:40 +01:00
}, completion: { })
2020-11-20 04:04:56 +01:00
let temporaryFilePath = URL(fileURLWithPath: OWSTemporaryDirectoryAccessibleAfterFirstAuth() + UUID().uuidString)
2020-11-23 00:24:40 +01:00
let handleFailure: (Swift.Error) -> Void = { error in // Intentionally capture self
OWSFileSystem.deleteFile(temporaryFilePath.absoluteString)
2020-11-23 05:46:53 +01:00
if let error = error as? Error, case .noAttachment = error {
2020-12-07 06:00:21 +01:00
storage.write(with: { transaction in
2021-01-14 04:57:32 +01:00
storage.setAttachmentState(to: .failed, for: pointer, associatedWith: self.tsMessageID, using: transaction)
2020-11-23 05:46:53 +01:00
}, completion: { })
self.handlePermanentFailure(error: error)
} else if let error = error as? OnionRequestAPI.Error, case .httpRequestFailedAtDestination(let statusCode, _, _) = error,
statusCode == 400 {
// Otherwise, the attachment will show a state of downloading forever,
// and the message won't be able to be marked as read.
storage.write(with: { transaction in
storage.setAttachmentState(to: .failed, for: pointer, associatedWith: self.tsMessageID, using: transaction)
}, completion: { })
// This usually indicates a file that has expired on the server, so there's no need to retry.
self.handlePermanentFailure(error: error)
2020-11-23 05:46:53 +01:00
} else {
self.handleFailure(error: error)
}
2020-11-23 00:24:40 +01:00
}
2021-03-26 05:59:22 +01:00
if let tsMessage = TSMessage.fetch(uniqueId: tsMessageID), let v2OpenGroup = storage.getV2OpenGroup(for: tsMessage.uniqueThreadId) {
guard let fileAsString = pointer.downloadURL.split(separator: "/").last, let file = UInt64(fileAsString) else {
return handleFailure(Error.invalidURL)
2020-11-20 04:04:56 +01:00
}
OpenGroupAPIV2.download(file, from: v2OpenGroup.room, on: v2OpenGroup.server).done(on: DispatchQueue.global(qos: .userInitiated)) { data in
self.handleDownloadedAttachment(data: data, temporaryFilePath: temporaryFilePath, pointer: pointer, failureHandler: handleFailure)
}.catch(on: DispatchQueue.global()) { error in
handleFailure(error)
2020-11-20 04:04:56 +01:00
}
2021-05-04 07:46:48 +02:00
} else {
guard let fileAsString = pointer.downloadURL.split(separator: "/").last, let file = UInt64(fileAsString) else {
return handleFailure(Error.invalidURL)
}
2021-05-20 02:53:56 +02:00
let useOldServer = pointer.downloadURL.contains(FileServerAPIV2.oldServer)
FileServerAPIV2.download(file, useOldServer: useOldServer).done(on: DispatchQueue.global(qos: .userInitiated)) { data in
self.handleDownloadedAttachment(data: data, temporaryFilePath: temporaryFilePath, pointer: pointer, failureHandler: handleFailure)
}.catch(on: DispatchQueue.global()) { error in
handleFailure(error)
}
2020-11-20 04:04:56 +01:00
}
}
private func handleDownloadedAttachment(data: Data, temporaryFilePath: URL, pointer: TSAttachmentPointer, failureHandler: (Swift.Error) -> Void) {
let storage = SNMessagingKitConfiguration.shared.storage
do {
try data.write(to: temporaryFilePath, options: .atomic)
} catch {
return failureHandler(error)
}
let plaintext: Data
2021-04-28 04:03:47 +02:00
if let key = pointer.encryptionKey, let digest = pointer.digest, key.count > 0 && digest.count > 0 {
do {
plaintext = try Cryptography.decryptAttachment(data, withKey: key, digest: digest, unpaddedSize: pointer.byteCount)
} catch {
return failureHandler(error)
}
} else {
plaintext = data // Open group attachments are unencrypted
}
let stream = TSAttachmentStream(pointer: pointer)
do {
try stream.write(plaintext)
} catch {
return failureHandler(error)
}
OWSFileSystem.deleteFile(temporaryFilePath.absoluteString)
storage.write(with: { transaction in
storage.persist(stream, associatedWith: self.tsMessageID, using: transaction)
}, completion: {
self.handleSuccess()
})
}
2020-11-08 03:12:38 +01:00
private func handleSuccess() {
delegate?.handleJobSucceeded(self)
}
2020-11-23 05:46:53 +01:00
private func handlePermanentFailure(error: Swift.Error) {
delegate?.handleJobFailedPermanently(self, with: error)
}
2020-11-20 04:04:56 +01:00
private func handleFailure(error: Swift.Error) {
2020-11-08 03:12:38 +01:00
delegate?.handleJobFailed(self, with: error)
}
}