GOOGLE
[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 Oban.Worker
31 def timeout(_job) do
32 Pleroma.Config.get([:workers, :timeout, :activity_expiration], :timer.minutes(1))
33 end
34
35 @impl true
36 def perform(%Oban.Job{args: %{"activity_id" => id}}) do
37 with %Activity{} = activity <- find_activity(id),
38 %Pleroma.User{} = user <- find_user(activity.object.data["actor"]) do
39 Pleroma.Web.CommonAPI.delete(activity.id, user)
40 end
41 end
42
43 defp enabled? do
44 with false <- Pleroma.Config.get([__MODULE__, :enabled], false) do
45 {:error, :expired_activities_disabled}
46 end
47 end
48
49 defp find_activity(id) do
50 with nil <- Activity.get_by_id_with_object(id) do
51 {:error, :activity_not_found}
52 end
53 end
54
55 defp find_user(ap_id) do
56 with nil <- Pleroma.User.get_by_ap_id(ap_id) do
57 {:error, :user_not_found}
58 end
59 end
60
61 def get_expiration(id) do
62 from(j in Oban.Job,
63 where: j.state == "scheduled",
64 where: j.queue == "activity_expiration",
65 where: fragment("?->>'activity_id' = ?", j.args, ^id)
66 )
67 |> Pleroma.Repo.one()
68 end
69
70 @spec expires_late_enough?(DateTime.t()) :: boolean()
71 def expires_late_enough?(scheduled_at) do
72 now = DateTime.utc_now()
73 diff = DateTime.diff(scheduled_at, now, :millisecond)
74 min_lifetime = Pleroma.Config.get([__MODULE__, :min_lifetime], 600)
75 diff > :timer.seconds(min_lifetime)
76 end
77 end