1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2022 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
5 defmodule Pleroma.Object do
11 alias Pleroma.Activity
15 alias Pleroma.Object.Fetcher
16 alias Pleroma.ObjectTombstone
19 alias Pleroma.Workers.AttachmentsCleanupWorker
23 @type t() :: %__MODULE__{}
25 @derive {Jason.Encoder, only: [:data]}
27 @cachex Pleroma.Config.get([:cachex, :provider], Cachex)
32 many_to_many(:hashtags, Hashtag, join_through: "hashtags_objects", on_replace: :delete)
37 def with_joined_activity(query, activity_type \\ "Create", join_type \\ :inner) do
38 object_position = Map.get(query.aliases, :object, 0)
40 join(query, join_type, [{object, object_position}], a in Activity,
43 "associated_object_id(?) = (? ->> 'id') AND (?->>'type' = ?) ",
55 |> Object.change(%{data: data})
59 def change(struct, params \\ %{}) do
61 |> cast(params, [:data])
62 |> validate_required([:data])
63 |> unique_constraint(:ap_id, name: :objects_unique_apid_index)
64 # Expecting `maybe_handle_hashtags_change/1` to run last:
65 |> maybe_handle_hashtags_change(struct)
68 # Note: not checking activity type (assuming non-legacy objects are associated with Create act.)
69 defp maybe_handle_hashtags_change(changeset, struct) do
70 with %Ecto.Changeset{valid?: true} <- changeset,
71 data_hashtags_change = get_change(changeset, :data),
72 {_, true} <- {:changed, hashtags_changed?(struct, data_hashtags_change)},
73 {:ok, hashtag_records} <-
75 |> object_data_hashtags()
76 |> Hashtag.get_or_create_by_names() do
77 put_assoc(changeset, :hashtags, hashtag_records)
86 validate_change(changeset, :data, fn _, _ ->
87 [data: "error referencing hashtags"]
92 defp hashtags_changed?(%Object{} = struct, %{"tag" => _} = data) do
93 Enum.sort(embedded_hashtags(struct)) !=
94 Enum.sort(object_data_hashtags(data))
97 defp hashtags_changed?(_, _), do: false
99 def get_by_id(nil), do: nil
100 def get_by_id(id), do: Repo.get(Object, id)
102 def get_by_id_and_maybe_refetch(id, opts \\ []) do
103 %{updated_at: updated_at} = object = get_by_id(id)
105 if opts[:interval] &&
106 NaiveDateTime.diff(NaiveDateTime.utc_now(), updated_at) > opts[:interval] do
107 case Fetcher.refetch_object(object) do
108 {:ok, %Object{} = object} ->
112 Logger.error("Couldn't refresh #{object.data["id"]}:\n#{inspect(e)}")
120 def get_by_ap_id(nil), do: nil
122 def get_by_ap_id(ap_id) do
123 Repo.one(from(object in Object, where: fragment("(?)->>'id' = ?", object.data, ^ap_id)))
127 Get a single attachment by it's name and href
129 @spec get_attachment_by_name_and_href(String.t(), String.t()) :: Object.t() | nil
130 def get_attachment_by_name_and_href(name, href) do
133 where: fragment("(?)->>'name' = ?", o.data, ^name),
134 where: fragment("(?)->>'href' = ?", o.data, ^href)
140 defp warn_on_no_object_preloaded(ap_id) do
141 "Object.normalize() called without preloaded object (#{inspect(ap_id)}). Consider preloading the object"
144 Logger.debug("Backtrace: #{inspect(Process.info(:erlang.self(), :current_stacktrace))}")
147 def normalize(_, options \\ [fetch: false, id_only: false])
149 # If we pass an Activity to Object.normalize(), we can try to use the preloaded object.
150 # Use this whenever possible, especially when walking graphs in an O(N) loop!
151 def normalize(%Object{} = object, _), do: object
152 def normalize(%Activity{object: %Object{} = object}, _), do: object
154 # A hack for fake activities
155 def normalize(%Activity{data: %{"object" => %{"fake" => true} = data}}, _) do
156 %Object{id: "pleroma:fake_object_id", data: data}
159 # No preloaded object
160 def normalize(%Activity{data: %{"object" => %{"id" => ap_id}}}, options) do
161 warn_on_no_object_preloaded(ap_id)
162 normalize(ap_id, options)
165 # No preloaded object
166 def normalize(%Activity{data: %{"object" => ap_id}}, options) do
167 warn_on_no_object_preloaded(ap_id)
168 normalize(ap_id, options)
171 # Old way, try fetching the object through cache.
172 def normalize(%{"id" => ap_id}, options), do: normalize(ap_id, options)
174 def normalize(ap_id, options) when is_binary(ap_id) do
176 Keyword.get(options, :id_only) ->
179 Keyword.get(options, :fetch) ->
180 case Fetcher.fetch_object_from_id(ap_id, options) do
181 {:ok, object} -> object
186 get_cached_by_ap_id(ap_id)
190 def normalize(_, _), do: nil
192 # Owned objects can only be accessed by their owner
193 def authorize_access(%Object{data: %{"actor" => actor}}, %User{ap_id: ap_id}) do
201 # Legacy objects can be accessed by anybody
202 def authorize_access(%Object{}, %User{}), do: :ok
204 @spec get_cached_by_ap_id(String.t()) :: Object.t() | nil
205 def get_cached_by_ap_id(ap_id) do
206 key = "object:#{ap_id}"
208 with {:ok, nil} <- @cachex.get(:object_cache, key),
209 object when not is_nil(object) <- get_by_ap_id(ap_id),
210 {:ok, true} <- @cachex.put(:object_cache, key, object) do
213 {:ok, object} -> object
218 def make_tombstone(%Object{data: %{"id" => id, "type" => type}}, deleted \\ DateTime.utc_now()) do
227 def swap_object_with_tombstone(object) do
228 tombstone = make_tombstone(object)
230 with {:ok, object} <-
232 |> Object.change(%{data: tombstone})
234 Hashtag.unlink(object)
239 def delete(%Object{data: %{"id" => id}} = object) do
240 with {:ok, _obj} = swap_object_with_tombstone(object),
241 deleted_activity = Activity.delete_all_by_object_ap_id(id),
242 {:ok, _} <- invalid_object_cache(object) do
244 Config.get([:instance, :cleanup_attachments]),
248 {:ok, object, deleted_activity}
252 @spec cleanup_attachments(boolean(), Object.t()) ::
253 {:ok, Oban.Job.t() | nil}
254 def cleanup_attachments(true, %Object{} = object) do
255 AttachmentsCleanupWorker.enqueue("cleanup_attachments", %{"object" => object})
258 def cleanup_attachments(_, _), do: {:ok, nil}
260 def prune(%Object{data: %{"id" => _id}} = object) do
261 with {:ok, object} <- Repo.delete(object),
262 {:ok, _} <- invalid_object_cache(object) do
267 def invalid_object_cache(%Object{data: %{"id" => id}}) do
268 with {:ok, true} <- @cachex.del(:object_cache, "object:#{id}") do
269 @cachex.del(:web_resp_cache, URI.parse(id).path)
273 def set_cache(%Object{data: %{"id" => ap_id}} = object) do
274 @cachex.put(:object_cache, "object:#{ap_id}", object)
278 def update_and_set_cache(changeset) do
279 with {:ok, object} <- Repo.update(changeset) do
284 def increase_replies_count(ap_id) do
286 |> where([o], fragment("?->>'id' = ?::text", o.data, ^to_string(ap_id)))
292 safe_jsonb_set(?, '{repliesCount}',
293 (coalesce((?->>'repliesCount')::int, 0) + 1)::varchar::jsonb, true)
300 |> Repo.update_all([])
302 {1, [object]} -> set_cache(object)
303 _ -> {:error, "Not found"}
307 defp poll_is_multiple?(%Object{data: %{"anyOf" => [_ | _]}}), do: true
309 defp poll_is_multiple?(_), do: false
311 def decrease_replies_count(ap_id) do
313 |> where([o], fragment("?->>'id' = ?::text", o.data, ^to_string(ap_id)))
319 safe_jsonb_set(?, '{repliesCount}',
320 (greatest(0, (?->>'repliesCount')::int - 1))::varchar::jsonb, true)
327 |> Repo.update_all([])
329 {1, [object]} -> set_cache(object)
330 _ -> {:error, "Not found"}
334 def increase_quotes_count(ap_id) do
336 |> where([o], fragment("?->>'id' = ?::text", o.data, ^to_string(ap_id)))
342 safe_jsonb_set(?, '{quotesCount}',
343 (coalesce((?->>'quotesCount')::int, 0) + 1)::varchar::jsonb, true)
350 |> Repo.update_all([])
352 {1, [object]} -> set_cache(object)
353 _ -> {:error, "Not found"}
357 def decrease_quotes_count(ap_id) do
359 |> where([o], fragment("?->>'id' = ?::text", o.data, ^to_string(ap_id)))
365 safe_jsonb_set(?, '{quotesCount}',
366 (greatest(0, (?->>'quotesCount')::int - 1))::varchar::jsonb, true)
373 |> Repo.update_all([])
375 {1, [object]} -> set_cache(object)
376 _ -> {:error, "Not found"}
380 def increase_vote_count(ap_id, name, actor) do
381 with %Object{} = object <- Object.normalize(ap_id, fetch: false),
382 "Question" <- object.data["type"] do
383 key = if poll_is_multiple?(object), do: "anyOf", else: "oneOf"
388 %{"name" => ^name} = option ->
389 Kernel.update_in(option["replies"]["totalItems"], &(&1 + 1))
395 voters = [actor | object.data["voters"] || []] |> Enum.uniq()
399 |> Map.put(key, options)
400 |> Map.put("voters", voters)
403 |> Object.change(%{data: data})
404 |> update_and_set_cache()
410 @doc "Updates data field of an object"
411 def update_data(%Object{data: data} = object, attrs \\ %{}) do
413 |> Object.change(%{data: Map.merge(data || %{}, attrs)})
417 def local?(%Object{data: %{"id" => id}}) do
418 String.starts_with?(id, Pleroma.Web.Endpoint.url() <> "/")
421 def replies(object, opts \\ []) do
422 object = Object.normalize(object, fetch: false)
428 fragment("(?)->>'inReplyTo' = ?", o.data, ^object.data["id"])
430 |> order_by([o], asc: o.id)
432 if opts[:self_only] do
433 actor = object.data["actor"]
434 where(query, [o], fragment("(?)->>'actor' = ?", o.data, ^actor))
440 def self_replies(object, opts \\ []),
441 do: replies(object, Keyword.put(opts, :self_only, true))
443 def tags(%Object{data: %{"tag" => tags}}) when is_list(tags), do: tags
447 def hashtags(%Object{} = object) do
448 # Note: always using embedded hashtags regardless whether they are migrated to hashtags table
449 # (embedded hashtags stay in sync anyways, and we avoid extra joins and preload hassle)
450 embedded_hashtags(object)
453 def embedded_hashtags(%Object{data: data}) do
454 object_data_hashtags(data)
457 def embedded_hashtags(_), do: []
459 def object_data_hashtags(%{"tag" => tags}) when is_list(tags) do
462 %{"type" => "Hashtag"} = data -> Map.has_key?(data, "name")
463 plain_text when is_bitstring(plain_text) -> true
467 %{"name" => "#" <> hashtag} -> String.downcase(hashtag)
468 %{"name" => hashtag} -> String.downcase(hashtag)
469 hashtag when is_bitstring(hashtag) -> String.downcase(hashtag)
472 # Note: "" elements (plain text) might occur in `data.tag` for incoming objects
473 |> Enum.filter(&(&1 not in [nil, ""]))
476 def object_data_hashtags(_), do: []
478 def get_emoji_reactions(object) do
479 reactions = object.data["reactions"]
481 if is_list(reactions) or is_map(reactions) do
484 [_emoji, users, _maybe_url] = item when is_list(users) ->
487 [emoji, users] when is_list(users) ->
490 # This case is here to process the Map situation, which will happen
491 # only with the legacy two-value format.
492 {emoji, users} when is_list(users) ->
498 |> Enum.reject(&is_nil/1)