Fix buckets for query timing
[akkoma] / lib / pleroma / workers / backup_worker.ex
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
4
5 defmodule Pleroma.Workers.BackupWorker do
6 use Oban.Worker, queue: :backup, max_attempts: 1
7
8 alias Oban.Job
9 alias Pleroma.User.Backup
10
11 def process(backup, admin_user_id \\ nil) do
12 %{"op" => "process", "backup_id" => backup.id, "admin_user_id" => admin_user_id}
13 |> new()
14 |> Oban.insert()
15 end
16
17 @impl Oban.Worker
18 def timeout(_job) do
19 Pleroma.Config.get([:workers, :timeout, :backup], :timer.minutes(1))
20 end
21
22 def schedule_deletion(backup) do
23 days = Pleroma.Config.get([Backup, :purge_after_days])
24 time = 60 * 60 * 24 * days
25 scheduled_at = Calendar.NaiveDateTime.add!(backup.inserted_at, time)
26
27 %{"op" => "delete", "backup_id" => backup.id}
28 |> new(scheduled_at: scheduled_at)
29 |> Oban.insert()
30 end
31
32 def delete(backup) do
33 %{"op" => "delete", "backup_id" => backup.id}
34 |> new()
35 |> Oban.insert()
36 end
37
38 @impl true
39 def perform(%Job{
40 args: %{"op" => "process", "backup_id" => backup_id, "admin_user_id" => admin_user_id}
41 }) do
42 with {:ok, %Backup{} = backup} <-
43 backup_id |> Backup.get() |> Backup.process(),
44 {:ok, _job} <- schedule_deletion(backup),
45 :ok <- Backup.remove_outdated(backup),
46 :ok <- maybe_deliver_email(backup, admin_user_id) do
47 {:ok, backup}
48 end
49 end
50
51 def perform(%Job{args: %{"op" => "delete", "backup_id" => backup_id}}) do
52 case Backup.get(backup_id) do
53 %Backup{} = backup -> Backup.delete(backup)
54 nil -> :ok
55 end
56 end
57
58 defp has_email?(user) do
59 not is_nil(user.email) and user.email != ""
60 end
61
62 defp maybe_deliver_email(backup, admin_user_id) do
63 has_mailer = Pleroma.Config.get([Pleroma.Emails.Mailer, :enabled])
64 backup = backup |> Pleroma.Repo.preload(:user)
65
66 if has_email?(backup.user) and has_mailer do
67 backup
68 |> Pleroma.Emails.UserEmail.backup_is_ready_email(admin_user_id)
69 |> Pleroma.Emails.Mailer.deliver()
70
71 :ok
72 else
73 :ok
74 end
75 end
76 end