1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2019 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"
15 %{"object" => %{"data" => %{"attachment" => [_ | _] = attachments, "actor" => actor}}},
19 Enum.flat_map(attachments, fn attachment ->
20 Enum.map(attachment["url"], & &1["href"])
23 names = Enum.map(attachments, & &1["name"])
25 uploader = Pleroma.Config.get([Pleroma.Upload, :uploader])
27 # find all objects for copies of the attachments, name and actor doesn't matter here
32 "to_jsonb(array(select jsonb_array_elements((?)#>'{url}') ->> 'href' where jsonb_typeof((?)#>'{url}') = 'array'))::jsonb \\?| (?)",
38 # The query above can be time consumptive on large instances until we
39 # refactor how uploads are stored
40 |> Repo.all(timout: :infinity)
41 # we should delete 1 object for any given attachment, but don't delete
42 # files if there are more than 1 object for it
43 |> Enum.reduce(%{}, fn %{
46 "url" => [%{"href" => href}],
52 Map.update(acc, href, %{id: id, count: 1}, fn val ->
53 case obj_actor == actor and name in names do
55 # set id of the actor's object that will be deleted
56 %{val | id: id, count: val.count + 1}
59 # another actor's object, just increase count to not delete file
60 %{val | count: val.count + 1}
64 |> Enum.map(fn {href, %{id: id, count: count}} ->
65 # only delete files that have single instance
68 case Pleroma.Config.get([Pleroma.Upload, :base_url]) do
73 base_url = Pleroma.Config.get([__MODULE__, :base_url], Pleroma.Web.base_url())
75 file_path = String.trim_leading(href, "#{base_url}/#{prefix}")
77 uploader.delete_file(file_path)
83 from(o in Object, where: o.id in ^delete_ids)
87 def perform(%{"object" => _object}, _job), do: :ok