summaryrefslogtreecommitdiff
path: root/lib/lsg_irc/user_track_handler.ex
blob: d167af5e11dca967822e27d939d4e6f6ce2e8eaf (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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
defmodule LSG.IRC.UserTrackHandler do
  @moduledoc """
  # User Track Handler

  This handlers keeps track of users presence and privileges.

  Planned API:

      UserTrackHandler.operator?(%ExIRC.Sender{nick: "href", …}, "#channel") :: boolean

  """

  def irc_doc, do: nil

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

  defstruct client: nil, ets: nil

  def init([client]) do
    ExIRC.Client.add_handler client, self
    {:ok, %__MODULE__{client: client}}
  end

  def handle_info({:joined, channel}, state) do
    ExIRC.Client.who(state.client, channel)
    {:noreply, state}
  end

  def handle_info({:who, channel, whos}, state) do
    Enum.map(whos, fn(who = %ExIRC.Who{nick: nick, operator?: operator}) ->
      priv = if operator, do: [:operator], else: []
      LSG.IRC.UserTrack.joined(channel, who, priv)
    end)
    {:noreply, state}
  end

  def handle_info({:quit, _reason, sender}, state) do
    LSG.IRC.UserTrack.quitted(sender)
    {:noreply, state}
  end

  def handle_info({:joined, channel, sender}, state) do
    LSG.IRC.UserTrack.joined(channel, sender, [])
    {:noreply, state}
  end

  def handle_info({:kicked, nick, _by, channel, _reason}, state) do
    parted(channel, nick)
    {:noreply, state}
  end

  def handle_info({:parted, channel, %ExIRC.SenderInfo{nick: nick}}, state) do
    parted(channel, nick)
    {:noreply, state}
  end

  def handle_info({:mode, [channel, mode, nick]}, state) do
    mode(channel, nick, mode)
    {:noreply, state}
  end

  def handle_info({:nick_changed, old_nick, new_nick}, state) do
    rename(old_nick, new_nick)
    {:noreply, state}
  end

  def handle_info(msg, state) do
    {:noreply, state}
  end

  defp parted(channel, nick) do
    LSG.IRC.UserTrack.parted(channel, nick)
    :ok
  end

  defp mode(channel, nick, "+o") do
    LSG.IRC.UserTrack.change_privileges(channel, nick, {[:operator], []})
    :ok
  end

  defp mode(channel, nick, "-o") do
    LSG.IRC.UserTrack.change_privileges(channel, nick, {[], [:operator]})
    :ok
  end

  defp rename(old, new) do
    LSG.IRC.UserTrack.renamed(old, new)
    :ok
  end

end