Serenity Operating System
1/*
2 * Copyright (c) 2021, Dex♪ <dexes.ttp@gmail.com>
3 *
4 * SPDX-License-Identifier: BSD-2-Clause
5 */
6
7#pragma once
8
9#include <AK/Badge.h>
10#include <AK/ByteBuffer.h>
11#include <AK/DeprecatedString.h>
12#include <AK/Function.h>
13#include <AK/RefCounted.h>
14#include <AK/WeakPtr.h>
15#include <LibCore/Notifier.h>
16#include <LibIPC/Forward.h>
17
18namespace Protocol {
19
20class WebSocketClient;
21
22class WebSocket : public RefCounted<WebSocket> {
23public:
24 struct CertificateAndKey {
25 DeprecatedString certificate;
26 DeprecatedString key;
27 };
28
29 struct Message {
30 ByteBuffer data;
31 bool is_text { false };
32 };
33
34 enum class Error {
35 CouldNotEstablishConnection,
36 ConnectionUpgradeFailed,
37 ServerClosedSocket,
38 };
39
40 enum class ReadyState {
41 Connecting = 0,
42 Open = 1,
43 Closing = 2,
44 Closed = 3,
45 };
46
47 static NonnullRefPtr<WebSocket> create_from_id(Badge<WebSocketClient>, WebSocketClient& client, i32 connection_id)
48 {
49 return adopt_ref(*new WebSocket(client, connection_id));
50 }
51
52 int id() const { return m_connection_id; }
53
54 ReadyState ready_state();
55
56 DeprecatedString subprotocol_in_use();
57
58 void send(ByteBuffer binary_or_text_message, bool is_text);
59 void send(StringView text_message);
60 void close(u16 code = 1005, DeprecatedString reason = {});
61
62 Function<void()> on_open;
63 Function<void(Message)> on_message;
64 Function<void(Error)> on_error;
65 Function<void(u16 code, DeprecatedString reason, bool was_clean)> on_close;
66 Function<CertificateAndKey()> on_certificate_requested;
67
68 void did_open(Badge<WebSocketClient>);
69 void did_receive(Badge<WebSocketClient>, ByteBuffer, bool);
70 void did_error(Badge<WebSocketClient>, i32);
71 void did_close(Badge<WebSocketClient>, u16, DeprecatedString, bool);
72 void did_request_certificates(Badge<WebSocketClient>);
73
74private:
75 explicit WebSocket(WebSocketClient&, i32 connection_id);
76 WeakPtr<WebSocketClient> m_client;
77 int m_connection_id { -1 };
78};
79
80}