WebSocket.h 2.1 KB

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