Merge branch 'develop' into a1batross-develop-patch-62810
[akkoma] / lib / pleroma / workers / purge_expired_activity.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.PurgeExpiredActivity do
6 @moduledoc """
7 Worker which purges expired activity.
8 """
9
10 use Oban.Worker, queue: :activity_expiration, max_attempts: 1, unique: [period: :infinity]
11
12 import Ecto.Query
13
14 alias Pleroma.Activity
15
16 @spec enqueue(map()) ::
17 {:ok, Oban.Job.t()}
18 | {:error, :expired_activities_disabled}
19 | {:error, :expiration_too_close}
20 def enqueue(args) do
21 with true <- enabled?() do
22 {scheduled_at, args} = Map.pop(args, :expires_at)
23
24 args
25 |> new(scheduled_at: scheduled_at)
26 |> Oban.insert()
27 end
28 end
29
30 @impl true
31 def perform(%Oban.Job{args: %{"activity_id" => id}}) do
32 with %Activity{} = activity <- find_activity(id),
33 %Pleroma.User{} = user <- find_user(activity.object.data["actor"]) do
34 Pleroma.Web.CommonAPI.delete(activity.id, user)
35 end
36 end
37
38 defp enabled? do
39 with false <- Pleroma.Config.get([__MODULE__, :enabled], false) do
40 {:error, :expired_activities_disabled}
41 end
42 end
43
44 defp find_activity(id) do
45 with nil <- Activity.get_by_id_with_object(id) do
46 {:error, :activity_not_found}
47 end
48 end
49
50 defp find_user(ap_id) do
51 with nil <- Pleroma.User.get_by_ap_id(ap_id) do
52 {:error, :user_not_found}
53 end
54 end
55
56 def get_expiration(id) do
57 from(j in Oban.Job,
58 where: j.state == "scheduled",
59 where: j.queue == "activity_expiration",
60 where: fragment("?->>'activity_id' = ?", j.args, ^id)
61 )
62 |> Pleroma.Repo.one()
63 end
64
65 @spec expires_late_enough?(DateTime.t()) :: boolean()
66 def expires_late_enough?(scheduled_at) do
67 now = DateTime.utc_now()
68 diff = DateTime.diff(scheduled_at, now, :millisecond)
69 min_lifetime = Pleroma.Config.get([__MODULE__, :min_lifetime], 600)
70 diff > :timer.seconds(min_lifetime)
71 end
72 end