summaryrefslogtreecommitdiff
path: root/lib/web/controllers/alcoolog_controller.ex
blob: 3c812c5300c75c57c7250d9dbf07360bc89e6776 (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
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
defmodule NolaWeb.AlcoologController do
  use NolaWeb, :controller
  require Logger

  plug NolaWeb.ContextPlug when action not in [:token]
  plug NolaWeb.ContextPlug, [restrict: :public] when action in [:token]

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

  def nick(conn = %{assigns: %{account: account}}, params = %{"network" => network, "nick" => nick}) do
    profile_account = IRC.Account.find_always_by_nick(network, nick, nick)
    days = String.to_integer(Map.get(params, "days", "180"))
    friend? = Enum.member?(IRC.Membership.friends(account), profile_account.id)
    if friend? do
      stats = Nola.Plugins.Alcoolog.get_full_statistics(profile_account.id)
      history = for {{nick, ts}, points, active, cl, deg, type, descr, meta} <- Nola.Plugins.Alcoolog.nick_history(profile_account) do
        %{
          at: ts |> DateTime.from_unix!(:millisecond),
          points: points,
          active: active,
          cl: cl,
          deg: deg,
          type: type,
          description: descr,
          meta: meta
        }
    end
      history = Enum.sort(history, &(DateTime.compare(&1.at, &2.at) != :lt))
                |> IO.inspect()
      conn
      |> assign(:title, "alcoolog #{nick}")
      |> render("user.html", network: network, profile: profile_account, days: days, nick: nick, history: history, stats: stats)
    else
      conn
      |> put_status(404)
      |> text("Page not found")
    end
  end

  def nick_stats_json(conn = %{assigns: %{account: account}}, params = %{"network" => network, "nick" => nick}) do
    profile_account = IRC.Account.find_always_by_nick(network, nick, nick)
    friend? = Enum.member?(IRC.Membership.friends(account), profile_account.id)
    if friend? do
      stats = Nola.Plugins.Alcoolog.get_full_statistics(profile_account.id)

      conn
      |> put_resp_content_type("application/json")
      |> text(Jason.encode!(stats))
    else
      conn
      |> put_status(404)
      |> json([])
    end
  end

  def nick_gls_json(conn = %{assigns: %{account: account}}, params = %{"network" => network, "nick" => nick}) do
    profile_account = IRC.Account.find_always_by_nick(network, nick, nick)
    friend? = Enum.member?(IRC.Membership.friends(account), profile_account.id)
    count = String.to_integer(Map.get(params, "days", "180"))
    if friend? do
      data = Nola.Plugins.Alcoolog.user_over_time_gl(profile_account, count)
    delay = count*((24 * 60)*60)
    now = DateTime.utc_now()
    start_date = DateTime.utc_now()
             |> DateTime.shift_zone!("Europe/Paris", Tzdata.TimeZoneDatabase)
             |> DateTime.add(-delay, :second, Tzdata.TimeZoneDatabase)
             |> DateTime.to_date()
             |> Date.to_erl()
  filled = (:calendar.date_to_gregorian_days(start_date) .. :calendar.date_to_gregorian_days(DateTime.utc_now |> DateTime.to_date() |> Date.to_erl))
  |> Enum.to_list
  |> Enum.map(&(:calendar.gregorian_days_to_date(&1)))
  |> Enum.map(&Date.from_erl!(&1))
  |> Enum.map(fn(date) ->
    %{date: date, gls: Map.get(data, date, 0)}
  end)
  |> Enum.sort(&(Date.compare(&1.date, &2.date) != :gt))

      conn
      |> put_resp_content_type("application/json")
      |> text(Jason.encode!(filled))
    else
      conn
      |> put_status(404)
      |> json([])
    end
  end



  def nick_volumes_json(conn = %{assigns: %{account: account}}, params = %{"network" => network, "nick" => nick}) do
    profile_account = IRC.Account.find_always_by_nick(network, nick, nick)
    friend? = Enum.member?(IRC.Membership.friends(account), profile_account.id)
    count = String.to_integer(Map.get(params, "days", "180"))
    if friend? do
      data = Nola.Plugins.Alcoolog.user_over_time(profile_account, count)
    delay = count*((24 * 60)*60)
    now = DateTime.utc_now()
    start_date = DateTime.utc_now()
             |> DateTime.shift_zone!("Europe/Paris", Tzdata.TimeZoneDatabase)
             |> DateTime.add(-delay, :second, Tzdata.TimeZoneDatabase)
             |> DateTime.to_date()
             |> Date.to_erl()
  filled = (:calendar.date_to_gregorian_days(start_date) .. :calendar.date_to_gregorian_days(DateTime.utc_now |> DateTime.to_date() |> Date.to_erl))
  |> Enum.to_list
  |> Enum.map(&(:calendar.gregorian_days_to_date(&1)))
  |> Enum.map(&Date.from_erl!(&1))
  |> Enum.map(fn(date) ->
    %{date: date, volumes: Map.get(data, date, 0)}
  end)
  |> Enum.sort(&(Date.compare(&1.date, &2.date) != :gt))

      conn
      |> put_resp_content_type("application/json")
      |> text(Jason.encode!(filled))
    else
      conn
      |> put_status(404)
      |> json([])
    end
  end

  def nick_log_json(conn = %{assigns: %{account: account}}, %{"network" => network, "nick" => nick}) do
    profile_account = IRC.Account.find_always_by_nick(network, nick, nick)
    friend? = Enum.member?(IRC.Membership.friends(account), profile_account.id)
    if friend? do
      history = for {{nick, ts}, points, active, cl, deg, type, descr, meta} <- Nola.Plugins.Alcoolog.nick_history(profile_account) do
        %{
          at: ts |> DateTime.from_unix!(:millisecond) |> DateTime.to_iso8601(),
          points: points,
          active: active,
          cl: cl,
          deg: deg,
          type: type,
          description: descr,
          meta: meta
        }
    end
      last = List.last(history)
      {_, active} = Nola.Plugins.Alcoolog.user_stats(profile_account)
      last = %{last | active: active, at: DateTime.utc_now() |> DateTime.to_iso8601()}
      history = history ++ [last]

      conn
      |> put_resp_content_type("application/json")
      |> text(Jason.encode!(history))
    else
      conn
      |> put_status(404)
      |> json([])
    end
  end

  def nick_history_json(conn = %{assigns: %{account: account}}, %{"network" => network, "nick" => nick}) do
    profile_account = IRC.Account.find_always_by_nick(network, nick, nick)
    friend? = Enum.member?(IRC.Membership.friends(account), profile_account.id)
    if friend? do
      history = for {_, date, value} <- Nola.Plugs.AlcoologAnnouncer.log(profile_account) do
        %{date: DateTime.to_iso8601(date), value: value}
    end
      conn
      |> put_resp_content_type("application/json")
      |> text(Jason.encode!(history))
    else
      conn
      |> put_status(404)
      |> json([])
    end
  end

  def index(conn = %{assigns: %{account: account}}, %{"network" => network, "chan" => channel}) do
    index(conn, account, network, NolaWeb.reformat_chan(channel))
  end

  def index(conn = %{assigns: %{account: account}}, _) do
    index(conn, account, nil, nil)
  end

  #def index(conn, params) do
  #  network = Map.get(params, "network")
  #  chan = if c = Map.get(params, "chan") do
  #    NolaWeb.reformat_chan(c)
  #  end
  #  irc_conn = if network do
  #    IRC.Connection.get_network(network, chan)
  #  end
  #  bot = if(irc_conn, do: irc_conn.nick)#
  #
  #  conn
  #  |> put_status(403)
  #  |> render("auth.html", network: network, channel: chan, irc_conn: conn, bot: bot)
  #end

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

  # tuple ets:  {{nick, date}, volumes, current, nom, commentaire}
    members = IRC.Membership.expanded_members_or_friends(account, network, channel)
    members_ids = Enum.map(members, fn({account, _, nick}) -> account.id end)
    member_names = Enum.reduce(members, %{}, fn({account, _, nick}, acc) -> Map.put(acc, account.id, nick) end)
    drinks = :ets.select(Nola.Plugins.Alcoolog.ETS, match)
             |> Enum.filter(fn({{account, _}, _vol, _cur, _cl, _deg, _name, _cmt, _meta}) -> Enum.member?(members_ids, account) end)
             |> Enum.map(fn({{account, _}, _, _, _, _, _, _, _} = object) -> {object, Map.get(member_names, account)} end)
    |> Enum.sort_by(fn({{{_, ts}, _, _, _, _, _, _, _}, _}) -> ts end, &>/2)

    stats = Nola.Plugins.Alcoolog.get_channel_statistics(account, network, channel)

    top = Enum.reduce(drinks, %{}, fn({{{account_id, _}, vol, _, _, _, _, _, _}, _}, acc) ->
      nick = Map.get(member_names, account_id)
      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}
    #
    conn
    |> assign(:title, "alcoolog")
    |> render("index.html", network: network, channel: channel, drinks: drinks, top: top, stats: stats)
  end

  def index_gls_json(conn = %{assigns: %{account: account}}, %{"network" => network, "chan" => channel}) do
    count = 30
    channel = NolaWeb.reformat_chan(channel)
    members = IRC.Membership.expanded_members_or_friends(account, network, channel)
    members_ids = Enum.map(members, fn({account, _, nick}) -> account.id end)
    member_names = Enum.reduce(members, %{}, fn({account, _, nick}, acc) -> Map.put(acc, account.id, nick) end)
    delay = count*((24 * 60)*60)
    now = DateTime.utc_now()
    start_date = DateTime.utc_now()
             |> DateTime.shift_zone!("Europe/Paris", Tzdata.TimeZoneDatabase)
             |> DateTime.add(-delay, :second, Tzdata.TimeZoneDatabase)
             |> DateTime.to_date()
             |> Date.to_erl()
  filled = (:calendar.date_to_gregorian_days(start_date) .. :calendar.date_to_gregorian_days(DateTime.utc_now |> DateTime.to_date() |> Date.to_erl))
  |> Enum.to_list
  |> Enum.map(&(:calendar.gregorian_days_to_date(&1)))
  |> Enum.map(&Date.from_erl!(&1))
  |> Enum.map(fn(date) ->
    {date, (for {a, _, _} <- members, into: Map.new, do: {Map.get(member_names, a.id, a.id), 0})}
  end)
  |> Enum.into(Map.new)

    gls = Enum.reduce(members, filled, fn({account, _, _}, gls) ->
      Enum.reduce(Nola.Plugins.Alcoolog.user_over_time_gl(account, count), gls, fn({date, gl}, gls) ->
        u = Map.get(gls, date, %{})
            |> Map.put(Map.get(member_names, account.id, account.id), gl)
        Map.put(gls, date, u)
      end)
    end)

    dates = (:calendar.date_to_gregorian_days(start_date) .. :calendar.date_to_gregorian_days(DateTime.utc_now |> DateTime.to_date() |> Date.to_erl))
    |> Enum.to_list
    |> Enum.map(&(:calendar.gregorian_days_to_date(&1)))
    |> Enum.map(&Date.from_erl!(&1))

    filled2 = Enum.map(member_names, fn({_, name}) ->
    history = (:calendar.date_to_gregorian_days(start_date) .. :calendar.date_to_gregorian_days(DateTime.utc_now |> DateTime.to_date() |> Date.to_erl))
    |> Enum.to_list
    |> Enum.map(&(:calendar.gregorian_days_to_date(&1)))
    |> Enum.map(&Date.from_erl!(&1))
    |> Enum.map(fn(date) ->
      get_in(gls, [date, name]) #%{date: date, gl: get_in(gls, [date, name])}
    end)
      if Enum.all?(history, fn(x) -> x == 0 end) do
        nil
      else
        %{name: name, history: history}
      end
    end)
    |> Enum.filter(fn(x) -> x end)

      conn
      |> put_resp_content_type("application/json")
      |> text(Jason.encode!(%{labels: dates, data: filled2}))
  end

  def minisync(conn, %{"user_id" => user_id, "key" => key, "value" => value}) do
    account = IRC.Account.get(user_id)
    if account do
      ds = Nola.Plugins.Alcoolog.data_state()
      meta = Nola.Plugins.Alcoolog.get_user_meta(ds, account.id)
      case Float.parse(value) do
        {val, _} ->
          new_meta = Map.put(meta, String.to_existing_atom(key), val)
          Nola.Plugins.Alcoolog.put_user_meta(ds, account.id, new_meta)
        _ ->
          conn
          |> put_status(:unprocessable_entity)
          |> text("invalid value")
      end
    else
      conn
      |> put_status(:not_found)
      |> text("not found")
    end
  end

end