1
Fork 0
mirror of https://github.com/RGBCube/serenity synced 2025-07-26 05:07:35 +00:00

LibProtocol: Add a Download object so users don't have to manage ID's

LibProtocol::Client::start_download() now gives you a Download object
with convenient hooks (on_finish & on_progress).

Also, the IPC handshake is snuck into the Client constructor, so you
don't need to perform it after instantiating a Client.

This makes using LibProtocol much more pleasant. :^)
This commit is contained in:
Andreas Kling 2019-11-24 13:20:44 +01:00
parent 3dc87be891
commit 653e61d9cf
6 changed files with 112 additions and 28 deletions

View file

@ -2,6 +2,7 @@
#include <LibC/SharedBuffer.h>
#include <LibCore/CEventLoop.h>
#include <LibProtocol/Client.h>
#include <LibProtocol/Download.h>
#include <stdio.h>
int main(int argc, char** argv)
@ -20,25 +21,19 @@ int main(int argc, char** argv)
CEventLoop loop;
auto protocol_client = LibProtocol::Client::construct();
protocol_client->handshake();
protocol_client->on_download_finish = [&](i32 download_id, bool success, u32 total_size, i32 shared_buffer_id) {
dbgprintf("download %d finished, success=%u, shared_buffer_id=%d\n", download_id, success, shared_buffer_id);
if (success) {
ASSERT(shared_buffer_id != -1);
auto shared_buffer = SharedBuffer::create_from_shared_buffer_id(shared_buffer_id);
auto payload_bytes = ByteBuffer::wrap(shared_buffer->data(), total_size);
write(STDOUT_FILENO, payload_bytes.data(), payload_bytes.size());
}
auto download = protocol_client->start_download(url.to_string());
download->on_progress = [](u32 total_size, u32 downloaded_size) {
dbgprintf("download progress: %u / %u\n", downloaded_size, total_size);
};
download->on_finish = [&](bool success, auto& payload, auto) {
if (success)
write(STDOUT_FILENO, payload.data(), payload.size());
else
fprintf(stderr, "Download failed :(\n");
loop.quit(0);
};
protocol_client->on_download_progress = [&](i32 download_id, u32 total_size, u32 downloaded_size) {
dbgprintf("download %d progress: %u / %u\n", download_id, downloaded_size, total_size);
};
i32 download_id = protocol_client->start_download(url.to_string());
dbgprintf("started download with id %d\n", download_id);
dbgprintf("started download with id %d\n", download->id());
return loop.exec();
}