WebSocket.cpp 2.0 KB

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