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
25 @anonymous_streams ["public", "public:local", "hashtag"]
27 # Handled by periodic keepalive in Pleroma.Web.Streamer.
30 def init(%{qs: qs} = req, state) do
31 with params <- :cow_qs.parse_qs(qs),
32 sec_websocket <- :cowboy_req.header("sec-websocket-protocol", req, nil),
33 access_token <- List.keyfind(params, "access_token", 0),
34 {_, stream} <- List.keyfind(params, "stream", 0),
35 {:ok, user} <- allow_request(stream, [access_token, sec_websocket]),
36 topic when is_binary(topic) <- expand_topic(stream, params) do
37 {:cowboy_websocket, req, %{user: user, topic: topic}, %{idle_timeout: @timeout}}
40 Logger.debug("#{__MODULE__} denied connection: #{inspect(code)} - #{inspect(req)}")
41 {:ok, req} = :cowboy_req.reply(code, req)
45 Logger.debug("#{__MODULE__} denied connection: #{inspect(error)} - #{inspect(req)}")
46 {:ok, req} = :cowboy_req.reply(400, req)
51 def websocket_init(state) do
52 send(self(), :subscribe)
56 # We never receive messages.
57 def websocket_handle(_frame, state) do
61 def websocket_info(:subscribe, state) do
63 "#{__MODULE__} accepted websocket connection for user #{
64 (state.user || %{id: "anonymous"}).id
65 }, topic #{state.topic}"
68 Pleroma.Web.Streamer.add_socket(state.topic, streamer_socket(state))
72 def websocket_info({:text, message}, state) do
73 {:reply, {:text, message}, state}
76 def terminate(reason, _req, state) do
78 "#{__MODULE__} terminating websocket connection for user #{
79 (state.user || %{id: "anonymous"}).id
80 }, topic #{state.topic || "?"}: #{inspect(reason)}"
83 Pleroma.Web.Streamer.remove_socket(state.topic, streamer_socket(state))
87 # Public streams without authentication.
88 defp allow_request(stream, [nil, nil]) when stream in @anonymous_streams do
92 # Authenticated streams.
93 defp allow_request(stream, [access_token, sec_websocket]) when stream in @streams do
95 with {"access_token", token} <- access_token do
101 with true <- is_bitstring(token),
102 %Token{user_id: user_id} <- Repo.get_by(Token, token: token),
103 user = %User{} <- User.get_cached_by_id(user_id) do
111 defp allow_request(stream, _) when stream in @streams, do: {:error, 403}
113 # No matching stream.
114 defp allow_request(_, _), do: {:error, 404}
116 defp expand_topic("hashtag", params) do
117 case List.keyfind(params, "tag", 0) do
118 {_, tag} -> "hashtag:#{tag}"
123 defp expand_topic("list", params) do
124 case List.keyfind(params, "list", 0) do
125 {_, list} -> "list:#{list}"
130 defp expand_topic(topic, _), do: topic
132 defp streamer_socket(state) do
133 %{transport_pid: self(), assigns: state}