1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2019 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
5 defmodule Pleroma.Web.MastodonAPI.WebsocketHandler do
10 alias Pleroma.Web.OAuth.Token
11 alias Pleroma.Web.Streamer
13 @behaviour :cowboy_websocket
26 @anonymous_streams ["public", "public:local", "hashtag"]
28 # Handled by periodic keepalive in Pleroma.Web.Streamer.Ping.
31 def init(%{qs: qs} = req, state) do
32 with params <- :cow_qs.parse_qs(qs),
33 sec_websocket <- :cowboy_req.header("sec-websocket-protocol", req, nil),
34 access_token <- List.keyfind(params, "access_token", 0),
35 {_, stream} <- List.keyfind(params, "stream", 0),
36 {:ok, user} <- allow_request(stream, [access_token, sec_websocket]),
37 topic when is_binary(topic) <- expand_topic(stream, params) do
38 {:cowboy_websocket, req, %{user: user, topic: topic}, %{idle_timeout: @timeout}}
41 Logger.debug("#{__MODULE__} denied connection: #{inspect(code)} - #{inspect(req)}")
42 {:ok, req} = :cowboy_req.reply(code, req)
46 Logger.debug("#{__MODULE__} denied connection: #{inspect(error)} - #{inspect(req)}")
47 {:ok, req} = :cowboy_req.reply(400, req)
52 def websocket_init(state) do
53 send(self(), :subscribe)
57 # We never receive messages.
58 def websocket_handle(_frame, state) do
62 def websocket_info(:subscribe, state) do
64 "#{__MODULE__} accepted websocket connection for user #{
65 (state.user || %{id: "anonymous"}).id
66 }, topic #{state.topic}"
69 Streamer.add_socket(state.topic, streamer_socket(state))
73 def websocket_info({:text, message}, state) do
74 {:reply, {:text, message}, state}
77 def terminate(reason, _req, state) do
79 "#{__MODULE__} terminating websocket connection for user #{
80 (state.user || %{id: "anonymous"}).id
81 }, topic #{state.topic || "?"}: #{inspect(reason)}"
84 Streamer.remove_socket(state.topic, streamer_socket(state))
88 # Public streams without authentication.
89 defp allow_request(stream, [nil, nil]) when stream in @anonymous_streams do
93 # Authenticated streams.
94 defp allow_request(stream, [access_token, sec_websocket]) when stream in @streams do
96 with {"access_token", token} <- access_token do
102 with true <- is_bitstring(token),
103 %Token{user_id: user_id} <- Repo.get_by(Token, token: token),
104 user = %User{} <- User.get_cached_by_id(user_id) do
112 defp allow_request(stream, _) when stream in @streams, do: {:error, 403}
114 # No matching stream.
115 defp allow_request(_, _), do: {:error, 404}
117 defp expand_topic("hashtag", params) do
118 case List.keyfind(params, "tag", 0) do
119 {_, tag} -> "hashtag:#{tag}"
124 defp expand_topic("list", params) do
125 case List.keyfind(params, "list", 0) do
126 {_, list} -> "list:#{list}"
131 defp expand_topic(topic, _), do: topic
133 defp streamer_socket(state) do
134 %{transport_pid: self(), assigns: state}