summaryrefslogtreecommitdiff
path: root/Libraries/LibProtocol/Client.cpp
blob: fc2eedb0d476c4081c80c3891c3f94249b673b83 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#include <AK/SharedBuffer.h>
#include <LibProtocol/Client.h>
#include <LibProtocol/Download.h>

namespace LibProtocol {

Client::Client()
    : IServerConnection(*this, "/tmp/portal/protocol")
{
    handshake();
}

void Client::handshake()
{
    auto response = send_sync<ProtocolServer::Greet>();
    set_my_client_id(response->client_id());
}

bool Client::is_supported_protocol(const String& protocol)
{
    return send_sync<ProtocolServer::IsSupportedProtocol>(protocol)->supported();
}

RefPtr<Download> Client::start_download(const String& url)
{
    i32 download_id = send_sync<ProtocolServer::StartDownload>(url)->download_id();
    auto download = Download::create_from_id({}, *this, download_id);
    m_downloads.set(download_id, download);
    return download;
}

bool Client::stop_download(Badge<Download>, Download& download)
{
    if (!m_downloads.contains(download.id()))
        return false;
    return send_sync<ProtocolServer::StopDownload>(download.id())->success();
}

void Client::handle(const ProtocolClient::DownloadFinished& message)
{
    RefPtr<Download> download;
    if ((download = m_downloads.get(message.download_id()).value_or(nullptr))) {
        download->did_finish({}, message.success(), message.total_size(), message.shared_buffer_id());
    }
    send_sync<ProtocolServer::DisownSharedBuffer>(message.shared_buffer_id());
    m_downloads.remove(message.download_id());
}

void Client::handle(const ProtocolClient::DownloadProgress& message)
{
    if (auto download = m_downloads.get(message.download_id()).value_or(nullptr)) {
        download->did_progress({}, message.total_size(), message.downloaded_size());
    }
}

}