Casablanca – showing progress for an HTTP download

The current release of Casablanca does not support progress reporting when reading from an HTTP stream, you only know when it’s completed – but, you can read chunk by chunk and get a percentage based on the total size that you can get off the header. Here’s a code snippet that shows one way of doing this with PPL tasks. It recursively calls the Repeat function until there’s nothing left to read, and the then() code in the original call is executed. So you still get a completed event while also being able to report progress. The code snippet does not do anything with the data, it just shows a percentage.

concurrency::task<void> Repeat(
  istream bodyStream, size_t chunkSize, 
  size_t lenRead, size_t contentLength)
{
	container_buffer<std::string> buffer;

	return concurrency::create_task(
    [=] { return bodyStream.read(buffer, chunkSize).get(); })
		.then([=](int bytesRead)
	{
		if(bytesRead > 0)
		{
			std::wcout << (lenRead + bytesRead) * 100 / contentLength 
                 << L"% downloaded"  << std::endl;
			return Repeat(bodyStream, chunkSize, lenRead + bytesRead, contentLength);
		}

		return concurrency::create_task([]{});
	});
}

// . . .

http_client client(L"http://www.codeproject.com");

client.request(methods::GET).then([](http_response response)
{
  if(response.status_code() == status_codes::OK)
  {
    auto bodyStream = response.body();		

    size_t contentLength = response.headers().content_length();
    std::wcout << L"Content length: " << contentLength << std::endl;            

    Repeat(bodyStream, 8192, 0, contentLength).then([]
    {
      std::wcout << L"Completed." << std::endl;            
    });
  }
});

Here’s some sample output:

Content length: 79025
3% downloaded
13% downloaded
17% downloaded
27% downloaded
31% downloaded
41% downloaded
42% downloaded
52% downloaded
58% downloaded
68% downloaded
68% downloaded
79% downloaded
79% downloaded
89% downloaded
91% downloaded
100% downloaded
Completed.

I am not a PPL expert so if you notice anything quirky about this, feel free to comment on it. Thanks.

Advertisements

One thought on “Casablanca – showing progress for an HTTP download

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s