mastodon_socket.ex 1.38 KB
Newer Older
lain's avatar
lain committed
1
2
3
defmodule Pleroma.Web.MastodonAPI.MastodonSocket do
  use Phoenix.Socket

Roger Braun's avatar
Roger Braun committed
4
5
6
  alias Pleroma.Web.OAuth.Token
  alias Pleroma.{User, Repo}

lain's avatar
lain committed
7
8
9
10
11
12
  transport(
    :streaming,
    Phoenix.Transports.WebSocket.Raw,
    # We never receive data.
    timeout: :infinity
  )
lain's avatar
lain committed
13
14

  def connect(params, socket) do
Roger Braun's avatar
Roger Braun committed
15
16
17
    with token when not is_nil(token) <- params["access_token"],
         %Token{user_id: user_id} <- Repo.get_by(Token, token: token),
         %User{} = user <- Repo.get(User, user_id),
18
19
20
21
22
23
24
25
26
27
         stream
         when stream in [
                "public",
                "public:local",
                "public:media",
                "public:local:media",
                "user",
                "direct",
                "list"
              ] <- params["stream"] do
eal's avatar
eal committed
28
29
      topic = if stream == "list", do: "list:#{params["list"]}", else: stream

lain's avatar
lain committed
30
31
      socket =
        socket
eal's avatar
eal committed
32
        |> assign(:topic, topic)
lain's avatar
lain committed
33
34
        |> assign(:user, user)

35
36
37
      Pleroma.Web.Streamer.add_socket(params["stream"], socket)
      {:ok, socket}
    else
Roger Braun's avatar
Roger Braun committed
38
      _e -> :error
39
    end
lain's avatar
lain committed
40
41
  end

Thog's avatar
Thog committed
42
  def id(_), do: nil
lain's avatar
lain committed
43

Thog's avatar
Thog committed
44
  def handle(:text, message, _state) do
lain's avatar
lain committed
45
46
47
48
49
    # | :ok
    # | state
    # | {:text, message}
    # | {:text, message, state}
    # | {:close, "Goodbye!"}
lain's avatar
lain committed
50
51
52
    {:text, message}
  end

Thog's avatar
Thog committed
53
  def handle(:closed, _, %{socket: socket}) do
54
55
    topic = socket.assigns[:topic]
    Pleroma.Web.Streamer.remove_socket(topic, socket)
lain's avatar
lain committed
56
57
  end
end