Serenity Operating System
1/*
2 * Copyright (c) 2021, Dex♪ <dexes.ttp@gmail.com>
3 *
4 * SPDX-License-Identifier: BSD-2-Clause
5 */
6
7#include <LibProtocol/WebSocket.h>
8#include <LibProtocol/WebSocketClient.h>
9
10namespace Protocol {
11
12WebSocket::WebSocket(WebSocketClient& client, i32 connection_id)
13 : m_client(client)
14 , m_connection_id(connection_id)
15{
16}
17
18WebSocket::ReadyState WebSocket::ready_state()
19{
20 return (WebSocket::ReadyState)m_client->ready_state({}, *this);
21}
22
23DeprecatedString WebSocket::subprotocol_in_use()
24{
25 return m_client->subprotocol_in_use({}, *this);
26}
27
28void WebSocket::send(ByteBuffer binary_or_text_message, bool is_text)
29{
30 m_client->send({}, *this, move(binary_or_text_message), is_text);
31}
32
33void WebSocket::send(StringView text_message)
34{
35 send(ByteBuffer::copy(text_message.bytes()).release_value_but_fixme_should_propagate_errors(), true);
36}
37
38void WebSocket::close(u16 code, DeprecatedString reason)
39{
40 m_client->close({}, *this, code, move(reason));
41}
42
43void WebSocket::did_open(Badge<WebSocketClient>)
44{
45 if (on_open)
46 on_open();
47}
48
49void WebSocket::did_receive(Badge<WebSocketClient>, ByteBuffer data, bool is_text)
50{
51 if (on_message)
52 on_message(WebSocket::Message { move(data), is_text });
53}
54
55void WebSocket::did_error(Badge<WebSocketClient>, i32 error_code)
56{
57 if (on_error)
58 on_error((WebSocket::Error)error_code);
59}
60
61void WebSocket::did_close(Badge<WebSocketClient>, u16 code, DeprecatedString reason, bool was_clean)
62{
63 if (on_close)
64 on_close(code, move(reason), was_clean);
65}
66
67void WebSocket::did_request_certificates(Badge<WebSocketClient>)
68{
69 if (on_certificate_requested) {
70 auto result = on_certificate_requested();
71 if (!m_client->set_certificate({}, *this, result.certificate, result.key))
72 dbgln("WebSocket: set_certificate failed");
73 }
74}
75}