API compatibility with fedibird, frontend config (#163)
[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,
36 %{
37 user: user,
38 topic: topic,
39 count: 0,
40 timer: nil,
41 subscriptions: [],
42 oauth_token: oauth_token
43 }, %{idle_timeout: @timeout}}
44 else
45 {:error, :bad_topic} ->
46 Logger.debug("#{__MODULE__} bad topic #{inspect(req)}")
47 req = :cowboy_req.reply(404, req)
48 {:ok, req, state}
49
50 {:error, :unauthorized} ->
51 Logger.debug("#{__MODULE__} authentication error: #{inspect(req)}")
52 req = :cowboy_req.reply(401, req)
53 {:ok, req, state}
54 end
55 end
56
57 def websocket_init(state) do
58 Logger.debug(
59 "#{__MODULE__} accepted websocket connection for user #{(state.user || %{id: "anonymous"}).id}, topic #{state.topic}"
60 )
61
62 Streamer.add_socket(state.topic, state.user)
63 {:ok, %{state | timer: timer()}}
64 end
65
66 # Client's Pong frame.
67 def websocket_handle(:pong, state) do
68 if state.timer, do: Process.cancel_timer(state.timer)
69 {:ok, %{state | timer: timer()}}
70 end
71
72 # We only receive pings for now
73 def websocket_handle(:ping, state), do: {:ok, state}
74
75 def websocket_handle({:text, ping}, state) when ping in ~w[ping PING] do
76 if state.timer, do: Process.cancel_timer(state.timer)
77 {:reply, {:text, "pong"}, %{state | timer: timer()}}
78 end
79
80 def websocket_handle({:text, text}, state) do
81 with {:ok, json} <- Jason.decode(text) do
82 websocket_handle({:json, json}, state)
83 else
84 _ ->
85 Logger.error("#{__MODULE__} received text frame: #{text}")
86 {:ok, state}
87 end
88 end
89
90 def websocket_handle(
91 {:json, %{"type" => "subscribe", "stream" => stream_name}},
92 %{user: user, oauth_token: token} = state
93 ) do
94 with {:ok, topic} <- Streamer.get_topic(stream_name, user, token, %{}) do
95 new_subscriptions =
96 [topic | Map.get(state, :subscriptions, [])]
97 |> Enum.uniq()
98
99 {:ok, _topic} = Streamer.add_socket(topic, user)
100
101 {:ok, Map.put(state, :subscriptions, new_subscriptions)}
102 else
103 _ ->
104 Logger.error("#{__MODULE__} received invalid topic: #{stream_name}")
105 {:ok, state}
106 end
107 end
108
109 def websocket_handle(frame, state) do
110 Logger.error("#{__MODULE__} received frame: #{inspect(frame)}")
111 {:ok, state}
112 end
113
114 def websocket_info({:render_with_user, view, template, item, topic}, state) do
115 user = %User{} = User.get_cached_by_ap_id(state.user.ap_id)
116
117 unless Streamer.filtered_by_user?(user, item) do
118 websocket_info({:text, view.render(template, item, user, topic)}, %{state | user: user})
119 else
120 {:ok, state}
121 end
122 end
123
124 def websocket_info({:text, message}, state) do
125 # If the websocket processed X messages, force an hibernate/GC.
126 # We don't hibernate at every message to balance CPU usage/latency with RAM usage.
127 if state.count > @hibernate_every do
128 {:reply, {:text, message}, %{state | count: 0}, :hibernate}
129 else
130 {:reply, {:text, message}, %{state | count: state.count + 1}}
131 end
132 end
133
134 # Ping tick. We don't re-queue a timer there, it is instead queued when :pong is received.
135 # As we hibernate there, reset the count to 0.
136 # If the client misses :pong, Cowboy will automatically timeout the connection after
137 # `@idle_timeout`.
138 def websocket_info(:tick, state) do
139 {:reply, :ping, %{state | timer: nil, count: 0}, :hibernate}
140 end
141
142 # State can be `[]` only in case we terminate before switching to websocket,
143 # we already log errors for these cases in `init/1`, so just do nothing here
144 def terminate(_reason, _req, []), do: :ok
145
146 def terminate(reason, _req, state) do
147 Logger.debug(
148 "#{__MODULE__} terminating websocket connection for user #{(state.user || %{id: "anonymous"}).id}, topic #{state.topic || "?"}: #{inspect(reason)}"
149 )
150
151 Streamer.remove_socket(state.topic)
152 :ok
153 end
154
155 # Public streams without authentication.
156 defp authenticate_request(nil, nil) do
157 {:ok, nil, nil}
158 end
159
160 # Authenticated streams.
161 defp authenticate_request(access_token, sec_websocket) do
162 token = access_token || sec_websocket
163
164 with true <- is_bitstring(token),
165 oauth_token = %Token{user_id: user_id} <- Repo.get_by(Token, token: token),
166 user = %User{} <- User.get_cached_by_id(user_id) do
167 {:ok, user, oauth_token}
168 else
169 _ -> {:error, :unauthorized}
170 end
171 end
172
173 defp timer do
174 Process.send_after(self(), :tick, @tick)
175 end
176 end