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
|
|
|
|
notifications = Repo.all(
|
2020-12-09 12:16:16 +03:00
|
|
|
from sn in SpikeNotification,
|
2020-12-09 12:00:14 +03:00
|
|
|
where: is_nil(sn.last_sent),
|
2020-12-09 12:16:16 +03:00
|
|
|
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)
|
|
|
|
notify(notification, current_visitors)
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
def notify(notification, current_visitors) do
|
|
|
|
if current_visitors >= notification.threshold do
|
|
|
|
for recipient <- notification.recipients do
|
|
|
|
send_notification(recipient, notification.site, current_visitors)
|
|
|
|
end
|
2020-12-09 12:16:16 +03:00
|
|
|
notification
|
|
|
|
|> SpikeNotification.was_sent()
|
|
|
|
|> Repo.update
|
2020-12-09 12:00:14 +03:00
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
defp send_notification(recipient, site, current_visitors) do
|
|
|
|
template = PlausibleWeb.Email.spike_notification(recipient, site, current_visitors)
|
|
|
|
try do
|
|
|
|
Plausible.Mailer.send_email(template)
|
|
|
|
rescue
|
|
|
|
_ -> nil
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|