Repository: Automattic/pocket-casts-ios
File: podcasts/MediaExporterResourceLoaderDelegate.swift (Swift)

Code before:
                return dataRequest.currentOffset >= requestedLength + requestedOffset
            }
            return false
        }

        // Data length to be loaded into memory with maximum size of readDataLimit.
        let bytesToRespond = min(bytesCached - currentOffset, requestedLength, readDataLimit)

        // Read data from disk and pass it to the dataRequest
        guard let data = fileHandle.readData(withOffset: currentOffset, forLength: bytesToRespond) else { return false }
        dataRequest.respond(with: data)

        return dataRequest.currentOffset >= requestedLength + requestedOffset
    }

    private func writeBufferDataToFileIfNeeded() {
        lock.lock()
        defer { lock.unlock() }

        guard bufferData.count >= downloadBufferLimit else { return }

        do {
            try fileHandle.append(data: bufferData)
            bufferData = Data()
        } catch {
            FileLog.shared.addMessage("MediaExporterResourceLoaderDelegate: failed to write date to file:\(error)")
            invalidateAndCancelSession()
        }
    }

    private func downloadComplete() {
        processPendingRequests()

        isDownloadComplete = true
        let contentType = self.response?.mimeType
        DispatchQueue.main.async {
            self.callback?(.completed, contentType, Int64(self.fileHandle.fileSize), Int64(self.fileHandle.fileSize))
        }
    }

    private func verifyResponse() -> NSError? {
        guard let response = response as? HTTPURLResponse else { return nil }

        let shouldVerifyDownloadedFileSize = MediaExporterItemConfiguration.shouldVerifyDownloadedFileSize
        let minimumExpectedFileSize = MediaExporterItemConfiguration.minimumExpectedFileSize
        var error: NSError?

        if response.statusCode >= 400 {
            error = NSError(domain: "Failed downloading asset. Reason: response status code \(response.statusCode).", code: response.statusCode, userInfo: nil)
        } else if shouldVerifyDownloadedFileSize && response.expectedContentLength != -1 && response.expectedContentLength != fileHandle.fileSize {
            error = NSError(domain: "Failed downloading asset. Reason: wrong file size, expected: \(response.expectedContentLength), actual: \(fileHandle.fileSize).", code: response.statusCode, userInfo: nil)

Review comment (bug):
Small typo:

```suggestion
            FileLog.shared.addMessage("MediaExporterResourceLoaderDelegate: failed to write data to file:\(error)")
```

Code after:
        let requestedLength = dataRequest.requestedLength
        let currentOffset = Int(dataRequest.currentOffset)
        let bytesCached = fileHandle.fileSize

        // Is there enough data cached to fulfill the request?
        guard bytesCached > currentOffset else {
            if FeatureFlag.streamAndDownloadReadFromMemoryBuffer.enabled, currentOffset < bufferData.count + bytesCached {
                let start = currentOffset - bytesCached
                let end = min(currentOffset + requestedLength - bytesCached, bufferData.count)
                if start >= end {
                    FileLog.shared.addMessage("MediaExporterResourceLoaderDelegate: try to read from memory with wrong indeces: \(start):\(end)")
                    return false
                }
                let dataRequested = bufferData.subdata(in: start..<end)
                dataRequest.respond(with: dataRequested)
                return dataRequest.currentOffset >= requestedLength + requestedOffset
            }
            return false
        }

        // Data length to be loaded into memory with maximum size of readDataLimit.
        let bytesToRespond = min(bytesCached - currentOffset, requestedLength, readDataLimit)

        // Read data from disk and pass it to the dataRequest
        guard let data = fileHandle.readData(withOffset: currentOffset, forLength: bytesToRespond) else { return false }
        dataRequest.respond(with: data)

        return dataRequest.currentOffset >= requestedLength + requestedOffset
    }

    private func writeBufferDataToFileIfNeeded() {
        lock.lock()
        defer { lock.unlock() }

        guard bufferData.count >= downloadBufferLimit else { return }

        do {
            try fileHandle.append(data: bufferData)
            bufferData = Data()
        } catch {
            FileLog.shared.addMessage("MediaExporterResourceLoaderDelegate: failed to write data to file: \(error)")
            invalidateAndCancelSession()
        }
    }

    private func downloadComplete() {
        processPendingRequests()

        isDownloadComplete = true
        let contentType = self.response?.mimeType
        callbackQueue.async {