summaryrefslogtreecommitdiff
path: root/lib/plugins/quatre_cent_vingt.ex
blob: 59b2dea0f966d6e7ee13967b5b1ec8274bcde007 (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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
defmodule Nola.Plugins.QuatreCentVingt do
  require Logger

  @moduledoc """
  # 420

  * **!420**: recorde un nouveau 420.
  * **!420*x**: recorde un nouveau 420*x (*2 = 840, ...) (à vous de faire la multiplication).
  * **!420 pseudo**: stats du pseudo.
  """

  @achievements %{
    1    => ["[le premier… il faut bien commencer un jour]"],
    10   => ["T'en es seulement à 10 ? ╭∩╮(Ο_Ο)╭∩╮"],
    42   => ["Bravo, et est-ce que autant de pétards t'on aidés à trouver la Réponse ? ٩(- ̮̮̃-̃)۶ [42]"],
    100  => ["°º¤ø,¸¸,ø¤º°`°º¤ø,¸,ø¤°º¤ø,¸¸,ø¤º°`°º¤ø,¸ 100 °º¤ø,¸¸,ø¤º°`°º¤ø,¸,ø¤°º¤ø,¸¸,ø¤º°`°º¤ø,¸"],
    115  => [" ۜ\(סּںסּَ` )/ۜ 115!!"]
  }

  @emojis [
    "\\o/",
    "~o~",
    "~~o∞~~",
    "*\\o/*",
    "**\\o/**",
    "*ô*",
  ]

  @coeffs Range.new(1, 100)

  def irc_doc, do: @moduledoc

  def start_link, do: GenServer.start_link(__MODULE__, [], name: __MODULE__)

  def init(_) do
    for coeff <- @coeffs do
      {:ok, _} = Registry.register(Nola.PubSub, "trigger:#{420*coeff}", [plugin: __MODULE__])
    end
    {:ok, _} = Registry.register(Nola.PubSub, "account", [plugin: __MODULE__])
    dets_filename = (Nola.data_path() <> "/420.dets") |> String.to_charlist
    {:ok, dets} = :dets.open_file(dets_filename, [{:type,:bag},{:repair,:force}])
    {:ok, dets}
    :ignore
  end

  for coeff <- @coeffs do
    qvc = to_string(420 * coeff)
    def handle_info({:irc, :trigger, unquote(qvc), m = %IRC.Message{trigger: %IRC.Trigger{args: [], type: :bang}}}, dets) do
      {count, last} = get_statistics_for_nick(dets, m.account.id)
      count = count + unquote(coeff)
      text = achievement_text(count)
      now = DateTime.to_unix(DateTime.utc_now())-1 # this is ugly
      for i <- Range.new(1, unquote(coeff)) do
        :ok = :dets.insert(dets, {m.account.id, now+i})
      end
      last_s = if last do
        last_s = format_relative_timestamp(last)
        " (le dernier était #{last_s})"
      else
        ""
      end
      m.replyfun.("#{m.sender.nick} 420 +#{unquote(coeff)} #{text}#{last_s}")
      {:noreply, dets}
    end
  end

  def handle_info({:irc, :trigger, "420", m = %IRC.Message{trigger: %IRC.Trigger{args: [nick], type: :bang}}}, dets) do
    account = IRC.Account.find_by_nick(m.network, nick)
    if account do
      text = case get_statistics_for_nick(dets, m.account.id) do
        {0, _} -> "#{nick} n'a jamais !420 ... honte à lui."
        {count, last} ->
          last_s = format_relative_timestamp(last)
          "#{nick} 420: total #{count}, le dernier #{last_s}"
      end
      m.replyfun.(text)
    else
      m.replyfun.("je connais pas de #{nick}")
    end
    {:noreply, dets}
  end

  # Account
  def handle_info({:account_change, old_id, new_id}, dets) do
    spec = [{{:"$1", :_}, [{:==, :"$1", {:const, old_id}}], [:"$_"]}]
    Util.ets_mutate_select_each(:dets, dets, spec, fn(table, obj) ->
      rename_object_owner(table, obj, new_id)
    end)
    {:noreply, dets}
  end

  # Account: move from nick to account id
  def handle_info({:accounts, accounts}, dets) do
    for x={:account, _net, _chan, _nick, _account_id} <- accounts do
      handle_info(x, dets)
    end
    {:noreply, dets}
  end
  def handle_info({:account, _net, _chan, nick, account_id}, dets) do
    nick = String.downcase(nick)
    spec = [{{:"$1", :_}, [{:==, :"$1", {:const, nick}}], [:"$_"]}]
    Util.ets_mutate_select_each(:dets, dets, spec, fn(table, obj) ->
      Logger.debug("account:: merging #{nick} -> #{account_id}")
      rename_object_owner(table, obj, account_id)
    end)
    {:noreply, dets}
  end

  def handle_info(_, dets) do
    {:noreply, dets}
  end

  defp rename_object_owner(table, object = {_, at}, account_id) do
    :dets.delete_object(table, object)
    :dets.insert(table, {account_id, at})
  end


  defp format_relative_timestamp(timestamp) do
    alias Timex.Format.DateTime.Formatters
    alias Timex.Timezone
    date = timestamp
    |> DateTime.from_unix!
    |> Timezone.convert("Europe/Paris")

    {:ok, relative} = Formatters.Relative.relative_to(date, Timex.now("Europe/Paris"), "{relative}", "fr")
    {:ok, detail} = Formatters.Default.lformat(date, " ({h24}:{m})", "fr")

    relative <> detail
  end

  defp get_statistics_for_nick(dets, acct) do
    qvc = :dets.lookup(dets, acct) |> Enum.sort
    count = Enum.reduce(qvc, 0, fn(_, acc) -> acc + 1 end)
    {_, last} = List.last(qvc) || {nil, nil}
    {count, last}
  end

  @achievements_keys Map.keys(@achievements)
  defp achievement_text(count) when count in @achievements_keys do
    Enum.random(Map.get(@achievements, count))
  end

  defp achievement_text(count) do
    emoji = Enum.random(@emojis)
    "#{emoji} [#{count}]"
  end

end