common_fixes: Get fixes common from Audio and Question
[akkoma] / lib / transports.ex
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2020 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 Transport.connect(endpoint, handler, transport, __MODULE__, nil, conn.params) do
35 {:ok, socket} ->
36 {:ok, conn, {__MODULE__, {socket, opts}}}
37
38 :error ->
39 send_resp(conn, :forbidden, "")
40 {:error, conn}
41 end
42
43 _ ->
44 {:error, conn}
45 end
46 end
47
48 def init(conn, _) do
49 send_resp(conn, :bad_request, "")
50 {:error, conn}
51 end
52
53 def ws_init({socket, config}) do
54 Process.flag(:trap_exit, true)
55 {:ok, %{socket: socket}, config[:timeout]}
56 end
57
58 def ws_handle(op, data, state) do
59 state.socket.handler
60 |> apply(:handle, [op, data, state])
61 |> case do
62 {op, data} ->
63 {:reply, {op, data}, state}
64
65 {op, data, state} ->
66 {:reply, {op, data}, state}
67
68 %{} = state ->
69 {:ok, state}
70
71 _ ->
72 {:ok, state}
73 end
74 end
75
76 def ws_info({_, _} = tuple, state) do
77 {:reply, tuple, state}
78 end
79
80 def ws_info(_tuple, state), do: {:ok, state}
81
82 def ws_close(state) do
83 ws_handle(:closed, :normal, state)
84 end
85
86 def ws_terminate(reason, state) do
87 ws_handle(:closed, reason, state)
88 end
89 end