Use PleromaJobQueue for scheduling
[akkoma] / lib / pleroma / digest_email_worker.ex
1 defmodule Pleroma.DigestEmailWorker do
2 import Ecto.Query
3
4 @queue_name :digest_emails
5
6 def perform do
7 config = Pleroma.Config.get([:email_notifications, :digest])
8 negative_interval = -Map.fetch!(config, :interval)
9 inactivity_threshold = Map.fetch!(config, :inactivity_threshold)
10 inactive_users_query = Pleroma.User.list_inactive_users_query(inactivity_threshold)
11
12 now = NaiveDateTime.truncate(NaiveDateTime.utc_now(), :second)
13
14 from(u in inactive_users_query,
15 where: fragment(~s(? #> '{"email_notifications","digest"}' @> 'true'), u.info),
16 where: u.last_digest_emailed_at < datetime_add(^now, ^negative_interval, "day"),
17 select: u
18 )
19 |> Pleroma.Repo.all()
20 |> Enum.each(&PleromaJobQueue.enqueue(@queue_name, __MODULE__, [&1]))
21 end
22
23 @doc """
24 Send digest email to the given user.
25 Updates `last_digest_emailed_at` field for the user and returns the updated user.
26 """
27 @spec perform(Pleroma.User.t()) :: Pleroma.User.t()
28 def perform(user) do
29 with %Swoosh.Email{} = email <- Pleroma.Emails.UserEmail.digest_email(user) do
30 Pleroma.Emails.Mailer.deliver_async(email)
31 end
32
33 Pleroma.User.touch_last_digest_emailed_at(user)
34 end
35 end