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.AttachmentsCleanupWorker do
11 use Pleroma.Workers.WorkerHelper, queue: "attachments_cleanup"
16 "op" => "cleanup_attachments",
17 "object" => %{"data" => %{"attachment" => [_ | _] = attachments, "actor" => actor}}
22 Enum.flat_map(attachments, fn attachment ->
23 Enum.map(attachment["url"], & &1["href"])
26 names = Enum.map(attachments, & &1["name"])
28 uploader = Pleroma.Config.get([Pleroma.Upload, :uploader])
31 case Pleroma.Config.get([Pleroma.Upload, :base_url]) do
38 Pleroma.Config.get([Pleroma.Upload, :base_url], Pleroma.Web.base_url()),
42 # find all objects for copies of the attachments, name and actor doesn't matter here
43 object_ids_and_hrefs =
47 "to_jsonb(array(select jsonb_array_elements((?)#>'{url}') ->> 'href' where jsonb_typeof((?)#>'{url}') = 'array'))::jsonb \\?| (?)",
53 # The query above can be time consumptive on large instances until we
54 # refactor how uploads are stored
55 |> Repo.all(timeout: :infinity)
56 # we should delete 1 object for any given attachment, but don't delete
57 # files if there are more than 1 object for it
58 |> Enum.reduce(%{}, fn %{
61 "url" => [%{"href" => href}],
67 Map.update(acc, href, %{id: id, count: 1}, fn val ->
68 case obj_actor == actor and name in names do
70 # set id of the actor's object that will be deleted
71 %{val | id: id, count: val.count + 1}
74 # another actor's object, just increase count to not delete file
75 %{val | count: val.count + 1}
79 |> Enum.map(fn {href, %{id: id, count: count}} ->
80 # only delete files that have single instance
83 |> String.trim_leading("#{base_url}/#{prefix}")
84 |> uploader.delete_file()
92 object_ids = Enum.map(object_ids_and_hrefs, fn {id, _} -> id end)
94 from(o in Object, where: o.id in ^object_ids)
98 |> Enum.filter(fn {_, href} -> not is_nil(href) end)
99 |> Enum.map(&elem(&1, 1))
100 |> Pleroma.Web.MediaProxy.Invalidation.purge()
105 def perform(%{"op" => "cleanup_attachments", "object" => _object}, _job), do: {:ok, :skip}