| 362 | } |
| 363 | |
| 364 | void RemoteDownloader::enqueue(const StringBox& localFilename, |
| 365 | const StringBox& url, |
| 366 | const IRemoteDownloaderItemHandler& itemHandler, |
| 367 | const BytesView& expectedHash, |
| 368 | RemoteDownloaderLoadCompletion completion) { |
| 369 | std::unique_lock<Mutex> guard(_mutex); |
| 370 | |
| 371 | const auto& inMemoryIt = _downloadedItemByUrl.find(url); |
| 372 | if (inMemoryIt != _downloadedItemByUrl.end()) { |
| 373 | inMemoryIt->second.markAccessed(); |
| 374 | |
| 375 | auto value = inMemoryIt->second.getValue(); |
| 376 | guard.unlock(); |
| 377 | |
| 378 | completion(std::move(value), RemoteDownloaderLoadSourceInMemory); |
| 379 | return; |
| 380 | } |
| 381 | |
| 382 | auto shouldStartRequest = false; |
| 383 | |
| 384 | Shared<RemoteDownloaderTask> task; |
| 385 | |
| 386 | const auto& it = _taskByUrl.find(url); |
| 387 | if (it == _taskByUrl.end()) { |
| 388 | task = Valdi::makeShared<RemoteDownloaderTask>(localFilename, url, expectedHash, itemHandler); |
| 389 | _taskByUrl[url] = task; |
| 390 | |
| 391 | shouldStartRequest = true; |
| 392 | } else { |
| 393 | task = it->second; |
| 394 | } |
| 395 | |
| 396 | task->appendRequest(RemoteDownloaderRequest(std::move(completion))); |
| 397 | |
| 398 | if (shouldStartRequest) { |
| 399 | guard.unlock(); |
| 400 | |
| 401 | auto weakThis = weak_from_this(); |
| 402 | _workQueue->async([=]() { |
| 403 | auto strongThis = weakThis.lock(); |
| 404 | if (strongThis != nullptr) { |
| 405 | strongThis->doLoad(task); |
| 406 | } |
| 407 | }); |
| 408 | } |
| 409 | } |
| 410 | |
| 411 | Result<Value> RemoteDownloader::transformLoadResult(const Shared<RemoteDownloaderTask>& task, const BytesView& result) { |
| 412 | auto transformResult = task->getItemHandler().transform(task->getLocalFilename(), result); |
no test coverage detected