summaryrefslogtreecommitdiff
path: root/lib/lsg_web/controllers/alcoolog_controller.ex
blob: 9d5d9d97fad7df91f9b1126ed7adbd3e8f357fa7 (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
defmodule LSGWeb.AlcoologController do
  use LSGWeb, :controller
  require Logger

  def index(conn, %{"channel" => channel}) do
    case LSG.Token.lookup(channel) do
      {:ok, obj} -> index(conn, obj)
      err ->
        Logger.debug("AlcoologControler: token #{inspect err} invalid")
        conn
        |> put_status(404)
        |> text("Page not found")
    end
  end

  def index(conn, {:alcoolog, :index, channel}) do
    aday = 7*((24 * 60)*60)
    now = DateTime.utc_now()
    before = now
             |> DateTime.add(-aday, :second)
    |> DateTime.to_unix(:millisecond)
    #match = :ets.fun2ms(fn(obj = {{^nick, date}, _, _, _, _}) when date > before -> obj end)
    match = [
  {{{:_, :"$1"}, :_, :_, :_, :_},
   [
     {:>, :"$1", {:const, before}},
   ], [:"$_"]}
    ]

    nicks_in_channel = IRC.UserTrack.channel(channel)
                       |> Enum.map(fn({_, nick, _, _, _, _, _}) -> String.downcase(nick) end)
  # tuple ets:  {{nick, date}, volumes, current, nom, commentaire}
    drinks = :ets.select(LSG.IRC.AlcoologPlugin.ETS, match)
    #|> Enum.filter(fn({{nick, _}, _, _, _, _}) -> Enum.member?(nicks_in_channel, nick) end)
             |> Enum.sort_by(fn({{_, ts}, _, _, _, _}) -> ts end, &>/2)

    stats = LSG.IRC.AlcoologPlugin.get_channel_statistics(channel)

    top = Enum.reduce(drinks, %{}, fn({{nick, _}, vol, _, _, _}, acc) ->
      all = Map.get(acc, nick, 0)
      Map.put(acc, nick, all + vol)
    end)
    |> Enum.sort_by(fn({_nick, count}) -> count end, &>/2)
    # {date, single_peak}
    render(conn, "index.html", channel: channel, drinks: drinks, top: top, stats: stats)
  end

end