Merge remote-tracking branch 'origin/develop' into global-status-expiration
[akkoma] / lib / pleroma / workers / cron / digest_emails_worker.ex
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
4
5 defmodule Pleroma.Workers.Cron.DigestEmailsWorker do
6 @moduledoc """
7 The worker to send digest emails.
8 """
9
10 use Oban.Worker, queue: "digest_emails"
11
12 alias Pleroma.Config
13 alias Pleroma.Emails
14 alias Pleroma.Repo
15 alias Pleroma.User
16
17 import Ecto.Query
18
19 require Logger
20
21 @impl Oban.Worker
22 def perform(_opts, _job) do
23 config = Config.get([:email_notifications, :digest])
24
25 if config[:active] do
26 negative_interval = -Map.fetch!(config, :interval)
27 inactivity_threshold = Map.fetch!(config, :inactivity_threshold)
28 inactive_users_query = User.list_inactive_users_query(inactivity_threshold)
29
30 now = NaiveDateTime.truncate(NaiveDateTime.utc_now(), :second)
31
32 from(u in inactive_users_query,
33 where: fragment(~s(? ->'digest' @> 'true'), u.email_notifications),
34 where: u.last_digest_emailed_at < datetime_add(^now, ^negative_interval, "day"),
35 select: u
36 )
37 |> Repo.all()
38 |> send_emails
39 end
40 end
41
42 def send_emails(users) do
43 Enum.each(users, &send_email/1)
44 end
45
46 @doc """
47 Send digest email to the given user.
48 Updates `last_digest_emailed_at` field for the user and returns the updated user.
49 """
50 @spec send_email(User.t()) :: User.t()
51 def send_email(user) do
52 with %Swoosh.Email{} = email <- Emails.UserEmail.digest_email(user) do
53 Emails.Mailer.deliver_async(email)
54 end
55
56 User.touch_last_digest_emailed_at(user)
57 end
58 end