[#1149] Upgraded `oban` from 0.6.0 to 0.7.1.
[akkoma] / lib / pleroma / digest_email_worker.ex
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2019 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
4
5 defmodule Pleroma.DigestEmailWorker do
6 alias Pleroma.Repo
7 alias Pleroma.Workers.Mailer, as: MailerWorker
8
9 import Ecto.Query
10
11 defdelegate worker_args(queue), to: Pleroma.Workers.Helper
12
13 def perform do
14 config = Pleroma.Config.get([:email_notifications, :digest])
15 negative_interval = -Map.fetch!(config, :interval)
16 inactivity_threshold = Map.fetch!(config, :inactivity_threshold)
17 inactive_users_query = Pleroma.User.list_inactive_users_query(inactivity_threshold)
18
19 now = NaiveDateTime.truncate(NaiveDateTime.utc_now(), :second)
20
21 from(u in inactive_users_query,
22 where: fragment(~s(? #> '{"email_notifications","digest"}' @> 'true'), u.info),
23 where: u.last_digest_emailed_at < datetime_add(^now, ^negative_interval, "day"),
24 select: u
25 )
26 |> Pleroma.Repo.all()
27 |> Enum.each(fn user ->
28 %{"op" => "digest_email", "user_id" => user.id}
29 |> MailerWorker.new([queue: "digest_emails"] ++ worker_args(:digest_emails))
30 |> Repo.insert()
31 end)
32 end
33
34 @doc """
35 Send digest email to the given user.
36 Updates `last_digest_emailed_at` field for the user and returns the updated user.
37 """
38 @spec perform(Pleroma.User.t()) :: Pleroma.User.t()
39 def perform(user) do
40 with %Swoosh.Email{} = email <- Pleroma.Emails.UserEmail.digest_email(user) do
41 Pleroma.Emails.Mailer.deliver_async(email)
42 end
43
44 Pleroma.User.touch_last_digest_emailed_at(user)
45 end
46 end