1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2022 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
5 defmodule Pleroma.Workers.AttachmentsCleanupWorker do
11 use Pleroma.Workers.WorkerHelper, queue: "attachments_cleanup"
16 "op" => "cleanup_attachments",
17 "object" => %{"data" => %{"attachment" => [_ | _] = attachments, "actor" => actor}}
20 if Pleroma.Config.get([:instance, :cleanup_attachments], false) do
22 |> Enum.flat_map(fn item -> Enum.map(item["url"], & &1["href"]) end)
24 |> prepare_objects(actor, Enum.map(attachments, & &1["name"]))
32 def perform(%Job{args: %{"op" => "cleanup_attachments", "object" => _object}}), do: {:ok, :skip}
35 def timeout(_job), do: :timer.seconds(900)
37 defp do_clean({object_ids, attachment_urls}) do
38 uploader = Pleroma.Config.get([Pleroma.Upload, :uploader])
42 Pleroma.Upload.base_url(),
46 Enum.each(attachment_urls, fn href ->
48 |> String.trim_leading("#{base_url}")
49 |> uploader.delete_file()
52 delete_objects(object_ids)
55 defp delete_objects([_ | _] = object_ids) do
56 Repo.delete_all(from(o in Object, where: o.id in ^object_ids))
59 defp delete_objects(_), do: :ok
61 # we should delete 1 object for any given attachment, but don't delete
62 # files if there are more than 1 object for it
63 defp filter_objects(objects) do
64 Enum.reduce(objects, {[], []}, fn {href, %{id: id, count: count}}, {ids, hrefs} ->
66 {ids ++ [id], hrefs ++ [href]}
68 _ -> {ids ++ [id], hrefs}
73 defp prepare_objects(objects, actor, names) do
75 |> Enum.reduce(%{}, fn %{
78 "url" => [%{"href" => href}],
84 Map.update(acc, href, %{id: id, count: 1}, fn val ->
85 case obj_actor == actor and name in names do
87 # set id of the actor's object that will be deleted
88 %{val | id: id, count: val.count + 1}
91 # another actor's object, just increase count to not delete file
92 %{val | count: val.count + 1}
98 defp fetch_objects(hrefs) do
102 "to_jsonb(array(select jsonb_array_elements((?)#>'{url}') ->> 'href' where jsonb_typeof((?)#>'{url}') = 'array'))::jsonb \\?| (?)",
108 # The query above can be time consumptive on large instances until we
109 # refactor how uploads are stored
110 |> Repo.all(timeout: :infinity)