2018-12-23 13:11:29 -07:00
|
|
|
# Pleroma: A lightweight social networking server
|
2023-01-02 13:38:50 -07:00
|
|
|
# Copyright © 2017-2022 Pleroma Authors <https://pleroma.social/>
|
2018-12-23 13:11:29 -07:00
|
|
|
# SPDX-License-Identifier: AGPL-3.0-only
|
|
|
|
|
2018-12-17 09:09:06 -07:00
|
|
|
defmodule Pleroma.Integration.WebsocketClient do
|
2022-09-02 16:35:40 -06:00
|
|
|
# https://github.com/phoenixframework/phoenix/blob/master/test/support/websocket_client.exs
|
2022-03-19 23:33:37 -06:00
|
|
|
|
2022-08-19 11:56:39 -06:00
|
|
|
use WebSockex
|
|
|
|
|
2022-03-19 23:33:37 -06:00
|
|
|
@doc """
|
2022-09-02 16:35:40 -06:00
|
|
|
Starts the WebSocket server for given ws URL. Received Socket.Message's
|
|
|
|
are forwarded to the sender pid
|
2022-03-19 23:33:37 -06:00
|
|
|
"""
|
2022-09-02 16:35:40 -06:00
|
|
|
def start_link(sender, url, headers \\ []) do
|
2022-08-19 11:56:39 -06:00
|
|
|
WebSockex.start_link(
|
|
|
|
url,
|
2022-09-02 16:35:40 -06:00
|
|
|
__MODULE__,
|
2022-08-19 11:56:39 -06:00
|
|
|
%{sender: sender},
|
2022-09-02 16:35:40 -06:00
|
|
|
extra_headers: headers
|
|
|
|
)
|
2018-12-17 09:09:06 -07:00
|
|
|
end
|
|
|
|
|
|
|
|
@doc """
|
|
|
|
Closes the socket
|
|
|
|
"""
|
|
|
|
def close(socket) do
|
2022-09-02 16:35:40 -06:00
|
|
|
send(socket, :close)
|
2018-12-17 09:09:06 -07:00
|
|
|
end
|
|
|
|
|
|
|
|
@doc """
|
|
|
|
Sends a low-level text message to the client.
|
|
|
|
"""
|
|
|
|
def send_text(server_pid, msg) do
|
2022-09-02 16:35:40 -06:00
|
|
|
send(server_pid, {:text, msg})
|
2018-12-17 09:09:06 -07:00
|
|
|
end
|
|
|
|
|
|
|
|
@doc false
|
2022-08-19 11:56:39 -06:00
|
|
|
@impl true
|
|
|
|
def handle_frame(frame, state) do
|
2022-09-02 16:35:40 -06:00
|
|
|
send(state.sender, frame)
|
|
|
|
{:ok, state}
|
2018-12-17 09:09:06 -07:00
|
|
|
end
|
|
|
|
|
2022-08-19 12:09:42 -06:00
|
|
|
@impl true
|
|
|
|
def handle_disconnect(conn_status, state) do
|
|
|
|
send(state.sender, {:close, conn_status})
|
|
|
|
{:ok, state}
|
|
|
|
end
|
|
|
|
|
2018-12-17 09:09:06 -07:00
|
|
|
@doc false
|
2022-08-19 11:56:39 -06:00
|
|
|
@impl true
|
|
|
|
def handle_info({:text, msg}, state) do
|
2022-09-02 16:35:40 -06:00
|
|
|
{:reply, {:text, msg}, state}
|
2022-03-19 23:33:37 -06:00
|
|
|
end
|
|
|
|
|
2022-08-19 11:56:39 -06:00
|
|
|
@impl true
|
|
|
|
def handle_info(:close, _state) do
|
2022-09-02 16:35:40 -06:00
|
|
|
{:close, <<>>, "done"}
|
2022-03-19 23:33:37 -06:00
|
|
|
end
|
|
|
|
|
2022-09-02 16:35:40 -06:00
|
|
|
@doc false
|
2022-08-19 11:56:39 -06:00
|
|
|
@impl true
|
|
|
|
def terminate(_reason, _state) do
|
2022-09-02 16:35:40 -06:00
|
|
|
:ok
|
2018-12-17 09:09:06 -07:00
|
|
|
end
|
|
|
|
end
|