philomena/lib/philomena_web/plugs/advert_plug.ex

41 lines
953 B
Elixir
Raw Normal View History

2019-11-29 07:26:05 +01:00
defmodule PhilomenaWeb.AdvertPlug do
2020-05-27 23:14:22 +02:00
alias PhilomenaWeb.AdvertUpdater
2019-11-29 07:26:05 +01:00
alias Philomena.Adverts
alias Plug.Conn
def init([]), do: []
def call(conn, _opts) do
user = conn.assigns.current_user
image = conn.assigns[:image]
show_ads? = show_ads?(user)
2020-05-27 23:14:22 +02:00
maybe_assign_ad(conn, image, show_ads?)
2019-11-29 07:26:05 +01:00
end
2020-08-08 02:23:36 +02:00
defp maybe_assign_ad(conn, image, show_ads?)
2019-11-29 07:26:05 +01:00
defp maybe_assign_ad(conn, nil, true),
2020-05-27 23:14:22 +02:00
do: Conn.assign(conn, :advert, record_impression(Adverts.random_live()))
2020-01-11 05:20:19 +01:00
2019-11-29 07:26:05 +01:00
defp maybe_assign_ad(conn, image, true),
2020-05-27 23:14:22 +02:00
do: Conn.assign(conn, :advert, record_impression(Adverts.random_live_for(image)))
2020-01-11 05:20:19 +01:00
2019-11-29 07:26:05 +01:00
defp maybe_assign_ad(conn, _image, _false),
2020-08-13 23:55:36 +02:00
do: Conn.assign(conn, :advert, nil)
2019-11-29 07:26:05 +01:00
2020-08-08 02:23:36 +02:00
defp show_ads?(%{hide_advertisements: hide}),
do: !hide
2020-01-11 05:20:19 +01:00
2019-11-29 07:26:05 +01:00
defp show_ads?(_user),
do: true
2020-05-27 23:14:22 +02:00
defp record_impression(nil), do: nil
defp record_impression(advert) do
AdvertUpdater.cast(:impression, advert.id)
advert
end
2020-01-11 05:20:19 +01:00
end