summaryrefslogtreecommitdiff
path: root/Userland/Libraries/LibCore/NetworkJob.h
blob: 781dc825a8ad8dd04c52b92fb1f4b2ff466c7808 (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
57
58
59
60
61
62
63
64
65
66
67
/*
 * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
 *
 * SPDX-License-Identifier: BSD-2-Clause
 */

#pragma once

#include <AK/Function.h>
#include <AK/Stream.h>
#include <LibCore/Object.h>

namespace Core {

class NetworkJob : public Object {
    C_OBJECT_ABSTRACT(NetworkJob)
public:
    enum class Error {
        None,
        ConnectionFailed,
        TransmissionFailed,
        ProtocolFailed,
        Cancelled,
    };
    virtual ~NetworkJob() override;

    // Could fire twice, after Headers and after Trailers!
    Function<void(const HashMap<String, String, CaseInsensitiveStringTraits>& response_headers, Optional<u32> response_code)> on_headers_received;
    Function<void(bool success)> on_finish;
    Function<void(Optional<u32>, u32)> on_progress;

    bool is_cancelled() const { return m_error == Error::Cancelled; }
    bool has_error() const { return m_error != Error::None; }
    Error error() const { return m_error; }
    NetworkResponse* response() { return m_response.ptr(); }
    const NetworkResponse* response() const { return m_response.ptr(); }

    virtual void start(NonnullRefPtr<Core::Socket>) = 0;
    virtual void shutdown() = 0;

    void cancel()
    {
        shutdown();
        m_error = Error::Cancelled;
    }

protected:
    NetworkJob(OutputStream&);
    void did_finish(NonnullRefPtr<NetworkResponse>&&);
    void did_fail(Error);
    void did_progress(Optional<u32> total_size, u32 downloaded);

    size_t do_write(ReadonlyBytes bytes) { return m_output_stream.write(bytes); }

private:
    RefPtr<NetworkResponse> m_response;
    OutputStream& m_output_stream;
    Error m_error { Error::None };
};

const char* to_string(NetworkJob::Error);

}

template<>
struct AK::Formatter<Core::NetworkJob> : Formatter<Core::Object> {
};