Merge branch 'develop' into feature/gen-magic
[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(_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: not is_nil(u.email),
35 where: u.last_digest_emailed_at < datetime_add(^now, ^negative_interval, "day"),
36 select: u
37 )
38 |> Repo.all()
39 |> send_emails
40 end
41
42 :ok
43 end
44
45 def send_emails(users) do
46 Enum.each(users, &send_email/1)
47 end
48
49 @doc """
50 Send digest email to the given user.
51 Updates `last_digest_emailed_at` field for the user and returns the updated user.
52 """
53 @spec send_email(User.t()) :: User.t()
54 def send_email(user) do
55 with %Swoosh.Email{} = email <- Emails.UserEmail.digest_email(user) do
56 Emails.Mailer.deliver_async(email)
57 end
58
59 User.touch_last_digest_emailed_at(user)
60 end
61 end