move to 2.5.5
[anni] / lib / pleroma / web / mastodon_api / websocket_handler.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 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        %{user: user, topic: topic, oauth_token: oauth_token, count: 0, timer: nil},
37        %{idle_timeout: @timeout}}
38     else
39       {:error, :bad_topic} ->
40         Logger.debug("#{__MODULE__} bad topic #{inspect(req)}")
41         req = :cowboy_req.reply(404, req)
42         {:ok, req, state}
43
44       {:error, :unauthorized} ->
45         Logger.debug("#{__MODULE__} authentication error: #{inspect(req)}")
46         req = :cowboy_req.reply(401, req)
47         {:ok, req, state}
48     end
49   end
50
51   def websocket_init(state) do
52     Logger.debug(
53       "#{__MODULE__} accepted websocket connection for user #{(state.user || %{id: "anonymous"}).id}, topic #{state.topic}"
54     )
55
56     Streamer.add_socket(state.topic, state.oauth_token)
57     {:ok, %{state | timer: timer()}}
58   end
59
60   # Client's Pong frame.
61   def websocket_handle(:pong, state) do
62     if state.timer, do: Process.cancel_timer(state.timer)
63     {:ok, %{state | timer: timer()}}
64   end
65
66   # We only receive pings for now
67   def websocket_handle(:ping, state), do: {:ok, state}
68
69   def websocket_handle(frame, state) do
70     Logger.error("#{__MODULE__} received frame: #{inspect(frame)}")
71     {:ok, state}
72   end
73
74   def websocket_info({:render_with_user, view, template, item}, state) do
75     user = %User{} = User.get_cached_by_ap_id(state.user.ap_id)
76
77     unless Streamer.filtered_by_user?(user, item) do
78       websocket_info({:text, view.render(template, item, user)}, %{state | user: user})
79     else
80       {:ok, state}
81     end
82   end
83
84   def websocket_info({:text, message}, state) do
85     # If the websocket processed X messages, force an hibernate/GC.
86     # We don't hibernate at every message to balance CPU usage/latency with RAM usage.
87     if state.count > @hibernate_every do
88       {:reply, {:text, message}, %{state | count: 0}, :hibernate}
89     else
90       {:reply, {:text, message}, %{state | count: state.count + 1}}
91     end
92   end
93
94   # Ping tick. We don't re-queue a timer there, it is instead queued when :pong is received.
95   # As we hibernate there, reset the count to 0.
96   # If the client misses :pong, Cowboy will automatically timeout the connection after
97   # `@idle_timeout`.
98   def websocket_info(:tick, state) do
99     {:reply, :ping, %{state | timer: nil, count: 0}, :hibernate}
100   end
101
102   def websocket_info(:close, state) do
103     {:stop, state}
104   end
105
106   # State can be `[]` only in case we terminate before switching to websocket,
107   # we already log errors for these cases in `init/1`, so just do nothing here
108   def terminate(_reason, _req, []), do: :ok
109
110   def terminate(reason, _req, state) do
111     Logger.debug(
112       "#{__MODULE__} terminating websocket connection for user #{(state.user || %{id: "anonymous"}).id}, topic #{state.topic || "?"}: #{inspect(reason)}"
113     )
114
115     Streamer.remove_socket(state.topic)
116     :ok
117   end
118
119   # Public streams without authentication.
120   defp authenticate_request(nil, nil) do
121     {:ok, nil, nil}
122   end
123
124   # Authenticated streams.
125   defp authenticate_request(access_token, sec_websocket) do
126     token = access_token || sec_websocket
127
128     with true <- is_bitstring(token),
129          oauth_token = %Token{user_id: user_id} <- Repo.get_by(Token, token: token),
130          user = %User{} <- User.get_cached_by_id(user_id) do
131       {:ok, user, oauth_token}
132     else
133       _ -> {:error, :unauthorized}
134     end
135   end
136
137   defp timer do
138     Process.send_after(self(), :tick, @tick)
139   end
140 end