Merge branch 'develop' of https://git.pleroma.social/pleroma/pleroma into develop
[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: 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 end
42
43 def send_emails(users) do
44 Enum.each(users, &send_email/1)
45 end
46
47 @doc """
48 Send digest email to the given user.
49 Updates `last_digest_emailed_at` field for the user and returns the updated user.
50 """
51 @spec send_email(User.t()) :: User.t()
52 def send_email(user) do
53 with %Swoosh.Email{} = email <- Emails.UserEmail.digest_email(user) do
54 Emails.Mailer.deliver_async(email)
55 end
56
57 User.touch_last_digest_emailed_at(user)
58 end
59 end