summaryrefslogblamecommitdiff
path: root/lib/nola_plugins/buffer_plugin.ex
blob: eece34e8436ecc27c98706675d5a75fb56c1ef52 (plain) (tree)
1
                                  































                                                                                             

                                               








                                      
defmodule Nola.IRC.BufferPlugin do
  @table __MODULE__.ETS
  def irc_doc, do: nil

  def table(), do: @table

  def select_buffer(network, channel, limit \\ 50) do
    import Ex2ms
    spec = fun do {{n, c, _}, m} when n == ^network and (c == ^channel or is_nil(c)) -> m end
    :ets.select(@table, spec, limit)
  end

  def start_link() do
    GenServer.start_link(__MODULE__, [], name: __MODULE__)
  end

  def init(_) do
    for e <- ~w(messages triggers events outputs) do
      {:ok, _} = Registry.register(IRC.PubSub, e, plugin: __MODULE__)
    end
    {:ok, :ets.new(@table, [:named_table, :ordered_set, :protected])}
  end

  def handle_info({:irc, :trigger, _, message}, ets), do: handle_message(message, ets)
  def handle_info({:irc, :text, message}, ets), do: handle_message(message, ets)
  def handle_info({:irc, :event, event}, ets), do: handle_message(event, ets)

  defp handle_message(message = %{network: network}, ets) do
    key = {network, Map.get(message, :channel), ts(message.at)}
    :ets.insert(ets, {key, message})
    {:noreply, ets}
  end

  defp ts(nil), do: ts(NaiveDateTime.utc_now())

  defp ts(naive = %NaiveDateTime{}) do
    ts = naive
    |> DateTime.from_naive!("Etc/UTC")
    |> DateTime.to_unix()

    -ts
  end

end