FE
[akkoma] / lib / pleroma / workers / attachments_cleanup_worker.ex
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2019 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
4
5 defmodule Pleroma.Workers.AttachmentsCleanupWorker do
6 import Ecto.Query
7
8 alias Pleroma.Object
9 alias Pleroma.Repo
10
11 use Pleroma.Workers.WorkerHelper, queue: "attachments_cleanup"
12
13 @impl Oban.Worker
14 def perform(
15 %{"object" => %{"data" => %{"attachment" => [_ | _] = attachments, "actor" => actor}}},
16 _job
17 ) do
18 hrefs =
19 Enum.flat_map(attachments, fn attachment ->
20 Enum.map(attachment["url"], & &1["href"])
21 end)
22
23 names = Enum.map(attachments, & &1["name"])
24
25 uploader = Pleroma.Config.get([Pleroma.Upload, :uploader])
26
27 # find all objects for copies of the attachments, name and actor doesn't matter here
28 delete_ids =
29 from(o in Object,
30 where:
31 fragment(
32 "to_jsonb(array(select jsonb_array_elements((?)#>'{url}') ->> 'href' where jsonb_typeof((?)#>'{url}') = 'array'))::jsonb \\?| (?)",
33 o.data,
34 o.data,
35 ^hrefs
36 )
37 )
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 %{
44 id: id,
45 data: %{
46 "url" => [%{"href" => href}],
47 "actor" => obj_actor,
48 "name" => name
49 }
50 },
51 acc ->
52 Map.update(acc, href, %{id: id, count: 1}, fn val ->
53 case obj_actor == actor and name in names do
54 true ->
55 # set id of the actor's object that will be deleted
56 %{val | id: id, count: val.count + 1}
57
58 false ->
59 # another actor's object, just increase count to not delete file
60 %{val | count: val.count + 1}
61 end
62 end)
63 end)
64 |> Enum.map(fn {href, %{id: id, count: count}} ->
65 # only delete files that have single instance
66 with 1 <- count do
67 prefix =
68 case Pleroma.Config.get([Pleroma.Upload, :base_url]) do
69 nil -> "media"
70 _ -> ""
71 end
72
73 base_url = Pleroma.Config.get([__MODULE__, :base_url], Pleroma.Web.base_url())
74
75 file_path = String.trim_leading(href, "#{base_url}/#{prefix}")
76
77 uploader.delete_file(file_path)
78 end
79
80 id
81 end)
82
83 from(o in Object, where: o.id in ^delete_ids)
84 |> Repo.delete_all()
85 end
86
87 def perform(%{"object" => _object}, _job), do: :ok
88 end