summaryrefslogtreecommitdiff
path: root/lib/lsg_irc/seen_plugin.ex
blob: f1a5473ec9fcd42b76f9f2932f66a6f521db5ce7 (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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
defmodule LSG.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, "message", regopts)
    dets_filename = (LSG.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