1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2021 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 "COALESCE(?->'object'->>'id', ?->>'object') = (? ->> 'id') AND (?->>'type' = ?) ",
56 |> Object.change(%{data: data})
60 def change(struct, params \\ %{}) do
62 |> cast(params, [:data])
63 |> validate_required([:data])
64 |> unique_constraint(:ap_id, name: :objects_unique_apid_index)
65 |> maybe_handle_hashtags_change(struct)
68 defp maybe_handle_hashtags_change(changeset, struct) do
69 with data_hashtags_change = get_change(changeset, :data),
70 true <- hashtags_changed?(struct, data_hashtags_change),
71 {:ok, hashtag_records} <-
73 |> object_data_hashtags()
74 |> Hashtag.get_or_create_by_names() do
75 put_assoc(changeset, :hashtags, hashtag_records)
80 {:error, hashtag_changeset} ->
81 failed_hashtag = get_field(hashtag_changeset, :name)
83 validate_change(changeset, :data, fn _, _ ->
84 [data: "error referencing hashtag: #{failed_hashtag}"]
89 defp hashtags_changed?(%Object{} = struct, %{"tag" => _} = data) do
90 Enum.sort(embedded_hashtags(struct)) !=
91 Enum.sort(object_data_hashtags(data))
94 defp hashtags_changed?(_, _), do: false
96 def get_by_id(nil), do: nil
97 def get_by_id(id), do: Repo.get(Object, id)
99 def get_by_id_and_maybe_refetch(id, opts \\ []) do
100 %{updated_at: updated_at} = object = get_by_id(id)
102 if opts[:interval] &&
103 NaiveDateTime.diff(NaiveDateTime.utc_now(), updated_at) > opts[:interval] do
104 case Fetcher.refetch_object(object) do
105 {:ok, %Object{} = object} ->
109 Logger.error("Couldn't refresh #{object.data["id"]}:\n#{inspect(e)}")
117 def get_by_ap_id(nil), do: nil
119 def get_by_ap_id(ap_id) do
120 Repo.one(from(object in Object, where: fragment("(?)->>'id' = ?", object.data, ^ap_id)))
124 Get a single attachment by it's name and href
126 @spec get_attachment_by_name_and_href(String.t(), String.t()) :: Object.t() | nil
127 def get_attachment_by_name_and_href(name, href) do
130 where: fragment("(?)->>'name' = ?", o.data, ^name),
131 where: fragment("(?)->>'href' = ?", o.data, ^href)
137 defp warn_on_no_object_preloaded(ap_id) do
138 "Object.normalize() called without preloaded object (#{inspect(ap_id)}). Consider preloading the object"
141 Logger.debug("Backtrace: #{inspect(Process.info(:erlang.self(), :current_stacktrace))}")
144 def normalize(_, options \\ [fetch: false])
146 # If we pass an Activity to Object.normalize(), we can try to use the preloaded object.
147 # Use this whenever possible, especially when walking graphs in an O(N) loop!
148 def normalize(%Object{} = object, _), do: object
149 def normalize(%Activity{object: %Object{} = object}, _), do: object
151 # A hack for fake activities
152 def normalize(%Activity{data: %{"object" => %{"fake" => true} = data}}, _) do
153 %Object{id: "pleroma:fake_object_id", data: data}
156 # No preloaded object
157 def normalize(%Activity{data: %{"object" => %{"id" => ap_id}}}, options) do
158 warn_on_no_object_preloaded(ap_id)
159 normalize(ap_id, options)
162 # No preloaded object
163 def normalize(%Activity{data: %{"object" => ap_id}}, options) do
164 warn_on_no_object_preloaded(ap_id)
165 normalize(ap_id, options)
168 # Old way, try fetching the object through cache.
169 def normalize(%{"id" => ap_id}, options), do: normalize(ap_id, options)
171 def normalize(ap_id, options) when is_binary(ap_id) do
172 if Keyword.get(options, :fetch) do
173 Fetcher.fetch_object_from_id!(ap_id, options)
175 get_cached_by_ap_id(ap_id)
179 def normalize(_, _), do: nil
181 # Owned objects can only be accessed by their owner
182 def authorize_access(%Object{data: %{"actor" => actor}}, %User{ap_id: ap_id}) do
190 # Legacy objects can be accessed by anybody
191 def authorize_access(%Object{}, %User{}), do: :ok
193 @spec get_cached_by_ap_id(String.t()) :: Object.t() | nil
194 def get_cached_by_ap_id(ap_id) do
195 key = "object:#{ap_id}"
197 with {:ok, nil} <- @cachex.get(:object_cache, key),
198 object when not is_nil(object) <- get_by_ap_id(ap_id),
199 {:ok, true} <- @cachex.put(:object_cache, key, object) do
202 {:ok, object} -> object
207 def context_mapping(context) do
208 Object.change(%Object{}, %{data: %{"id" => context}})
211 def make_tombstone(%Object{data: %{"id" => id, "type" => type}}, deleted \\ DateTime.utc_now()) do
220 def swap_object_with_tombstone(object) do
221 tombstone = make_tombstone(object)
224 |> Object.change(%{data: tombstone})
228 def delete(%Object{data: %{"id" => id}} = object) do
229 with {:ok, _obj} = swap_object_with_tombstone(object),
230 deleted_activity = Activity.delete_all_by_object_ap_id(id),
231 {:ok, _} <- invalid_object_cache(object) do
233 Config.get([:instance, :cleanup_attachments]),
234 %{"object" => object}
237 {:ok, object, deleted_activity}
241 @spec cleanup_attachments(boolean(), %{required(:object) => map()}) ::
242 {:ok, Oban.Job.t() | nil}
243 def cleanup_attachments(true, %{"object" => _} = params) do
244 AttachmentsCleanupWorker.enqueue("cleanup_attachments", params)
247 def cleanup_attachments(_, _), do: {:ok, nil}
249 def prune(%Object{data: %{"id" => _id}} = object) do
250 with {:ok, object} <- Repo.delete(object),
251 {:ok, _} <- invalid_object_cache(object) do
256 def invalid_object_cache(%Object{data: %{"id" => id}}) do
257 with {:ok, true} <- @cachex.del(:object_cache, "object:#{id}") do
258 @cachex.del(:web_resp_cache, URI.parse(id).path)
262 def set_cache(%Object{data: %{"id" => ap_id}} = object) do
263 @cachex.put(:object_cache, "object:#{ap_id}", object)
267 def update_and_set_cache(changeset) do
268 with {:ok, object} <- Repo.update(changeset) do
273 def increase_replies_count(ap_id) do
275 |> where([o], fragment("?->>'id' = ?::text", o.data, ^to_string(ap_id)))
281 safe_jsonb_set(?, '{repliesCount}',
282 (coalesce((?->>'repliesCount')::int, 0) + 1)::varchar::jsonb, true)
289 |> Repo.update_all([])
291 {1, [object]} -> set_cache(object)
292 _ -> {:error, "Not found"}
296 defp poll_is_multiple?(%Object{data: %{"anyOf" => [_ | _]}}), do: true
298 defp poll_is_multiple?(_), do: false
300 def decrease_replies_count(ap_id) do
302 |> where([o], fragment("?->>'id' = ?::text", o.data, ^to_string(ap_id)))
308 safe_jsonb_set(?, '{repliesCount}',
309 (greatest(0, (?->>'repliesCount')::int - 1))::varchar::jsonb, true)
316 |> Repo.update_all([])
318 {1, [object]} -> set_cache(object)
319 _ -> {:error, "Not found"}
323 def increase_vote_count(ap_id, name, actor) do
324 with %Object{} = object <- Object.normalize(ap_id, fetch: false),
325 "Question" <- object.data["type"] do
326 key = if poll_is_multiple?(object), do: "anyOf", else: "oneOf"
331 %{"name" => ^name} = option ->
332 Kernel.update_in(option["replies"]["totalItems"], &(&1 + 1))
338 voters = [actor | object.data["voters"] || []] |> Enum.uniq()
342 |> Map.put(key, options)
343 |> Map.put("voters", voters)
346 |> Object.change(%{data: data})
347 |> update_and_set_cache()
353 @doc "Updates data field of an object"
354 def update_data(%Object{data: data} = object, attrs \\ %{}) do
356 |> Object.change(%{data: Map.merge(data || %{}, attrs)})
360 def local?(%Object{data: %{"id" => id}}) do
361 String.starts_with?(id, Pleroma.Web.base_url() <> "/")
364 def replies(object, opts \\ []) do
365 object = Object.normalize(object, fetch: false)
371 fragment("(?)->>'inReplyTo' = ?", o.data, ^object.data["id"])
373 |> order_by([o], asc: o.id)
375 if opts[:self_only] do
376 actor = object.data["actor"]
377 where(query, [o], fragment("(?)->>'actor' = ?", o.data, ^actor))
383 def self_replies(object, opts \\ []),
384 do: replies(object, Keyword.put(opts, :self_only, true))
386 def tags(%Object{data: %{"tag" => tags}}) when is_list(tags), do: tags
390 def hashtags(%Object{} = object) do
392 Config.object_embedded_hashtags?() ->
393 embedded_hashtags(object)
395 object.id == "pleroma:fake_object_id" ->
399 hashtag_records = Repo.preload(object, :hashtags).hashtags
400 Enum.map(hashtag_records, & &1.name)
404 defp embedded_hashtags(%Object{data: data}) do
405 object_data_hashtags(data)
408 defp embedded_hashtags(_), do: []
410 def object_data_hashtags(%{"tag" => tags}) when is_list(tags) do
413 %{"type" => "Hashtag"} = data -> Map.has_key?(data, "name")
414 plain_text when is_bitstring(plain_text) -> true
418 %{"name" => "#" <> hashtag} -> String.downcase(hashtag)
419 %{"name" => hashtag} -> String.downcase(hashtag)
420 hashtag when is_bitstring(hashtag) -> String.downcase(hashtag)
425 def object_data_hashtags(_), do: []