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
12 @behaviour :cowboy_websocket
24 @anonymous_streams ["public", "public:local", "hashtag"]
26 # Handled by periodic keepalive in Pleroma.Web.Streamer.
29 def init(%{qs: qs} = req, state) do
30 with params <- :cow_qs.parse_qs(qs),
31 access_token <- List.keyfind(params, "access_token", 0),
32 {_, stream} <- List.keyfind(params, "stream", 0),
33 {:ok, user} <- allow_request(stream, access_token),
34 topic when is_binary(topic) <- expand_topic(stream, params) do
35 {:cowboy_websocket, req, %{user: user, topic: topic}, %{idle_timeout: @timeout}}
38 Logger.debug("#{__MODULE__} denied connection: #{inspect(code)} - #{inspect(req)}")
39 {:ok, req} = :cowboy_req.reply(code, req)
43 Logger.debug("#{__MODULE__} denied connection: #{inspect(error)} - #{inspect(req)}")
44 {:ok, req} = :cowboy_req.reply(400, req)
49 def websocket_init(state) do
50 send(self(), :subscribe)
54 # We never receive messages.
55 def websocket_handle(_frame, state) do
59 def websocket_info(:subscribe, state) do
61 "#{__MODULE__} accepted websocket connection for user #{
62 (state.user || %{id: "anonymous"}).id
63 }, topic #{state.topic}"
66 Pleroma.Web.Streamer.add_socket(state.topic, streamer_socket(state))
70 def websocket_info({:text, message}, state) do
71 {:reply, {:text, message}, state}
74 def terminate(reason, _req, state) do
76 "#{__MODULE__} terminating websocket connection for user #{
77 (state.user || %{id: "anonymous"}).id
78 }, topic #{state.topic || "?"}: #{inspect(reason)}"
81 Pleroma.Web.Streamer.remove_socket(state.topic, streamer_socket(state))
85 # Public streams without authentication.
86 defp allow_request(stream, nil) when stream in @anonymous_streams do
90 # Authenticated streams.
91 defp allow_request(stream, {"access_token", access_token}) when stream in @streams do
92 with %Token{user_id: user_id} <- Repo.get_by(Token, token: access_token),
93 user = %User{} <- User.get_cached_by_id(user_id) do
101 defp allow_request(stream, _) when stream in @streams, do: {:error, 403}
103 # No matching stream.
104 defp allow_request(_, _), do: {:error, 404}
106 defp expand_topic("hashtag", params) do
107 case List.keyfind(params, "tag", 0) do
108 {_, tag} -> "hashtag:#{tag}"
113 defp expand_topic("list", params) do
114 case List.keyfind(params, "list", 0) do
115 {_, list} -> "list:#{list}"
120 defp expand_topic(topic, _), do: topic
122 defp streamer_socket(state) do
123 %{transport_pid: self(), assigns: state}