Nothing much just a build up of things
[anni] / lib / phoenix / transports / web_socket / raw.ex
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2022 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
4
5 defmodule Phoenix.Transports.WebSocket.Raw do
6   import Plug.Conn,
7     only: [
8       fetch_query_params: 1,
9       send_resp: 3
10     ]
11
12   alias Phoenix.Socket.Transport
13
14   def default_config do
15     [
16       timeout: 60_000,
17       transport_log: false,
18       cowboy: Phoenix.Endpoint.CowboyWebSocket
19     ]
20   end
21
22   def init(%Plug.Conn{method: "GET"} = conn, {endpoint, handler, transport}) do
23     {_, opts} = handler.__transport__(transport)
24
25     conn =
26       conn
27       |> fetch_query_params
28       |> Transport.transport_log(opts[:transport_log])
29       |> Transport.force_ssl(handler, endpoint, opts)
30       |> Transport.check_origin(handler, endpoint, opts)
31
32     case conn do
33       %{halted: false} = conn ->
34         case handler.connect(%{
35                endpoint: endpoint,
36                transport: transport,
37                options: [serializer: nil],
38                params: conn.params
39              }) do
40           {:ok, socket} ->
41             {:ok, conn, {__MODULE__, {socket, opts}}}
42
43           :error ->
44             send_resp(conn, :forbidden, "")
45             {:error, conn}
46         end
47
48       _ ->
49         {:error, conn}
50     end
51   end
52
53   def init(conn, _) do
54     send_resp(conn, :bad_request, "")
55     {:error, conn}
56   end
57
58   def ws_init({socket, config}) do
59     Process.flag(:trap_exit, true)
60     {:ok, %{socket: socket}, config[:timeout]}
61   end
62
63   def ws_handle(op, data, state) do
64     state.socket.handler
65     |> apply(:handle, [op, data, state])
66     |> case do
67       {op, data} ->
68         {:reply, {op, data}, state}
69
70       {op, data, state} ->
71         {:reply, {op, data}, state}
72
73       %{} = state ->
74         {:ok, state}
75
76       _ ->
77         {:ok, state}
78     end
79   end
80
81   def ws_info({_, _} = tuple, state) do
82     {:reply, tuple, state}
83   end
84
85   def ws_info(_tuple, state), do: {:ok, state}
86
87   def ws_close(state) do
88     ws_handle(:closed, :normal, state)
89   end
90
91   def ws_terminate(reason, state) do
92     ws_handle(:closed, reason, state)
93   end
94 end