Merge branch 'translation/errors-french' into 'develop'
[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 %{
16 "op" => "cleanup_attachments",
17 "object" => %{"data" => %{"attachment" => [_ | _] = attachments, "actor" => actor}}
18 },
19 _job
20 ) do
21 hrefs =
22 Enum.flat_map(attachments, fn attachment ->
23 Enum.map(attachment["url"], & &1["href"])
24 end)
25
26 names = Enum.map(attachments, & &1["name"])
27
28 uploader = Pleroma.Config.get([Pleroma.Upload, :uploader])
29
30 # find all objects for copies of the attachments, name and actor doesn't matter here
31 delete_ids =
32 from(o in Object,
33 where:
34 fragment(
35 "to_jsonb(array(select jsonb_array_elements((?)#>'{url}') ->> 'href' where jsonb_typeof((?)#>'{url}') = 'array'))::jsonb \\?| (?)",
36 o.data,
37 o.data,
38 ^hrefs
39 )
40 )
41 # The query above can be time consumptive on large instances until we
42 # refactor how uploads are stored
43 |> Repo.all(timeout: :infinity)
44 # we should delete 1 object for any given attachment, but don't delete
45 # files if there are more than 1 object for it
46 |> Enum.reduce(%{}, fn %{
47 id: id,
48 data: %{
49 "url" => [%{"href" => href}],
50 "actor" => obj_actor,
51 "name" => name
52 }
53 },
54 acc ->
55 Map.update(acc, href, %{id: id, count: 1}, fn val ->
56 case obj_actor == actor and name in names do
57 true ->
58 # set id of the actor's object that will be deleted
59 %{val | id: id, count: val.count + 1}
60
61 false ->
62 # another actor's object, just increase count to not delete file
63 %{val | count: val.count + 1}
64 end
65 end)
66 end)
67 |> Enum.map(fn {href, %{id: id, count: count}} ->
68 # only delete files that have single instance
69 with 1 <- count do
70 prefix =
71 case Pleroma.Config.get([Pleroma.Upload, :base_url]) do
72 nil -> "media"
73 _ -> ""
74 end
75
76 base_url = Pleroma.Config.get([__MODULE__, :base_url], Pleroma.Web.base_url())
77
78 file_path = String.trim_leading(href, "#{base_url}/#{prefix}")
79
80 uploader.delete_file(file_path)
81 end
82
83 id
84 end)
85
86 from(o in Object, where: o.id in ^delete_ids)
87 |> Repo.delete_all()
88 end
89
90 def perform(%{"op" => "cleanup_attachments", "object" => _object}, _job), do: :ok
91 end