mirror of
https://github.com/LadybirdBrowser/ladybird.git
synced 2024-11-22 15:40:19 +00:00
LibWeb: Add WebSocket bindings
The WebSocket bindings match the original specification from the WHATWG living standard, but do not match the later update of the standard that involves FETCH. The FETCH update will be handled later since the changes would also affect XMLHttpRequest.
This commit is contained in:
parent
68bfb46a6f
commit
22413ef729
Notes:
sideshowbarker
2024-07-18 19:05:45 +09:00
Author: https://github.com/Dexesttp Commit: https://github.com/SerenityOS/serenity/commit/22413ef729f Pull-request: https://github.com/SerenityOS/serenity/pull/6610 Reviewed-by: https://github.com/awesomekling Reviewed-by: https://github.com/linusg
16 changed files with 593 additions and 1 deletions
42
Base/res/html/misc/websocket.html
Normal file
42
Base/res/html/misc/websocket.html
Normal file
|
@ -0,0 +1,42 @@
|
|||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<title>WebSocket Test</title>
|
||||
</head>
|
||||
<body>
|
||||
<h2>WebSocket Test</h2>
|
||||
<div id="output"></div>
|
||||
<script type="text/javascript">
|
||||
var output = document.getElementById('output');
|
||||
|
||||
function println(message) {
|
||||
const p = document.createElement('p');
|
||||
p.innerHTML = message;
|
||||
output.appendChild(p);
|
||||
}
|
||||
|
||||
// Websocket echo server, provided from https://www.websocket.org/echo.html
|
||||
var targetUrl = 'wss://echo.websocket.org';
|
||||
var messageContent = 'Hello friends :^)';
|
||||
println('<span style="color: blue;">Connecting to:</span> ' + targetUrl);
|
||||
websocket = new WebSocket(targetUrl);
|
||||
websocket.onopen = function() {
|
||||
println('<span style="color: green;">Connected to:</span> ' + targetUrl);
|
||||
println('<span style="color: blue;">Sending Message:</span> ' + messageContent);
|
||||
websocket.send(messageContent);
|
||||
};
|
||||
websocket.onmessage = function(event) {
|
||||
println('<span style="color: green;">Received Response:</span> ' + event.data);
|
||||
println('<span style="color: blue;">Closing connection...</span> ');
|
||||
websocket.close();
|
||||
};
|
||||
websocket.onerror = function(evt) {
|
||||
println('<span style="color: red;">ERROR:</span> ' + evt.data);
|
||||
};
|
||||
websocket.onclose = function() {
|
||||
println('<span style="color: green;">Connection closed!</span>');
|
||||
};
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
|
@ -38,6 +38,7 @@ span#loadtime {
|
|||
<p>This page loaded in <b><span id="loadtime"></span></b> ms</p>
|
||||
<p>Some small test pages:</p>
|
||||
<ul>
|
||||
<li><a href="websocket.html">WebSocket API Test</a></li>
|
||||
<li><a href="cookie.html">document.cookie</a></li>
|
||||
<li><a href="last-of-type.html">CSS :last-of-type selector</a></li>
|
||||
<li><a href="first-of-type.html">CSS :first-of-type selector</a></li>
|
||||
|
|
|
@ -24,6 +24,7 @@
|
|||
#include <LibGUI/TabWidget.h>
|
||||
#include <LibGUI/Window.h>
|
||||
#include <LibGfx/Bitmap.h>
|
||||
#include <LibWeb/HTML/WebSocket.h>
|
||||
#include <LibWeb/Loader/ContentFilter.h>
|
||||
#include <LibWeb/Loader/ResourceLoader.h>
|
||||
#include <stdio.h>
|
||||
|
@ -66,8 +67,9 @@ int main(int argc, char** argv)
|
|||
|
||||
auto app = GUI::Application::construct(argc, argv);
|
||||
|
||||
// Connect to the ProtocolServer immediately so we can drop the "unix" pledge.
|
||||
// Connect to the ProtocolServer and the WebSocket service immediately so we can drop the "unix" pledge.
|
||||
Web::ResourceLoader::the();
|
||||
Web::HTML::WebSocketClientManager::the();
|
||||
|
||||
// Connect to LaunchServer immediately and let it know that we won't ask for anything other than opening
|
||||
// the user's downloads directory.
|
||||
|
|
|
@ -4,8 +4,10 @@
|
|||
* SPDX-License-Identifier: BSD-2-Clause
|
||||
*/
|
||||
|
||||
#include <LibWeb/Bindings/CloseEventWrapper.h>
|
||||
#include <LibWeb/Bindings/EventWrapper.h>
|
||||
#include <LibWeb/Bindings/EventWrapperFactory.h>
|
||||
#include <LibWeb/Bindings/MessageEventWrapper.h>
|
||||
#include <LibWeb/Bindings/MouseEventWrapper.h>
|
||||
|
||||
namespace Web {
|
||||
|
@ -13,6 +15,10 @@ namespace Bindings {
|
|||
|
||||
EventWrapper* wrap(JS::GlobalObject& global_object, DOM::Event& event)
|
||||
{
|
||||
if (is<HTML::MessageEvent>(event))
|
||||
return static_cast<MessageEventWrapper*>(wrap_impl(global_object, static_cast<HTML::MessageEvent&>(event)));
|
||||
if (is<HTML::CloseEvent>(event))
|
||||
return static_cast<CloseEventWrapper*>(wrap_impl(global_object, static_cast<HTML::CloseEvent&>(event)));
|
||||
if (is<UIEvents::MouseEvent>(event))
|
||||
return static_cast<MouseEventWrapper*>(wrap_impl(global_object, static_cast<UIEvents::MouseEvent&>(event)));
|
||||
return static_cast<EventWrapper*>(wrap_impl(global_object, event));
|
||||
|
|
|
@ -14,6 +14,8 @@
|
|||
#include <LibWeb/Bindings/CanvasRenderingContext2DPrototype.h>
|
||||
#include <LibWeb/Bindings/CharacterDataConstructor.h>
|
||||
#include <LibWeb/Bindings/CharacterDataPrototype.h>
|
||||
#include <LibWeb/Bindings/CloseEventConstructor.h>
|
||||
#include <LibWeb/Bindings/CloseEventPrototype.h>
|
||||
#include <LibWeb/Bindings/CommentConstructor.h>
|
||||
#include <LibWeb/Bindings/CommentPrototype.h>
|
||||
#include <LibWeb/Bindings/DOMExceptionConstructor.h>
|
||||
|
@ -177,6 +179,8 @@
|
|||
#include <LibWeb/Bindings/ImageConstructor.h>
|
||||
#include <LibWeb/Bindings/ImageDataConstructor.h>
|
||||
#include <LibWeb/Bindings/ImageDataPrototype.h>
|
||||
#include <LibWeb/Bindings/MessageEventConstructor.h>
|
||||
#include <LibWeb/Bindings/MessageEventPrototype.h>
|
||||
#include <LibWeb/Bindings/MouseEventConstructor.h>
|
||||
#include <LibWeb/Bindings/MouseEventPrototype.h>
|
||||
#include <LibWeb/Bindings/NodeConstructor.h>
|
||||
|
@ -213,6 +217,8 @@
|
|||
#include <LibWeb/Bindings/TextPrototype.h>
|
||||
#include <LibWeb/Bindings/UIEventConstructor.h>
|
||||
#include <LibWeb/Bindings/UIEventPrototype.h>
|
||||
#include <LibWeb/Bindings/WebSocketConstructor.h>
|
||||
#include <LibWeb/Bindings/WebSocketPrototype.h>
|
||||
#include <LibWeb/Bindings/XMLHttpRequestConstructor.h>
|
||||
#include <LibWeb/Bindings/XMLHttpRequestEventTargetConstructor.h>
|
||||
#include <LibWeb/Bindings/XMLHttpRequestEventTargetPrototype.h>
|
||||
|
@ -233,6 +239,7 @@
|
|||
auto& vm = this->vm(); \
|
||||
ADD_WINDOW_OBJECT_INTERFACE(CanvasRenderingContext2D) \
|
||||
ADD_WINDOW_OBJECT_INTERFACE(CharacterData) \
|
||||
ADD_WINDOW_OBJECT_INTERFACE(CloseEvent) \
|
||||
ADD_WINDOW_OBJECT_INTERFACE(Comment) \
|
||||
ADD_WINDOW_OBJECT_INTERFACE(CSSStyleSheet) \
|
||||
ADD_WINDOW_OBJECT_INTERFACE(DocumentFragment) \
|
||||
|
@ -315,6 +322,7 @@
|
|||
ADD_WINDOW_OBJECT_INTERFACE(HTMLUnknownElement) \
|
||||
ADD_WINDOW_OBJECT_INTERFACE(HTMLVideoElement) \
|
||||
ADD_WINDOW_OBJECT_INTERFACE(ImageData) \
|
||||
ADD_WINDOW_OBJECT_INTERFACE(MessageEvent) \
|
||||
ADD_WINDOW_OBJECT_INTERFACE(MouseEvent) \
|
||||
ADD_WINDOW_OBJECT_INTERFACE(Node) \
|
||||
ADD_WINDOW_OBJECT_INTERFACE(Performance) \
|
||||
|
@ -333,6 +341,7 @@
|
|||
ADD_WINDOW_OBJECT_INTERFACE(SVGSVGElement) \
|
||||
ADD_WINDOW_OBJECT_INTERFACE(Text) \
|
||||
ADD_WINDOW_OBJECT_INTERFACE(UIEvent) \
|
||||
ADD_WINDOW_OBJECT_INTERFACE(WebSocket) \
|
||||
ADD_WINDOW_OBJECT_INTERFACE(XMLHttpRequest) \
|
||||
ADD_WINDOW_OBJECT_INTERFACE(XMLHttpRequestEventTarget) \
|
||||
ADD_WINDOW_OBJECT_CONSTRUCTOR_AND_PROTOTYPE(Image, ImageConstructor, HTMLImageElementPrototype)
|
||||
|
|
|
@ -153,6 +153,7 @@ set(SOURCES
|
|||
HTML/Parser/StackOfOpenElements.cpp
|
||||
HTML/SubmitEvent.cpp
|
||||
HTML/TagNames.cpp
|
||||
HTML/WebSocket.cpp
|
||||
HighResolutionTime/Performance.cpp
|
||||
InProcessWebView.cpp
|
||||
Layout/BlockBox.cpp
|
||||
|
@ -318,6 +319,7 @@ libweb_js_wrapper(DOM/Node)
|
|||
libweb_js_wrapper(DOM/Range)
|
||||
libweb_js_wrapper(DOM/Text)
|
||||
libweb_js_wrapper(HTML/CanvasRenderingContext2D)
|
||||
libweb_js_wrapper(HTML/CloseEvent)
|
||||
libweb_js_wrapper(HTML/HTMLAnchorElement)
|
||||
libweb_js_wrapper(HTML/HTMLAreaElement)
|
||||
libweb_js_wrapper(HTML/HTMLAudioElement)
|
||||
|
@ -390,7 +392,9 @@ libweb_js_wrapper(HTML/HTMLUListElement)
|
|||
libweb_js_wrapper(HTML/HTMLUnknownElement)
|
||||
libweb_js_wrapper(HTML/HTMLVideoElement)
|
||||
libweb_js_wrapper(HTML/ImageData)
|
||||
libweb_js_wrapper(HTML/MessageEvent)
|
||||
libweb_js_wrapper(HTML/SubmitEvent)
|
||||
libweb_js_wrapper(HTML/WebSocket)
|
||||
libweb_js_wrapper(HighResolutionTime/Performance)
|
||||
libweb_js_wrapper(NavigationTiming/PerformanceTiming)
|
||||
libweb_js_wrapper(SVG/SVGElement)
|
||||
|
|
|
@ -645,6 +645,12 @@ static void generate_to_cpp(SourceGenerator& generator, ParameterType& parameter
|
|||
auto @cpp_name@ = @js_name@@js_suffix@.to_u32(global_object);
|
||||
if (vm.exception())
|
||||
@return_statement@
|
||||
)~~~");
|
||||
} else if (parameter.type.name == "unsigned short") {
|
||||
scoped_generator.append(R"~~~(
|
||||
auto @cpp_name@ = (u16)@js_name@@js_suffix@.to_u32(global_object);
|
||||
if (vm.exception())
|
||||
@return_statement@
|
||||
)~~~");
|
||||
} else if (parameter.type.name == "EventHandler") {
|
||||
// x.onfoo = function() { ... }
|
||||
|
|
|
@ -58,6 +58,7 @@ enum class QuirksMode;
|
|||
|
||||
namespace Web::HTML {
|
||||
class CanvasRenderingContext2D;
|
||||
class CloseEvent;
|
||||
class EventHandler;
|
||||
class HTMLAnchorElement;
|
||||
class HTMLAreaElement;
|
||||
|
@ -133,6 +134,8 @@ class HTMLUListElement;
|
|||
class HTMLUnknownElement;
|
||||
class HTMLVideoElement;
|
||||
class ImageData;
|
||||
class MessageEvent;
|
||||
class WebSocket;
|
||||
}
|
||||
|
||||
namespace Web::HighResolutionTime {
|
||||
|
@ -201,6 +204,7 @@ class CSSStyleDeclarationWrapper;
|
|||
class CSSStyleSheetWrapper;
|
||||
class CanvasRenderingContext2DWrapper;
|
||||
class CharacterDataWrapper;
|
||||
class CloseEventWrapper;
|
||||
class CommentWrapper;
|
||||
class DocumentFragmentWrapper;
|
||||
class DocumentTypeWrapper;
|
||||
|
@ -285,6 +289,7 @@ class HTMLUnknownElementWrapper;
|
|||
class HTMLVideoElementWrapper;
|
||||
class ImageDataWrapper;
|
||||
class LocationObject;
|
||||
class MessageEventWrapper;
|
||||
class MouseEventWrapper;
|
||||
class NodeWrapper;
|
||||
class PerformanceTimingWrapper;
|
||||
|
@ -303,6 +308,7 @@ class StyleSheetWrapper;
|
|||
class StyleSheetListWrapper;
|
||||
class TextWrapper;
|
||||
class UIEventWrapper;
|
||||
class WebSocketWrapper;
|
||||
class WindowObject;
|
||||
class Wrappable;
|
||||
class Wrapper;
|
||||
|
|
42
Userland/Libraries/LibWeb/HTML/CloseEvent.h
Normal file
42
Userland/Libraries/LibWeb/HTML/CloseEvent.h
Normal file
|
@ -0,0 +1,42 @@
|
|||
/*
|
||||
* Copyright (c) 2021, Dex♪ <dexes.ttp@gmail.com>
|
||||
*
|
||||
* SPDX-License-Identifier: BSD-2-Clause
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <LibWeb/DOM/Event.h>
|
||||
|
||||
namespace Web::HTML {
|
||||
|
||||
class CloseEvent : public DOM::Event {
|
||||
public:
|
||||
using WrapperType = Bindings::CloseEventWrapper;
|
||||
|
||||
static NonnullRefPtr<CloseEvent> create(const FlyString& event_name, bool was_clean, u16 code, const String& reason)
|
||||
{
|
||||
return adopt_ref(*new CloseEvent(event_name, was_clean, code, reason));
|
||||
}
|
||||
|
||||
virtual ~CloseEvent() override = default;
|
||||
|
||||
bool was_clean() { return m_was_clean; }
|
||||
u16 code() const { return m_code; }
|
||||
String reason() const { return m_reason; }
|
||||
|
||||
protected:
|
||||
CloseEvent(const FlyString& event_name, bool was_clean, u16 code, const String& reason)
|
||||
: Event(event_name)
|
||||
, m_was_clean(was_clean)
|
||||
, m_code(code)
|
||||
, m_reason(reason)
|
||||
{
|
||||
}
|
||||
|
||||
bool m_was_clean { false };
|
||||
u16 m_code { 0 };
|
||||
String m_reason;
|
||||
};
|
||||
|
||||
}
|
7
Userland/Libraries/LibWeb/HTML/CloseEvent.idl
Normal file
7
Userland/Libraries/LibWeb/HTML/CloseEvent.idl
Normal file
|
@ -0,0 +1,7 @@
|
|||
interface CloseEvent : Event {
|
||||
|
||||
readonly attribute boolean wasClean;
|
||||
readonly attribute unsigned short code;
|
||||
readonly attribute USVString reason;
|
||||
|
||||
};
|
39
Userland/Libraries/LibWeb/HTML/MessageEvent.h
Normal file
39
Userland/Libraries/LibWeb/HTML/MessageEvent.h
Normal file
|
@ -0,0 +1,39 @@
|
|||
/*
|
||||
* Copyright (c) 2021, Dex♪ <dexes.ttp@gmail.com>
|
||||
*
|
||||
* SPDX-License-Identifier: BSD-2-Clause
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <LibWeb/DOM/Event.h>
|
||||
|
||||
namespace Web::HTML {
|
||||
|
||||
class MessageEvent : public DOM::Event {
|
||||
public:
|
||||
using WrapperType = Bindings::MessageEventWrapper;
|
||||
|
||||
static NonnullRefPtr<MessageEvent> create(const FlyString& event_name, const String& data, const String& origin)
|
||||
{
|
||||
return adopt_ref(*new MessageEvent(event_name, data, origin));
|
||||
}
|
||||
|
||||
virtual ~MessageEvent() override = default;
|
||||
|
||||
const String& data() const { return m_data; }
|
||||
const String& origin() const { return m_origin; }
|
||||
|
||||
protected:
|
||||
MessageEvent(const FlyString& event_name, const String& data, const String& origin)
|
||||
: DOM::Event(event_name)
|
||||
, m_data(data)
|
||||
, m_origin(origin)
|
||||
{
|
||||
}
|
||||
|
||||
String m_data;
|
||||
String m_origin;
|
||||
};
|
||||
|
||||
}
|
7
Userland/Libraries/LibWeb/HTML/MessageEvent.idl
Normal file
7
Userland/Libraries/LibWeb/HTML/MessageEvent.idl
Normal file
|
@ -0,0 +1,7 @@
|
|||
interface MessageEvent : Event {
|
||||
|
||||
// FIXME: This should be of type "any" instead of "USVString"
|
||||
readonly attribute USVString data;
|
||||
readonly attribute USVString origin;
|
||||
|
||||
};
|
274
Userland/Libraries/LibWeb/HTML/WebSocket.cpp
Normal file
274
Userland/Libraries/LibWeb/HTML/WebSocket.cpp
Normal file
|
@ -0,0 +1,274 @@
|
|||
/*
|
||||
* Copyright (c) 2021, Dex♪ <dexes.ttp@gmail.com>
|
||||
*
|
||||
* SPDX-License-Identifier: BSD-2-Clause
|
||||
*/
|
||||
|
||||
#include <LibJS/Interpreter.h>
|
||||
#include <LibJS/Parser.h>
|
||||
#include <LibJS/Runtime/Function.h>
|
||||
#include <LibJS/Runtime/ScriptFunction.h>
|
||||
#include <LibProtocol/WebSocket.h>
|
||||
#include <LibProtocol/WebSocketClient.h>
|
||||
#include <LibWeb/Bindings/EventWrapper.h>
|
||||
#include <LibWeb/Bindings/WebSocketWrapper.h>
|
||||
#include <LibWeb/DOM/DOMException.h>
|
||||
#include <LibWeb/DOM/Document.h>
|
||||
#include <LibWeb/DOM/Event.h>
|
||||
#include <LibWeb/DOM/EventDispatcher.h>
|
||||
#include <LibWeb/DOM/EventListener.h>
|
||||
#include <LibWeb/DOM/ExceptionOr.h>
|
||||
#include <LibWeb/DOM/Window.h>
|
||||
#include <LibWeb/HTML/CloseEvent.h>
|
||||
#include <LibWeb/HTML/EventHandler.h>
|
||||
#include <LibWeb/HTML/EventNames.h>
|
||||
#include <LibWeb/HTML/MessageEvent.h>
|
||||
#include <LibWeb/HTML/WebSocket.h>
|
||||
#include <LibWeb/Origin.h>
|
||||
|
||||
namespace Web::HTML {
|
||||
|
||||
WebSocketClientManager& WebSocketClientManager::the()
|
||||
{
|
||||
static WebSocketClientManager* s_the;
|
||||
if (!s_the)
|
||||
s_the = &WebSocketClientManager::construct().leak_ref();
|
||||
return *s_the;
|
||||
}
|
||||
|
||||
WebSocketClientManager::WebSocketClientManager()
|
||||
: m_websocket_client(Protocol::WebSocketClient::construct())
|
||||
{
|
||||
}
|
||||
|
||||
RefPtr<Protocol::WebSocket> WebSocketClientManager::connect(const URL& url)
|
||||
{
|
||||
return m_websocket_client->connect(url);
|
||||
}
|
||||
|
||||
// https://html.spec.whatwg.org/multipage/web-sockets.html#the-websocket-interface
|
||||
DOM::ExceptionOr<NonnullRefPtr<WebSocket>> WebSocket::create_with_global_object(Bindings::WindowObject& window, const String& url)
|
||||
{
|
||||
URL url_record(url);
|
||||
if (!url_record.is_valid())
|
||||
return DOM::SyntaxError::create("Invalid URL");
|
||||
if (!url_record.protocol().is_one_of("ws", "wss"))
|
||||
return DOM::SyntaxError::create("Invalid protocol");
|
||||
if (!url_record.fragment().is_empty())
|
||||
return DOM::SyntaxError::create("Presence of URL fragment is invalid");
|
||||
// 5. If `protocols` is a string, set `protocols` to a sequence consisting of just that string
|
||||
// 6. If any of the values in `protocols` occur more than once or otherwise fail to match the requirements, throw SyntaxError
|
||||
return WebSocket::create(window.impl(), url_record);
|
||||
}
|
||||
|
||||
WebSocket::WebSocket(DOM::Window& window, URL& url)
|
||||
: EventTarget(static_cast<Bindings::ScriptExecutionContext&>(window.document()))
|
||||
, m_window(window)
|
||||
{
|
||||
// FIXME: Integrate properly with FETCH as per https://fetch.spec.whatwg.org/#websocket-opening-handshake
|
||||
m_websocket = WebSocketClientManager::the().connect(url);
|
||||
m_websocket->on_open = [weak_this = make_weak_ptr()] {
|
||||
if (!weak_this)
|
||||
return;
|
||||
auto& websocket = const_cast<WebSocket&>(*weak_this);
|
||||
websocket.on_open();
|
||||
};
|
||||
m_websocket->on_message = [weak_this = make_weak_ptr()](auto message) {
|
||||
if (!weak_this)
|
||||
return;
|
||||
auto& websocket = const_cast<WebSocket&>(*weak_this);
|
||||
websocket.on_message(move(message.data), message.is_text);
|
||||
};
|
||||
m_websocket->on_close = [weak_this = make_weak_ptr()](auto code, auto reason, bool was_clean) {
|
||||
if (!weak_this)
|
||||
return;
|
||||
auto& websocket = const_cast<WebSocket&>(*weak_this);
|
||||
websocket.on_close(code, reason, was_clean);
|
||||
};
|
||||
m_websocket->on_error = [weak_this = make_weak_ptr()](auto) {
|
||||
if (!weak_this)
|
||||
return;
|
||||
auto& websocket = const_cast<WebSocket&>(*weak_this);
|
||||
websocket.on_error();
|
||||
};
|
||||
}
|
||||
|
||||
WebSocket::~WebSocket()
|
||||
{
|
||||
}
|
||||
|
||||
// https://html.spec.whatwg.org/multipage/web-sockets.html#the-websocket-interface
|
||||
WebSocket::ReadyState WebSocket::ready_state() const
|
||||
{
|
||||
if (!m_websocket)
|
||||
return WebSocket::ReadyState::Closed;
|
||||
auto ready_state = const_cast<Protocol::WebSocket&>(*m_websocket).ready_state();
|
||||
switch (ready_state) {
|
||||
case Protocol::WebSocket::ReadyState::Connecting:
|
||||
return WebSocket::ReadyState::Connecting;
|
||||
case Protocol::WebSocket::ReadyState::Open:
|
||||
return WebSocket::ReadyState::Open;
|
||||
case Protocol::WebSocket::ReadyState::Closing:
|
||||
return WebSocket::ReadyState::Closing;
|
||||
case Protocol::WebSocket::ReadyState::Closed:
|
||||
return WebSocket::ReadyState::Closed;
|
||||
}
|
||||
return WebSocket::ReadyState::Closed;
|
||||
}
|
||||
|
||||
// https://html.spec.whatwg.org/multipage/web-sockets.html#the-websocket-interface
|
||||
String WebSocket::extensions() const
|
||||
{
|
||||
if (!m_websocket)
|
||||
return String::empty();
|
||||
// https://html.spec.whatwg.org/multipage/web-sockets.html#feedback-from-the-protocol
|
||||
// FIXME: Change the extensions attribute's value to the extensions in use, if it is not the null value.
|
||||
return String::empty();
|
||||
}
|
||||
|
||||
// https://html.spec.whatwg.org/multipage/web-sockets.html#the-websocket-interface
|
||||
String WebSocket::protocol() const
|
||||
{
|
||||
if (!m_websocket)
|
||||
return String::empty();
|
||||
// https://html.spec.whatwg.org/multipage/web-sockets.html#feedback-from-the-protocol
|
||||
// FIXME: Change the protocol attribute's value to the subprotocol in use, if it is not the null value.
|
||||
return String::empty();
|
||||
}
|
||||
|
||||
// https://html.spec.whatwg.org/multipage/web-sockets.html#the-websocket-interface
|
||||
DOM::ExceptionOr<void> WebSocket::close(u16 code, const String& reason)
|
||||
{
|
||||
// HACK : we should have an Optional<u16>
|
||||
if (code == 0)
|
||||
code = 1000;
|
||||
if (code != 1000 && (code < 3000 || code > 4099))
|
||||
return DOM::InvalidAccessError::create("The close error code is invalid");
|
||||
if (!reason.is_empty() && reason.bytes().size() > 123)
|
||||
return DOM::SyntaxError::create("The close reason is longer than 123 bytes");
|
||||
auto state = ready_state();
|
||||
if (state == WebSocket::ReadyState::Closing || state == WebSocket::ReadyState::Closed)
|
||||
return {};
|
||||
// Note : Both of these are handled by the WebSocket Protocol when calling close()
|
||||
// 3b. If the WebSocket connection is not yet established [WSP]
|
||||
// 3c. If the WebSocket closing handshake has not yet been started [WSP]
|
||||
m_websocket->close(code, reason);
|
||||
return {};
|
||||
}
|
||||
|
||||
// https://html.spec.whatwg.org/multipage/web-sockets.html#the-websocket-interface
|
||||
DOM::ExceptionOr<void> WebSocket::send(const String& data)
|
||||
{
|
||||
auto state = ready_state();
|
||||
if (state == WebSocket::ReadyState::Connecting)
|
||||
return DOM::InvalidStateError::create("Websocket is still CONNECTING");
|
||||
if (state == WebSocket::ReadyState::Open) {
|
||||
m_websocket->send(data);
|
||||
// TODO : If the data cannot be sent, e.g. because it would need to be buffered but the buffer is full, the user agent must flag the WebSocket as full and then close the WebSocket connection.
|
||||
// TODO : Any invocation of this method with a string argument that does not throw an exception must increase the bufferedAmount attribute by the number of bytes needed to express the argument as UTF-8.
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
// https://html.spec.whatwg.org/multipage/web-sockets.html#feedback-from-the-protocol
|
||||
void WebSocket::on_open()
|
||||
{
|
||||
// 1. Change the readyState attribute's value to OPEN (1).
|
||||
// 2. Change the extensions attribute's value to the extensions in use, if it is not the null value. [WSP]
|
||||
// 3. Change the protocol attribute's value to the subprotocol in use, if it is not the null value. [WSP]
|
||||
dispatch_event(DOM::Event::create(EventNames::open));
|
||||
}
|
||||
|
||||
// https://html.spec.whatwg.org/multipage/web-sockets.html#feedback-from-the-protocol
|
||||
void WebSocket::on_error()
|
||||
{
|
||||
dispatch_event(DOM::Event::create(EventNames::error));
|
||||
}
|
||||
|
||||
// https://html.spec.whatwg.org/multipage/web-sockets.html#feedback-from-the-protocol
|
||||
void WebSocket::on_close(u16 code, String reason, bool was_clean)
|
||||
{
|
||||
// 1. Change the readyState attribute's value to CLOSED. This is handled by the Protocol's WebSocket
|
||||
// 2. If [needed], fire an event named error at the WebSocket object. This is handled by the Protocol's WebSocket
|
||||
dispatch_event(CloseEvent::create(EventNames::close, was_clean, code, reason));
|
||||
}
|
||||
|
||||
// https://html.spec.whatwg.org/multipage/web-sockets.html#feedback-from-the-protocol
|
||||
void WebSocket::on_message(ByteBuffer message, bool is_text)
|
||||
{
|
||||
if (m_websocket->ready_state() != Protocol::WebSocket::ReadyState::Open)
|
||||
return;
|
||||
if (is_text) {
|
||||
auto text_message = String(ReadonlyBytes(message));
|
||||
dispatch_event(MessageEvent::create(EventNames::message, text_message, url()));
|
||||
return;
|
||||
}
|
||||
// type indicates that the data is Binary and binaryType is "blob"
|
||||
// type indicates that the data is Binary and binaryType is "arraybuffer"
|
||||
TODO();
|
||||
}
|
||||
|
||||
bool WebSocket::dispatch_event(NonnullRefPtr<DOM::Event> event)
|
||||
{
|
||||
return DOM::EventDispatcher::dispatch(*this, move(event));
|
||||
}
|
||||
|
||||
JS::Object* WebSocket::create_wrapper(JS::GlobalObject& global_object)
|
||||
{
|
||||
return wrap(global_object, *this);
|
||||
}
|
||||
|
||||
#undef __ENUMERATE
|
||||
#define __ENUMERATE(attribute_name, event_name) \
|
||||
void WebSocket::set_##attribute_name(HTML::EventHandler value) \
|
||||
{ \
|
||||
set_event_handler_attribute(event_name, move(value)); \
|
||||
} \
|
||||
HTML::EventHandler WebSocket::attribute_name() \
|
||||
{ \
|
||||
return get_event_handler_attribute(event_name); \
|
||||
}
|
||||
ENUMERATE_WEBSOCKET_EVENT_HANDLERS(__ENUMERATE)
|
||||
#undef __ENUMERATE
|
||||
|
||||
// FIXME: This is copied from GlobalEventHandlers.cpp. Find a way to deduplicate it.
|
||||
void WebSocket::set_event_handler_attribute(const FlyString& name, HTML::EventHandler value)
|
||||
{
|
||||
RefPtr<DOM::EventListener> listener;
|
||||
if (!value.callback.is_null()) {
|
||||
listener = adopt_ref(*new DOM::EventListener(move(value.callback)));
|
||||
} else {
|
||||
StringBuilder builder;
|
||||
builder.appendff("function {}(event) {{\n{}\n}}", name, value.string);
|
||||
auto parser = JS::Parser(JS::Lexer(builder.string_view()));
|
||||
auto program = parser.parse_function_node<JS::FunctionExpression>();
|
||||
if (parser.has_errors()) {
|
||||
dbgln("Failed to parse script in event handler attribute '{}'", name);
|
||||
return;
|
||||
}
|
||||
auto* function = JS::ScriptFunction::create(script_execution_context()->interpreter().global_object(), name, program->body(), program->parameters(), program->function_length(), nullptr, false, false);
|
||||
VERIFY(function);
|
||||
listener = adopt_ref(*new DOM::EventListener(JS::make_handle(static_cast<JS::Function*>(function))));
|
||||
}
|
||||
if (listener) {
|
||||
for (auto& registered_listener : listeners()) {
|
||||
if (registered_listener.event_name == name && registered_listener.listener->is_attribute()) {
|
||||
remove_event_listener(name, registered_listener.listener);
|
||||
break;
|
||||
}
|
||||
}
|
||||
add_event_listener(name, listener.release_nonnull());
|
||||
}
|
||||
}
|
||||
|
||||
HTML::EventHandler WebSocket::get_event_handler_attribute(const FlyString& name)
|
||||
{
|
||||
for (auto& listener : listeners()) {
|
||||
if (listener.event_name == name && listener.listener->is_attribute())
|
||||
return HTML::EventHandler { JS::make_handle(&listener.listener->function()) };
|
||||
}
|
||||
|
||||
return {};
|
||||
}
|
||||
|
||||
}
|
114
Userland/Libraries/LibWeb/HTML/WebSocket.h
Normal file
114
Userland/Libraries/LibWeb/HTML/WebSocket.h
Normal file
|
@ -0,0 +1,114 @@
|
|||
/*
|
||||
* Copyright (c) 2021, Dex♪ <dexes.ttp@gmail.com>
|
||||
*
|
||||
* SPDX-License-Identifier: BSD-2-Clause
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <AK/ByteBuffer.h>
|
||||
#include <AK/RefCounted.h>
|
||||
#include <AK/URL.h>
|
||||
#include <AK/Weakable.h>
|
||||
#include <LibCore/Object.h>
|
||||
#include <LibWeb/Bindings/WindowObject.h>
|
||||
#include <LibWeb/Bindings/Wrappable.h>
|
||||
#include <LibWeb/DOM/EventTarget.h>
|
||||
#include <LibWeb/DOM/ExceptionOr.h>
|
||||
#include <LibWeb/Forward.h>
|
||||
|
||||
#define ENUMERATE_WEBSOCKET_EVENT_HANDLERS(E) \
|
||||
E(onerror, HTML::EventNames::error) \
|
||||
E(onclose, HTML::EventNames::close) \
|
||||
E(onopen, HTML::EventNames::open) \
|
||||
E(onmessage, HTML::EventNames::message)
|
||||
|
||||
namespace Protocol {
|
||||
class WebSocketClient;
|
||||
class WebSocket;
|
||||
}
|
||||
|
||||
namespace Web::HTML {
|
||||
|
||||
class WebSocketClientManager : public Core::Object {
|
||||
C_OBJECT(WebSocketClientManager)
|
||||
public:
|
||||
static WebSocketClientManager& the();
|
||||
|
||||
RefPtr<Protocol::WebSocket> connect(const URL&);
|
||||
|
||||
private:
|
||||
WebSocketClientManager();
|
||||
RefPtr<Protocol::WebSocketClient> m_websocket_client;
|
||||
};
|
||||
|
||||
class WebSocket final
|
||||
: public RefCounted<WebSocket>
|
||||
, public Weakable<WebSocket>
|
||||
, public DOM::EventTarget
|
||||
, public Bindings::Wrappable {
|
||||
public:
|
||||
enum class ReadyState : u16 {
|
||||
Connecting = 0,
|
||||
Open = 1,
|
||||
Closing = 2,
|
||||
Closed = 3,
|
||||
};
|
||||
|
||||
using WrapperType = Bindings::WebSocketWrapper;
|
||||
|
||||
static NonnullRefPtr<WebSocket> create(DOM::Window& window, URL& url)
|
||||
{
|
||||
return adopt_ref(*new WebSocket(window, url));
|
||||
}
|
||||
|
||||
static DOM::ExceptionOr<NonnullRefPtr<WebSocket>> create_with_global_object(Bindings::WindowObject& window, const String& url);
|
||||
|
||||
virtual ~WebSocket() override;
|
||||
|
||||
using RefCounted::ref;
|
||||
using RefCounted::unref;
|
||||
|
||||
String url() const { return m_url.to_string(); }
|
||||
|
||||
#undef __ENUMERATE
|
||||
#define __ENUMERATE(attribute_name, event_name) \
|
||||
void set_##attribute_name(HTML::EventHandler); \
|
||||
HTML::EventHandler attribute_name();
|
||||
ENUMERATE_WEBSOCKET_EVENT_HANDLERS(__ENUMERATE)
|
||||
#undef __ENUMERATE
|
||||
|
||||
void set_event_handler_attribute(const FlyString& name, HTML::EventHandler);
|
||||
HTML::EventHandler get_event_handler_attribute(const FlyString& name);
|
||||
|
||||
ReadyState ready_state() const;
|
||||
String extensions() const;
|
||||
String protocol() const;
|
||||
|
||||
const String& binary_type() { return m_binary_type; };
|
||||
void set_binary_type(const String& type) { m_binary_type = type; };
|
||||
|
||||
DOM::ExceptionOr<void> close(u16 code, const String& reason);
|
||||
DOM::ExceptionOr<void> send(const String& data);
|
||||
|
||||
private:
|
||||
virtual void ref_event_target() override { ref(); }
|
||||
virtual void unref_event_target() override { unref(); }
|
||||
virtual bool dispatch_event(NonnullRefPtr<DOM::Event>) override;
|
||||
virtual JS::Object* create_wrapper(JS::GlobalObject&) override;
|
||||
|
||||
void on_open();
|
||||
void on_message(ByteBuffer message, bool is_text);
|
||||
void on_error();
|
||||
void on_close(u16 code, String reason, bool was_clean);
|
||||
|
||||
explicit WebSocket(DOM::Window&, URL&);
|
||||
|
||||
NonnullRefPtr<DOM::Window> m_window;
|
||||
|
||||
URL m_url;
|
||||
String m_binary_type { "blob" };
|
||||
RefPtr<Protocol::WebSocket> m_websocket;
|
||||
};
|
||||
|
||||
}
|
29
Userland/Libraries/LibWeb/HTML/WebSocket.idl
Normal file
29
Userland/Libraries/LibWeb/HTML/WebSocket.idl
Normal file
|
@ -0,0 +1,29 @@
|
|||
interface WebSocket : EventTarget {
|
||||
|
||||
// FIXME: A second "protocols" argument should be added once supported
|
||||
constructor(USVString url);
|
||||
|
||||
readonly attribute USVString url;
|
||||
|
||||
const unsigned short CONNECTING = 0;
|
||||
const unsigned short OPEN = 1;
|
||||
const unsigned short CLOSING = 2;
|
||||
const unsigned short CLOSED = 3;
|
||||
readonly attribute unsigned short readyState;
|
||||
// readonly attribute unsigned long long bufferedAmount;
|
||||
|
||||
attribute EventHandler onopen;
|
||||
attribute EventHandler onerror;
|
||||
attribute EventHandler onclose;
|
||||
readonly attribute DOMString extensions;
|
||||
readonly attribute DOMString protocol;
|
||||
undefined close(optional unsigned short code, optional USVString reason);
|
||||
|
||||
attribute EventHandler onmessage;
|
||||
attribute DOMString binaryType;
|
||||
undefined send(USVString data);
|
||||
// FIXME: Support other kinds of send() calls
|
||||
// undefined send(Blob data);
|
||||
// undefined send(ArrayBuffer data);
|
||||
// undefined send(ArrayBufferView data);
|
||||
};
|
|
@ -28,6 +28,10 @@ int main(int, char**)
|
|||
perror("unveil");
|
||||
return 1;
|
||||
}
|
||||
if (unveil("/tmp/portal/websocket", "rw") < 0) {
|
||||
perror("unveil");
|
||||
return 1;
|
||||
}
|
||||
if (unveil(nullptr, nullptr) < 0) {
|
||||
perror("unveil");
|
||||
return 1;
|
||||
|
|
Loading…
Reference in a new issue