Merge branch 'develop' of git.pleroma.social:pleroma/pleroma into develop
[akkoma] / lib / transports.ex
1 defmodule Phoenix.Transports.WebSocket.Raw do
2 import Plug.Conn,
3 only: [
4 fetch_query_params: 1,
5 send_resp: 3
6 ]
7
8 alias Phoenix.Socket.Transport
9
10 def default_config do
11 [
12 timeout: 60_000,
13 transport_log: false,
14 cowboy: Phoenix.Endpoint.CowboyWebSocket
15 ]
16 end
17
18 def init(%Plug.Conn{method: "GET"} = conn, {endpoint, handler, transport}) do
19 {_, opts} = handler.__transport__(transport)
20
21 conn =
22 conn
23 |> fetch_query_params
24 |> Transport.transport_log(opts[:transport_log])
25 |> Transport.force_ssl(handler, endpoint, opts)
26 |> Transport.check_origin(handler, endpoint, opts)
27
28 case conn do
29 %{halted: false} = conn ->
30 case Transport.connect(endpoint, handler, transport, __MODULE__, nil, conn.params) do
31 {:ok, socket} ->
32 {:ok, conn, {__MODULE__, {socket, opts}}}
33
34 :error ->
35 send_resp(conn, :forbidden, "")
36 {:error, conn}
37 end
38
39 _ ->
40 {:error, conn}
41 end
42 end
43
44 def init(conn, _) do
45 send_resp(conn, :bad_request, "")
46 {:error, conn}
47 end
48
49 def ws_init({socket, config}) do
50 Process.flag(:trap_exit, true)
51 {:ok, %{socket: socket}, config[:timeout]}
52 end
53
54 def ws_handle(op, data, state) do
55 state.socket.handler
56 |> apply(:handle, [op, data, state])
57 |> case do
58 {op, data} ->
59 {:reply, {op, data}, state}
60
61 {op, data, state} ->
62 {:reply, {op, data}, state}
63
64 %{} = state ->
65 {:ok, state}
66
67 _ ->
68 {:ok, state}
69 end
70 end
71
72 def ws_info({_, _} = tuple, state) do
73 {:reply, tuple, state}
74 end
75
76 def ws_info(_tuple, state), do: {:ok, state}
77
78 def ws_close(state) do
79 ws_handle(:closed, :normal, state)
80 end
81
82 def ws_terminate(reason, state) do
83 ws_handle(:closed, reason, state)
84 end
85 end