1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
5 defmodule Pleroma.Workers.PurgeExpiredActivity do
7 Worker which purges expired activity.
10 use Oban.Worker, queue: :activity_expiration, max_attempts: 1
14 alias Pleroma.Activity
17 with true <- enabled?(),
18 args when is_map(args) <- validate_expires_at(args) do
19 {scheduled_at, args} = Map.pop(args, :expires_at)
22 |> __MODULE__.new(scheduled_at: scheduled_at)
28 def perform(%Oban.Job{args: %{"activity_id" => id}}) do
29 with %Activity{} = activity <- find_activity(id),
30 %Pleroma.User{} = user <- find_user(activity.object.data["actor"]),
31 false <- pinned_by_actor?(activity, user) do
32 Pleroma.Web.CommonAPI.delete(activity.id, user)
35 # if activity is pinned, schedule deletion on next day
36 enqueue(%{activity_id: id, expires_at: DateTime.add(DateTime.utc_now(), 24 * 3600)})
46 with false <- Pleroma.Config.get([__MODULE__, :enabled], false) do
47 {:error, :expired_activities_disabled}
51 defp validate_expires_at(%{validate: false} = args), do: Map.delete(args, :validate)
53 defp validate_expires_at(args) do
54 if expires_late_enough?(args[:expires_at]) do
57 {:error, :expiration_too_close}
61 defp find_activity(id) do
62 with nil <- Activity.get_by_id_with_object(id) do
63 {:error, :activity_not_found}
67 defp find_user(ap_id) do
68 with nil <- Pleroma.User.get_by_ap_id(ap_id) do
69 {:error, :user_not_found}
73 defp pinned_by_actor?(activity, user) do
74 with true <- Activity.pinned_by_actor?(activity, user) do
79 def get_expiration(id) do
81 where: j.state == "scheduled",
82 where: j.queue == "activity_expiration",
83 where: fragment("?->>'activity_id' = ?", j.args, ^id)
88 @spec expires_late_enough?(DateTime.t()) :: boolean()
89 def expires_late_enough?(scheduled_at) do
90 now = DateTime.utc_now()
91 diff = DateTime.diff(scheduled_at, now, :millisecond)
92 diff > :timer.hours(1)