summaryrefslogtreecommitdiff
path: root/lib/nola_plugins/buffer_plugin.ex
diff options
context:
space:
mode:
authorJordan Bracco <href@random.sh>2022-12-20 00:21:54 +0000
committerJordan Bracco <href@random.sh>2022-12-20 19:29:41 +0100
commit2d83df8b32bff7f0028923bb5b64dc0b55f20d03 (patch)
tree1207e67b5b15f540963db05e7be89f3ca950e724 /lib/nola_plugins/buffer_plugin.ex
parentNola rename, the end. pt 6. Refs T77. (diff)
Nola rename: The Big Move, Refs T77
Diffstat (limited to 'lib/nola_plugins/buffer_plugin.ex')
-rw-r--r--lib/nola_plugins/buffer_plugin.ex44
1 files changed, 44 insertions, 0 deletions
diff --git a/lib/nola_plugins/buffer_plugin.ex b/lib/nola_plugins/buffer_plugin.ex
new file mode 100644
index 0000000..eece34e
--- /dev/null
+++ b/lib/nola_plugins/buffer_plugin.ex
@@ -0,0 +1,44 @@
+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