Merge branch 'develop' into admin-be
[akkoma] / lib / pleroma / object.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.Object do
6 use Ecto.Schema
7
8 alias Pleroma.Activity
9 alias Pleroma.Object
10 alias Pleroma.Object.Fetcher
11 alias Pleroma.ObjectTombstone
12 alias Pleroma.Repo
13 alias Pleroma.User
14
15 import Ecto.Query
16 import Ecto.Changeset
17
18 require Logger
19
20 @type t() :: %__MODULE__{}
21
22 schema "objects" do
23 field(:data, :map)
24
25 timestamps()
26 end
27
28 def with_joined_activity(query, activity_type \\ "Create", join_type \\ :inner) do
29 object_position = Map.get(query.aliases, :object, 0)
30
31 join(query, join_type, [{object, object_position}], a in Activity,
32 on:
33 fragment(
34 "COALESCE(?->'object'->>'id', ?->>'object') = (? ->> 'id') AND (?->>'type' = ?) ",
35 a.data,
36 a.data,
37 object.data,
38 a.data,
39 ^activity_type
40 ),
41 as: :object_activity
42 )
43 end
44
45 def create(data) do
46 Object.change(%Object{}, %{data: data})
47 |> Repo.insert()
48 end
49
50 def change(struct, params \\ %{}) do
51 struct
52 |> cast(params, [:data])
53 |> validate_required([:data])
54 |> unique_constraint(:ap_id, name: :objects_unique_apid_index)
55 end
56
57 def get_by_id(nil), do: nil
58 def get_by_id(id), do: Repo.get(Object, id)
59
60 def get_by_id_and_maybe_refetch(id, opts \\ []) do
61 %{updated_at: updated_at} = object = get_by_id(id)
62
63 if opts[:interval] &&
64 NaiveDateTime.diff(NaiveDateTime.utc_now(), updated_at) > opts[:interval] do
65 case Fetcher.refetch_object(object) do
66 {:ok, %Object{} = object} ->
67 object
68
69 e ->
70 Logger.error("Couldn't refresh #{object.data["id"]}:\n#{inspect(e)}")
71 object
72 end
73 else
74 object
75 end
76 end
77
78 def get_by_ap_id(nil), do: nil
79
80 def get_by_ap_id(ap_id) do
81 Repo.one(from(object in Object, where: fragment("(?)->>'id' = ?", object.data, ^ap_id)))
82 end
83
84 @doc """
85 Get a single attachment by it's name and href
86 """
87 @spec get_attachment_by_name_and_href(String.t(), String.t()) :: Object.t() | nil
88 def get_attachment_by_name_and_href(name, href) do
89 query =
90 from(o in Object,
91 where: fragment("(?)->>'name' = ?", o.data, ^name),
92 where: fragment("(?)->>'href' = ?", o.data, ^href)
93 )
94
95 Repo.one(query)
96 end
97
98 defp warn_on_no_object_preloaded(ap_id) do
99 "Object.normalize() called without preloaded object (#{inspect(ap_id)}). Consider preloading the object"
100 |> Logger.debug()
101
102 Logger.debug("Backtrace: #{inspect(Process.info(:erlang.self(), :current_stacktrace))}")
103 end
104
105 def normalize(_, fetch_remote \\ true, options \\ [])
106
107 # If we pass an Activity to Object.normalize(), we can try to use the preloaded object.
108 # Use this whenever possible, especially when walking graphs in an O(N) loop!
109 def normalize(%Object{} = object, _, _), do: object
110 def normalize(%Activity{object: %Object{} = object}, _, _), do: object
111
112 # A hack for fake activities
113 def normalize(%Activity{data: %{"object" => %{"fake" => true} = data}}, _, _) do
114 %Object{id: "pleroma:fake_object_id", data: data}
115 end
116
117 # No preloaded object
118 def normalize(%Activity{data: %{"object" => %{"id" => ap_id}}}, fetch_remote, _) do
119 warn_on_no_object_preloaded(ap_id)
120 normalize(ap_id, fetch_remote)
121 end
122
123 # No preloaded object
124 def normalize(%Activity{data: %{"object" => ap_id}}, fetch_remote, _) do
125 warn_on_no_object_preloaded(ap_id)
126 normalize(ap_id, fetch_remote)
127 end
128
129 # Old way, try fetching the object through cache.
130 def normalize(%{"id" => ap_id}, fetch_remote, _), do: normalize(ap_id, fetch_remote)
131 def normalize(ap_id, false, _) when is_binary(ap_id), do: get_cached_by_ap_id(ap_id)
132
133 def normalize(ap_id, true, options) when is_binary(ap_id) do
134 Fetcher.fetch_object_from_id!(ap_id, options)
135 end
136
137 def normalize(_, _, _), do: nil
138
139 # Owned objects can only be mutated by their owner
140 def authorize_mutation(%Object{data: %{"actor" => actor}}, %User{ap_id: ap_id}),
141 do: actor == ap_id
142
143 # Legacy objects can be mutated by anybody
144 def authorize_mutation(%Object{}, %User{}), do: true
145
146 def get_cached_by_ap_id(ap_id) do
147 key = "object:#{ap_id}"
148
149 Cachex.fetch!(:object_cache, key, fn _ ->
150 object = get_by_ap_id(ap_id)
151
152 if object do
153 {:commit, object}
154 else
155 {:ignore, object}
156 end
157 end)
158 end
159
160 def context_mapping(context) do
161 Object.change(%Object{}, %{data: %{"id" => context}})
162 end
163
164 def make_tombstone(%Object{data: %{"id" => id, "type" => type}}, deleted \\ DateTime.utc_now()) do
165 %ObjectTombstone{
166 id: id,
167 formerType: type,
168 deleted: deleted
169 }
170 |> Map.from_struct()
171 end
172
173 def swap_object_with_tombstone(object) do
174 tombstone = make_tombstone(object)
175
176 object
177 |> Object.change(%{data: tombstone})
178 |> Repo.update()
179 end
180
181 def delete(%Object{data: %{"id" => id}} = object) do
182 with {:ok, _obj} = swap_object_with_tombstone(object),
183 :ok <- delete_attachments(object),
184 deleted_activity = Activity.delete_all_by_object_ap_id(id),
185 {:ok, true} <- Cachex.del(:object_cache, "object:#{id}"),
186 {:ok, _} <- Cachex.del(:web_resp_cache, URI.parse(id).path) do
187 {:ok, object, deleted_activity}
188 end
189 end
190
191 defp delete_attachments(%{data: %{"attachment" => [_ | _] = attachments, "actor" => actor}}) do
192 hrefs =
193 Enum.flat_map(attachments, fn attachment ->
194 Enum.map(attachment["url"], & &1["href"])
195 end)
196
197 names = Enum.map(attachments, & &1["name"])
198
199 uploader = Pleroma.Config.get([Pleroma.Upload, :uploader])
200
201 # find all objects for copies of the attachments, name and actor doesn't matter here
202 delete_ids =
203 from(o in Object,
204 where:
205 fragment(
206 "to_jsonb(array(select jsonb_array_elements((?)#>'{url}') ->> 'href'))::jsonb \\?| (?)",
207 o.data,
208 ^hrefs
209 )
210 )
211 |> Repo.all()
212 # we should delete 1 object for any given attachment, but don't delete files if
213 # there are more than 1 object for it
214 |> Enum.reduce(%{}, fn %{
215 id: id,
216 data: %{
217 "url" => [%{"href" => href}],
218 "actor" => obj_actor,
219 "name" => name
220 }
221 },
222 acc ->
223 Map.update(acc, href, %{id: id, count: 1}, fn val ->
224 case obj_actor == actor and name in names do
225 true ->
226 # set id of the actor's object that will be deleted
227 %{val | id: id, count: val.count + 1}
228
229 false ->
230 # another actor's object, just increase count to not delete file
231 %{val | count: val.count + 1}
232 end
233 end)
234 end)
235 |> Enum.map(fn {href, %{id: id, count: count}} ->
236 # only delete files that have single instance
237 with 1 <- count do
238 prefix =
239 case Pleroma.Config.get([Pleroma.Upload, :base_url]) do
240 nil -> "media"
241 _ -> ""
242 end
243
244 base_url = Pleroma.Config.get([__MODULE__, :base_url], Pleroma.Web.base_url())
245
246 file_path = String.trim_leading(href, "#{base_url}/#{prefix}")
247
248 uploader.delete_file(file_path)
249 end
250
251 id
252 end)
253
254 from(o in Object, where: o.id in ^delete_ids)
255 |> Repo.delete_all()
256
257 :ok
258 end
259
260 defp delete_attachments(%{data: _data}), do: :ok
261
262 def prune(%Object{data: %{"id" => id}} = object) do
263 with {:ok, object} <- Repo.delete(object),
264 {:ok, true} <- Cachex.del(:object_cache, "object:#{id}"),
265 {:ok, _} <- Cachex.del(:web_resp_cache, URI.parse(id).path) do
266 {:ok, object}
267 end
268 end
269
270 def set_cache(%Object{data: %{"id" => ap_id}} = object) do
271 Cachex.put(:object_cache, "object:#{ap_id}", object)
272 {:ok, object}
273 end
274
275 def update_and_set_cache(changeset) do
276 with {:ok, object} <- Repo.update(changeset) do
277 set_cache(object)
278 end
279 end
280
281 def increase_replies_count(ap_id) do
282 Object
283 |> where([o], fragment("?->>'id' = ?::text", o.data, ^to_string(ap_id)))
284 |> update([o],
285 set: [
286 data:
287 fragment(
288 """
289 safe_jsonb_set(?, '{repliesCount}',
290 (coalesce((?->>'repliesCount')::int, 0) + 1)::varchar::jsonb, true)
291 """,
292 o.data,
293 o.data
294 )
295 ]
296 )
297 |> Repo.update_all([])
298 |> case do
299 {1, [object]} -> set_cache(object)
300 _ -> {:error, "Not found"}
301 end
302 end
303
304 def decrease_replies_count(ap_id) do
305 Object
306 |> where([o], fragment("?->>'id' = ?::text", o.data, ^to_string(ap_id)))
307 |> update([o],
308 set: [
309 data:
310 fragment(
311 """
312 safe_jsonb_set(?, '{repliesCount}',
313 (greatest(0, (?->>'repliesCount')::int - 1))::varchar::jsonb, true)
314 """,
315 o.data,
316 o.data
317 )
318 ]
319 )
320 |> Repo.update_all([])
321 |> case do
322 {1, [object]} -> set_cache(object)
323 _ -> {:error, "Not found"}
324 end
325 end
326
327 def increase_vote_count(ap_id, name) do
328 with %Object{} = object <- Object.normalize(ap_id),
329 "Question" <- object.data["type"] do
330 multiple = Map.has_key?(object.data, "anyOf")
331
332 options =
333 (object.data["anyOf"] || object.data["oneOf"] || [])
334 |> Enum.map(fn
335 %{"name" => ^name} = option ->
336 Kernel.update_in(option["replies"]["totalItems"], &(&1 + 1))
337
338 option ->
339 option
340 end)
341
342 data =
343 if multiple do
344 Map.put(object.data, "anyOf", options)
345 else
346 Map.put(object.data, "oneOf", options)
347 end
348
349 object
350 |> Object.change(%{data: data})
351 |> update_and_set_cache()
352 else
353 _ -> :noop
354 end
355 end
356
357 @doc "Updates data field of an object"
358 def update_data(%Object{data: data} = object, attrs \\ %{}) do
359 object
360 |> Object.change(%{data: Map.merge(data || %{}, attrs)})
361 |> Repo.update()
362 end
363
364 def local?(%Object{data: %{"id" => id}}) do
365 String.starts_with?(id, Pleroma.Web.base_url() <> "/")
366 end
367 end