2019-10-04 09:21:45 -06:00
|
|
|
# Pleroma: A lightweight social networking server
|
2020-03-03 15:44:49 -07:00
|
|
|
# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/>
|
2019-10-04 09:21:45 -06:00
|
|
|
# SPDX-License-Identifier: AGPL-3.0-only
|
|
|
|
|
2019-09-16 04:03:37 -06:00
|
|
|
defmodule Pleroma.Web.Streamer.State do
|
|
|
|
use GenServer
|
|
|
|
require Logger
|
|
|
|
|
|
|
|
alias Pleroma.Web.Streamer.StreamerSocket
|
|
|
|
|
2019-09-17 08:44:52 -06:00
|
|
|
@env Mix.env()
|
|
|
|
|
2019-09-16 04:03:37 -06:00
|
|
|
def start_link(_) do
|
|
|
|
GenServer.start_link(__MODULE__, %{sockets: %{}}, name: __MODULE__)
|
|
|
|
end
|
|
|
|
|
|
|
|
def add_socket(topic, socket) do
|
2019-09-17 08:44:52 -06:00
|
|
|
GenServer.call(__MODULE__, {:add, topic, socket})
|
2019-09-16 04:03:37 -06:00
|
|
|
end
|
|
|
|
|
|
|
|
def remove_socket(topic, socket) do
|
2019-09-17 08:44:52 -06:00
|
|
|
do_remove_socket(@env, topic, socket)
|
2019-09-16 04:03:37 -06:00
|
|
|
end
|
|
|
|
|
|
|
|
def get_sockets do
|
|
|
|
%{sockets: stream_sockets} = GenServer.call(__MODULE__, :get_state)
|
|
|
|
stream_sockets
|
|
|
|
end
|
|
|
|
|
|
|
|
def init(init_arg) do
|
|
|
|
{:ok, init_arg}
|
|
|
|
end
|
|
|
|
|
|
|
|
def handle_call(:get_state, _from, state) do
|
|
|
|
{:reply, state, state}
|
|
|
|
end
|
|
|
|
|
2019-09-17 08:44:52 -06:00
|
|
|
def handle_call({:add, topic, socket}, _from, %{sockets: sockets} = state) do
|
2019-09-16 04:03:37 -06:00
|
|
|
stream_socket = StreamerSocket.from_socket(socket)
|
|
|
|
|
|
|
|
sockets_for_topic =
|
|
|
|
sockets
|
2020-05-12 13:06:23 -06:00
|
|
|
|> Map.get(topic, [])
|
2019-09-16 04:03:37 -06:00
|
|
|
|> List.insert_at(0, stream_socket)
|
|
|
|
|> Enum.uniq()
|
|
|
|
|
2020-05-12 13:06:23 -06:00
|
|
|
state = put_in(state, [:sockets, topic], sockets_for_topic)
|
2019-09-16 04:03:37 -06:00
|
|
|
Logger.debug("Got new conn for #{topic}")
|
|
|
|
{:reply, state, state}
|
|
|
|
end
|
|
|
|
|
2019-09-17 08:44:52 -06:00
|
|
|
def handle_call({:remove, topic, socket}, _from, %{sockets: sockets} = state) do
|
2019-09-16 04:03:37 -06:00
|
|
|
stream_socket = StreamerSocket.from_socket(socket)
|
|
|
|
|
|
|
|
sockets_for_topic =
|
|
|
|
sockets
|
2020-05-12 13:06:23 -06:00
|
|
|
|> Map.get(topic, [])
|
2019-09-16 04:03:37 -06:00
|
|
|
|> List.delete(stream_socket)
|
|
|
|
|
2020-05-12 13:06:23 -06:00
|
|
|
state = Kernel.put_in(state, [:sockets, topic], sockets_for_topic)
|
2019-09-16 04:03:37 -06:00
|
|
|
{:reply, state, state}
|
|
|
|
end
|
|
|
|
|
2019-09-17 08:44:52 -06:00
|
|
|
defp do_remove_socket(:test, _, _) do
|
|
|
|
:ok
|
|
|
|
end
|
|
|
|
|
|
|
|
defp do_remove_socket(_env, topic, socket) do
|
|
|
|
GenServer.call(__MODULE__, {:remove, topic, socket})
|
|
|
|
end
|
2019-09-16 04:03:37 -06:00
|
|
|
end
|