2017-11-11 13:59:25 +00:00
|
|
|
defmodule Pleroma.Web.MastodonAPI.MastodonSocket do
|
|
|
|
use Phoenix.Socket
|
|
|
|
|
2017-11-16 12:48:58 +00:00
|
|
|
alias Pleroma.Web.OAuth.Token
|
|
|
|
alias Pleroma.{User, Repo}
|
|
|
|
|
2018-12-10 06:39:57 +00:00
|
|
|
@spec connect(params :: map(), Phoenix.Socket.t()) :: {:ok, Phoenix.Socket.t()} | :error
|
2018-11-24 05:43:03 +00:00
|
|
|
def connect(%{"access_token" => token} = params, socket) do
|
|
|
|
with %Token{user_id: user_id} <- Repo.get_by(Token, token: token),
|
2017-11-16 12:48:58 +00:00
|
|
|
%User{} = user <- Repo.get(User, user_id),
|
2018-06-17 13:01:27 +00:00
|
|
|
stream
|
|
|
|
when stream in [
|
|
|
|
"public",
|
|
|
|
"public:local",
|
|
|
|
"public:media",
|
|
|
|
"public:local:media",
|
|
|
|
"user",
|
|
|
|
"direct",
|
2018-08-07 20:45:40 +00:00
|
|
|
"list",
|
|
|
|
"hashtag"
|
2018-06-17 13:01:27 +00:00
|
|
|
] <- params["stream"] do
|
2018-11-11 03:33:14 +00:00
|
|
|
topic =
|
|
|
|
case stream do
|
|
|
|
"hashtag" -> "hashtag:#{params["tag"]}"
|
|
|
|
"list" -> "list:#{params["list"]}"
|
|
|
|
_ -> stream
|
|
|
|
end
|
2018-05-30 13:33:37 +00:00
|
|
|
|
2018-03-30 13:01:53 +00:00
|
|
|
socket =
|
|
|
|
socket
|
2018-05-30 13:33:37 +00:00
|
|
|
|> assign(:topic, topic)
|
2018-03-30 13:01:53 +00:00
|
|
|
|> assign(:user, user)
|
|
|
|
|
2018-11-11 03:33:14 +00:00
|
|
|
Pleroma.Web.Streamer.add_socket(topic, socket)
|
2017-11-11 19:00:11 +00:00
|
|
|
{:ok, socket}
|
|
|
|
else
|
2017-11-16 12:48:58 +00:00
|
|
|
_e -> :error
|
2017-11-11 19:00:11 +00:00
|
|
|
end
|
2017-11-11 13:59:25 +00:00
|
|
|
end
|
|
|
|
|
2018-11-24 05:13:36 +00:00
|
|
|
def connect(%{"stream" => stream} = params, socket)
|
|
|
|
when stream in ["public", "public:local", "hashtag"] do
|
|
|
|
topic =
|
|
|
|
case stream do
|
|
|
|
"hashtag" -> "hashtag:#{params["tag"]}"
|
|
|
|
_ -> stream
|
|
|
|
end
|
|
|
|
|
2018-12-10 06:39:57 +00:00
|
|
|
socket =
|
|
|
|
socket
|
|
|
|
|> assign(:topic, topic)
|
|
|
|
|
|
|
|
Pleroma.Web.Streamer.add_socket(topic, socket)
|
|
|
|
{:ok, socket}
|
2018-11-24 05:13:36 +00:00
|
|
|
end
|
|
|
|
|
2018-12-10 06:39:57 +00:00
|
|
|
def connect(_params, _socket), do: :error
|
|
|
|
|
2017-11-19 01:22:07 +00:00
|
|
|
def id(_), do: nil
|
2017-11-11 13:59:25 +00:00
|
|
|
|
2017-11-19 01:22:07 +00:00
|
|
|
def handle(:text, message, _state) do
|
2018-03-30 13:01:53 +00:00
|
|
|
# | :ok
|
|
|
|
# | state
|
|
|
|
# | {:text, message}
|
|
|
|
# | {:text, message, state}
|
|
|
|
# | {:close, "Goodbye!"}
|
2017-11-11 13:59:25 +00:00
|
|
|
{:text, message}
|
|
|
|
end
|
|
|
|
|
2017-11-19 01:22:07 +00:00
|
|
|
def handle(:closed, _, %{socket: socket}) do
|
2017-11-11 19:00:11 +00:00
|
|
|
topic = socket.assigns[:topic]
|
|
|
|
Pleroma.Web.Streamer.remove_socket(topic, socket)
|
2017-11-11 13:59:25 +00:00
|
|
|
end
|
|
|
|
end
|