quarantine instances info
[akkoma] / lib / pleroma / web / mastodon_api / websocket_handler.ex
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
4
5 defmodule Pleroma.Web.MastodonAPI.WebsocketHandler do
6 require Logger
7
8 alias Pleroma.Repo
9 alias Pleroma.User
10 alias Pleroma.Web.OAuth.Token
11 alias Pleroma.Web.Streamer
12
13 @behaviour :cowboy_websocket
14
15 # Client ping period.
16 @tick :timer.seconds(30)
17 # Cowboy timeout period.
18 @timeout :timer.seconds(60)
19 # Hibernate every X messages
20 @hibernate_every 100
21
22 def init(%{qs: qs} = req, state) do
23 with params <- Enum.into(:cow_qs.parse_qs(qs), %{}),
24 sec_websocket <- :cowboy_req.header("sec-websocket-protocol", req, nil),
25 access_token <- Map.get(params, "access_token"),
26 {:ok, user, oauth_token} <- authenticate_request(access_token, sec_websocket),
27 {:ok, topic} <- Streamer.get_topic(params["stream"], user, oauth_token, params) do
28 req =
29 if sec_websocket do
30 :cowboy_req.set_resp_header("sec-websocket-protocol", sec_websocket, req)
31 else
32 req
33 end
34
35 {:cowboy_websocket, req, %{user: user, topic: topic, count: 0, timer: nil},
36 %{idle_timeout: @timeout}}
37 else
38 {:error, :bad_topic} ->
39 Logger.debug("#{__MODULE__} bad topic #{inspect(req)}")
40 req = :cowboy_req.reply(404, req)
41 {:ok, req, state}
42
43 {:error, :unauthorized} ->
44 Logger.debug("#{__MODULE__} authentication error: #{inspect(req)}")
45 req = :cowboy_req.reply(401, req)
46 {:ok, req, state}
47 end
48 end
49
50 def websocket_init(state) do
51 Logger.debug(
52 "#{__MODULE__} accepted websocket connection for user #{
53 (state.user || %{id: "anonymous"}).id
54 }, topic #{state.topic}"
55 )
56
57 Streamer.add_socket(state.topic, state.user)
58 {:ok, %{state | timer: timer()}}
59 end
60
61 # Client's Pong frame.
62 def websocket_handle(:pong, state) do
63 if state.timer, do: Process.cancel_timer(state.timer)
64 {:ok, %{state | timer: timer()}}
65 end
66
67 # We only receive pings for now
68 def websocket_handle(:ping, state), do: {:ok, state}
69
70 def websocket_handle(frame, state) do
71 Logger.error("#{__MODULE__} received frame: #{inspect(frame)}")
72 {:ok, state}
73 end
74
75 def websocket_info({:render_with_user, view, template, item}, state) do
76 user = %User{} = User.get_cached_by_ap_id(state.user.ap_id)
77
78 unless Streamer.filtered_by_user?(user, item) do
79 websocket_info({:text, view.render(template, item, user)}, %{state | user: user})
80 else
81 {:ok, state}
82 end
83 end
84
85 def websocket_info({:text, message}, state) do
86 # If the websocket processed X messages, force an hibernate/GC.
87 # We don't hibernate at every message to balance CPU usage/latency with RAM usage.
88 if state.count > @hibernate_every do
89 {:reply, {:text, message}, %{state | count: 0}, :hibernate}
90 else
91 {:reply, {:text, message}, %{state | count: state.count + 1}}
92 end
93 end
94
95 # Ping tick. We don't re-queue a timer there, it is instead queued when :pong is received.
96 # As we hibernate there, reset the count to 0.
97 # If the client misses :pong, Cowboy will automatically timeout the connection after
98 # `@idle_timeout`.
99 def websocket_info(:tick, state) do
100 {:reply, :ping, %{state | timer: nil, count: 0}, :hibernate}
101 end
102
103 # State can be `[]` only in case we terminate before switching to websocket,
104 # we already log errors for these cases in `init/1`, so just do nothing here
105 def terminate(_reason, _req, []), do: :ok
106
107 def terminate(reason, _req, state) do
108 Logger.debug(
109 "#{__MODULE__} terminating websocket connection for user #{
110 (state.user || %{id: "anonymous"}).id
111 }, topic #{state.topic || "?"}: #{inspect(reason)}"
112 )
113
114 Streamer.remove_socket(state.topic)
115 :ok
116 end
117
118 # Public streams without authentication.
119 defp authenticate_request(nil, nil) do
120 {:ok, nil, nil}
121 end
122
123 # Authenticated streams.
124 defp authenticate_request(access_token, sec_websocket) do
125 token = access_token || sec_websocket
126
127 with true <- is_bitstring(token),
128 oauth_token = %Token{user_id: user_id} <- Repo.get_by(Token, token: token),
129 user = %User{} <- User.get_cached_by_id(user_id) do
130 {:ok, user, oauth_token}
131 else
132 _ -> {:error, :unauthorized}
133 end
134 end
135
136 defp timer do
137 Process.send_after(self(), :tick, @tick)
138 end
139 end