defmodule Nola.IRC.SeenPlugin do
@moduledoc """
# seen
* **!seen `<nick>`**
"""
def irc_doc, do: @moduledoc
def start_link() do
GenServer.start_link(__MODULE__, [], name: __MODULE__)
end
def init([]) do
regopts = [plugin: __MODULE__]
{:ok, _} = Registry.register(IRC.PubSub, "triggers", regopts)
{:ok, _} = Registry.register(IRC.PubSub, "messages", regopts)
dets_filename = (Nola.data_path() <> "/seen.dets") |> String.to_charlist()
{:ok, dets} = :dets.open_file(dets_filename, [])
{:ok, %{dets: dets}}
end
def handle_info({:irc, :trigger, "seen", m = %IRC.Message{trigger: %IRC.Trigger{type: :bang, args: [nick]}}}, state) do
witness(m, state)
m.replyfun.(last_seen(m.channel, nick, state))
{:noreply, state}
end
def handle_info({:irc, :trigger, _, m}, state) do
witness(m, state)
{:noreply, state}
end
def handle_info({:irc, :text, m}, state) do
witness(m, state)
{:noreply, state}
end
defp witness(%IRC.Message{channel: channel, text: text, sender: %{nick: nick}}, %{dets: dets}) do
:dets.insert(dets, {{channel, nick}, DateTime.utc_now(), text})
:ok
end
defp last_seen(channel, nick, %{dets: dets}) do
case :dets.lookup(dets, {channel, nick}) do
[{_, date, text}] ->
diff = round(DateTime.diff(DateTime.utc_now(), date)/60)
cond do
diff >= 30 ->
duration = Timex.Duration.from_minutes(diff)
format = Timex.Format.Duration.Formatter.lformat(duration, "fr", :humanized)
"#{nick} a parlé pour la dernière fois il y a #{format}: “#{text}”"
true -> "#{nick} est là..."
end
[] ->
"je ne connais pas de #{nick}"
end
end
end