summaryrefslogtreecommitdiff
path: root/lib/lsg_irc/buffer_plugin.ex
blob: d278151be5bd0a6a2336b916f31506f55a1e1f54 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
defmodule LSG.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