|
| 1 | +//===----------------------------------------------------------------------===// |
| 2 | +// |
| 3 | +// This source file is part of the AsyncHTTPClient open source project |
| 4 | +// |
| 5 | +// Copyright (c) 2020 Apple Inc. and the AsyncHTTPClient project authors |
| 6 | +// Licensed under Apache License v2.0 |
| 7 | +// |
| 8 | +// See LICENSE.txt for license information |
| 9 | +// See CONTRIBUTORS.txt for the list of AsyncHTTPClient project authors |
| 10 | +// |
| 11 | +// SPDX-License-Identifier: Apache-2.0 |
| 12 | +// |
| 13 | +//===----------------------------------------------------------------------===// |
| 14 | + |
| 15 | +import NIO |
| 16 | +import NIOHTTP1 |
| 17 | + |
| 18 | +/// Handles a streaming download to a given file path, allowing headers and progress to be reported. |
| 19 | +public final class FileDownloadDelegate: HTTPClientResponseDelegate { |
| 20 | + /// The response type for this delegate: the total count of bytes as reported by the response |
| 21 | + /// "Content-Length" header (if available) and the count of bytes downloaded. |
| 22 | + public struct Progress { |
| 23 | + public var totalBytes: Int? |
| 24 | + public var receivedBytes: Int |
| 25 | + } |
| 26 | + |
| 27 | + private var progress = Progress(totalBytes: nil, receivedBytes: 0) |
| 28 | + |
| 29 | + public typealias Response = Progress |
| 30 | + |
| 31 | + private let filePath: String |
| 32 | + private let io: NonBlockingFileIO |
| 33 | + private let reportHead: ((HTTPResponseHead) -> Void)? |
| 34 | + private let reportProgress: ((Progress) -> Void)? |
| 35 | + |
| 36 | + private var fileHandleFuture: EventLoopFuture<NIOFileHandle>? |
| 37 | + private var writeFuture: EventLoopFuture<Void>? |
| 38 | + |
| 39 | + /// Initializes a new file download delegate. |
| 40 | + /// - parameters: |
| 41 | + /// - path: Path to a file you'd like to write the download to. |
| 42 | + /// - pool: A thread pool to use for asynchronous file I/O. |
| 43 | + /// - reportHead: A closure called when the response head is available. |
| 44 | + /// - reportProgress: A closure called when a body chunk has been downloaded, with |
| 45 | + /// the total byte count and download byte count passed to it as arguments. The callbacks |
| 46 | + /// will be invoked in the same threading context that the delegate itself is invoked, |
| 47 | + /// as controlled by `EventLoopPreference`. |
| 48 | + public init( |
| 49 | + path: String, |
| 50 | + pool: NIOThreadPool = NIOThreadPool(numberOfThreads: 1), |
| 51 | + reportHead: ((HTTPResponseHead) -> Void)? = nil, |
| 52 | + reportProgress: ((Progress) -> Void)? = nil |
| 53 | + ) throws { |
| 54 | + pool.start() |
| 55 | + self.io = NonBlockingFileIO(threadPool: pool) |
| 56 | + self.filePath = path |
| 57 | + |
| 58 | + self.reportHead = reportHead |
| 59 | + self.reportProgress = reportProgress |
| 60 | + } |
| 61 | + |
| 62 | + public func didReceiveHead( |
| 63 | + task: HTTPClient.Task<Response>, |
| 64 | + _ head: HTTPResponseHead |
| 65 | + ) -> EventLoopFuture<Void> { |
| 66 | + self.reportHead?(head) |
| 67 | + |
| 68 | + if let totalBytesString = head.headers.first(name: "Content-Length"), |
| 69 | + let totalBytes = Int(totalBytesString) { |
| 70 | + self.progress.totalBytes = totalBytes |
| 71 | + } |
| 72 | + |
| 73 | + return task.eventLoop.makeSucceededFuture(()) |
| 74 | + } |
| 75 | + |
| 76 | + public func didReceiveBodyPart( |
| 77 | + task: HTTPClient.Task<Response>, |
| 78 | + _ buffer: ByteBuffer |
| 79 | + ) -> EventLoopFuture<Void> { |
| 80 | + self.progress.receivedBytes += buffer.readableBytes |
| 81 | + self.reportProgress?(self.progress) |
| 82 | + |
| 83 | + let writeFuture: EventLoopFuture<Void> |
| 84 | + if let fileHandleFuture = self.fileHandleFuture { |
| 85 | + writeFuture = fileHandleFuture.flatMap { |
| 86 | + self.io.write(fileHandle: $0, buffer: buffer, eventLoop: task.eventLoop) |
| 87 | + } |
| 88 | + } else { |
| 89 | + let fileHandleFuture = self.io.openFile( |
| 90 | + path: self.filePath, |
| 91 | + mode: .write, |
| 92 | + flags: .allowFileCreation(), |
| 93 | + eventLoop: task.eventLoop |
| 94 | + ) |
| 95 | + self.fileHandleFuture = fileHandleFuture |
| 96 | + writeFuture = fileHandleFuture.flatMap { |
| 97 | + self.io.write(fileHandle: $0, buffer: buffer, eventLoop: task.eventLoop) |
| 98 | + } |
| 99 | + } |
| 100 | + |
| 101 | + self.writeFuture = writeFuture |
| 102 | + return writeFuture |
| 103 | + } |
| 104 | + |
| 105 | + private func close(fileHandle: NIOFileHandle) { |
| 106 | + try! fileHandle.close() |
| 107 | + self.fileHandleFuture = nil |
| 108 | + } |
| 109 | + |
| 110 | + private func finalize() { |
| 111 | + if let writeFuture = self.writeFuture { |
| 112 | + writeFuture.whenComplete { _ in |
| 113 | + self.fileHandleFuture?.whenSuccess(self.close(fileHandle:)) |
| 114 | + self.writeFuture = nil |
| 115 | + } |
| 116 | + } else { |
| 117 | + self.fileHandleFuture?.whenSuccess(self.close(fileHandle:)) |
| 118 | + } |
| 119 | + } |
| 120 | + |
| 121 | + public func didReceiveError(task: HTTPClient.Task<Progress>, _ error: Error) { |
| 122 | + self.finalize() |
| 123 | + } |
| 124 | + |
| 125 | + public func didFinishRequest(task: HTTPClient.Task<Response>) throws -> Response { |
| 126 | + self.finalize() |
| 127 | + return self.progress |
| 128 | + } |
| 129 | +} |
0 commit comments