Merge branch 'develop' into feature/reports-groups-and-multiple-state-update
[akkoma] / lib / pleroma / daemons / digest_email_daemon.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.Daemons.DigestEmailDaemon do
6 alias Pleroma.Repo
7 alias Pleroma.Workers.DigestEmailsWorker
8
9 import Ecto.Query
10
11 def perform do
12 config = Pleroma.Config.get([:email_notifications, :digest])
13 negative_interval = -Map.fetch!(config, :interval)
14 inactivity_threshold = Map.fetch!(config, :inactivity_threshold)
15 inactive_users_query = Pleroma.User.list_inactive_users_query(inactivity_threshold)
16
17 now = NaiveDateTime.truncate(NaiveDateTime.utc_now(), :second)
18
19 from(u in inactive_users_query,
20 where: fragment(~s(? #> '{"email_notifications","digest"}' @> 'true'), u.info),
21 where: u.last_digest_emailed_at < datetime_add(^now, ^negative_interval, "day"),
22 select: u
23 )
24 |> Repo.all()
25 |> Enum.each(fn user ->
26 DigestEmailsWorker.enqueue("digest_email", %{"user_id" => user.id})
27 end)
28 end
29
30 @doc """
31 Send digest email to the given user.
32 Updates `last_digest_emailed_at` field for the user and returns the updated user.
33 """
34 @spec perform(Pleroma.User.t()) :: Pleroma.User.t()
35 def perform(user) do
36 with %Swoosh.Email{} = email <- Pleroma.Emails.UserEmail.digest_email(user) do
37 Pleroma.Emails.Mailer.deliver_async(email)
38 end
39
40 Pleroma.User.touch_last_digest_emailed_at(user)
41 end
42 end