f8239ece6a779f0e7f68e2f7e632843e94912755
[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 refactor how uploads are stored
39 |> Repo.all(timout: :infinity)
40 # we should delete 1 object for any given attachment, but don't delete files if
41 # there are more than 1 object for it
42 |> Enum.reduce(%{}, fn %{
43 id: id,
44 data: %{
45 "url" => [%{"href" => href}],
46 "actor" => obj_actor,
47 "name" => name
48 }
49 },
50 acc ->
51 Map.update(acc, href, %{id: id, count: 1}, fn val ->
52 case obj_actor == actor and name in names do
53 true ->
54 # set id of the actor's object that will be deleted
55 %{val | id: id, count: val.count + 1}
56
57 false ->
58 # another actor's object, just increase count to not delete file
59 %{val | count: val.count + 1}
60 end
61 end)
62 end)
63 |> Enum.map(fn {href, %{id: id, count: count}} ->
64 # only delete files that have single instance
65 with 1 <- count do
66 prefix =
67 case Pleroma.Config.get([Pleroma.Upload, :base_url]) do
68 nil -> "media"
69 _ -> ""
70 end
71
72 base_url = Pleroma.Config.get([__MODULE__, :base_url], Pleroma.Web.base_url())
73
74 file_path = String.trim_leading(href, "#{base_url}/#{prefix}")
75
76 uploader.delete_file(file_path)
77 end
78
79 id
80 end)
81
82 from(o in Object, where: o.id in ^delete_ids)
83 |> Repo.delete_all()
84 end
85
86 def perform(%{"object" => _object}, _job), do: :ok
87 end