2020-12-09 12:00:14 +03:00
|
|
|
defmodule Plausible.Workers.SpikeNotifier do
|
|
|
|
use Plausible.Repo
|
|
|
|
alias Plausible.Stats.Query
|
2020-12-09 12:16:16 +03:00
|
|
|
alias Plausible.Site.SpikeNotification
|
2020-12-09 12:00:14 +03:00
|
|
|
use Oban.Worker, queue: :spike_notifications
|
|
|
|
@at_most_every "12 hours"
|
|
|
|
|
|
|
|
@impl Oban.Worker
|
|
|
|
def perform(_args, _job, clickhouse \\ Plausible.Stats.Clickhouse) do
|
2020-12-29 16:17:27 +03:00
|
|
|
notifications =
|
|
|
|
Repo.all(
|
|
|
|
from sn in SpikeNotification,
|
|
|
|
where: is_nil(sn.last_sent),
|
|
|
|
or_where: sn.last_sent < fragment("now() - INTERVAL ?", @at_most_every),
|
|
|
|
preload: :site
|
|
|
|
)
|
2020-12-09 12:00:14 +03:00
|
|
|
|
|
|
|
for notification <- notifications do
|
|
|
|
query = Query.from(notification.site.timezone, %{"period" => "realtime"})
|
|
|
|
current_visitors = clickhouse.current_visitors(notification.site, query)
|
2020-12-11 18:01:09 +03:00
|
|
|
sources = clickhouse.top_sources(notification.site, query, 3, 1, true)
|
2020-12-11 12:50:44 +03:00
|
|
|
notify(notification, current_visitors, sources)
|
2020-12-09 12:00:14 +03:00
|
|
|
end
|
2020-12-29 16:23:24 +03:00
|
|
|
|
|
|
|
:ok
|
2020-12-09 12:00:14 +03:00
|
|
|
end
|
|
|
|
|
2020-12-11 12:50:44 +03:00
|
|
|
def notify(notification, current_visitors, sources) do
|
2020-12-09 12:00:14 +03:00
|
|
|
if current_visitors >= notification.threshold do
|
|
|
|
for recipient <- notification.recipients do
|
2020-12-11 12:50:44 +03:00
|
|
|
send_notification(recipient, notification.site, current_visitors, sources)
|
2020-12-09 12:00:14 +03:00
|
|
|
end
|
2020-12-29 16:17:27 +03:00
|
|
|
|
2020-12-09 12:16:16 +03:00
|
|
|
notification
|
|
|
|
|> SpikeNotification.was_sent()
|
2020-12-29 16:17:27 +03:00
|
|
|
|> Repo.update()
|
2020-12-09 12:00:14 +03:00
|
|
|
end
|
|
|
|
end
|
|
|
|
|
2020-12-11 12:50:44 +03:00
|
|
|
defp send_notification(recipient, site, current_visitors, sources) do
|
|
|
|
site = Repo.preload(site, :members)
|
|
|
|
|
2020-12-29 16:17:27 +03:00
|
|
|
dashboard_link =
|
|
|
|
if Enum.member?(site.members, recipient) do
|
|
|
|
PlausibleWeb.Endpoint.url() <> "/" <> URI.encode_www_form(site.domain)
|
|
|
|
end
|
|
|
|
|
|
|
|
template =
|
|
|
|
PlausibleWeb.Email.spike_notification(
|
|
|
|
recipient,
|
|
|
|
site,
|
|
|
|
current_visitors,
|
|
|
|
sources,
|
|
|
|
dashboard_link
|
|
|
|
)
|
2020-12-11 12:50:44 +03:00
|
|
|
|
2020-12-09 12:00:14 +03:00
|
|
|
try do
|
|
|
|
Plausible.Mailer.send_email(template)
|
|
|
|
rescue
|
|
|
|
_ -> nil
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|