2019-11-27 05:59:13 -07:00
|
|
|
# Pleroma: A lightweight social networking server
|
2022-02-25 23:11:42 -07:00
|
|
|
# Copyright © 2017-2022 Pleroma Authors <https://pleroma.social/>
|
2019-11-27 05:59:13 -07:00
|
|
|
# SPDX-License-Identifier: AGPL-3.0-only
|
|
|
|
|
|
|
|
defmodule Pleroma.Workers.Cron.DigestEmailsWorker do
|
|
|
|
@moduledoc """
|
|
|
|
The worker to send digest emails.
|
|
|
|
"""
|
|
|
|
|
|
|
|
use Oban.Worker, queue: "digest_emails"
|
|
|
|
|
|
|
|
alias Pleroma.Config
|
|
|
|
alias Pleroma.Emails
|
|
|
|
alias Pleroma.Repo
|
|
|
|
alias Pleroma.User
|
|
|
|
|
|
|
|
import Ecto.Query
|
|
|
|
|
|
|
|
require Logger
|
|
|
|
|
|
|
|
@impl Oban.Worker
|
2020-06-23 06:09:01 -06:00
|
|
|
def perform(_job) do
|
2019-11-27 05:59:13 -07:00
|
|
|
config = Config.get([:email_notifications, :digest])
|
|
|
|
|
|
|
|
if config[:active] do
|
|
|
|
negative_interval = -Map.fetch!(config, :interval)
|
|
|
|
inactivity_threshold = Map.fetch!(config, :inactivity_threshold)
|
|
|
|
inactive_users_query = User.list_inactive_users_query(inactivity_threshold)
|
|
|
|
|
|
|
|
now = NaiveDateTime.truncate(NaiveDateTime.utc_now(), :second)
|
|
|
|
|
|
|
|
from(u in inactive_users_query,
|
|
|
|
where: fragment(~s(? ->'digest' @> 'true'), u.email_notifications),
|
2020-02-27 06:27:49 -07:00
|
|
|
where: not is_nil(u.email),
|
2019-11-27 05:59:13 -07:00
|
|
|
where: u.last_digest_emailed_at < datetime_add(^now, ^negative_interval, "day"),
|
|
|
|
select: u
|
|
|
|
)
|
|
|
|
|> Repo.all()
|
|
|
|
|> send_emails
|
|
|
|
end
|
2020-08-13 12:01:54 -06:00
|
|
|
|
|
|
|
:ok
|
2019-11-27 05:59:13 -07:00
|
|
|
end
|
|
|
|
|
|
|
|
def send_emails(users) do
|
|
|
|
Enum.each(users, &send_email/1)
|
|
|
|
end
|
|
|
|
|
|
|
|
@doc """
|
|
|
|
Send digest email to the given user.
|
|
|
|
Updates `last_digest_emailed_at` field for the user and returns the updated user.
|
|
|
|
"""
|
|
|
|
@spec send_email(User.t()) :: User.t()
|
|
|
|
def send_email(user) do
|
|
|
|
with %Swoosh.Email{} = email <- Emails.UserEmail.digest_email(user) do
|
|
|
|
Emails.Mailer.deliver_async(email)
|
|
|
|
end
|
|
|
|
|
|
|
|
User.touch_last_digest_emailed_at(user)
|
|
|
|
end
|
|
|
|
end
|