1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
5 defmodule Pleroma.Object do
11 alias Pleroma.Activity
13 alias Pleroma.Object.Fetcher
14 alias Pleroma.ObjectTombstone
20 @type t() :: %__MODULE__{}
22 @derive {Jason.Encoder, only: [:data]}
30 def with_joined_activity(query, activity_type \\ "Create", join_type \\ :inner) do
31 object_position = Map.get(query.aliases, :object, 0)
33 join(query, join_type, [{object, object_position}], a in Activity,
36 "COALESCE(?->'object'->>'id', ?->>'object') = (? ->> 'id') AND (?->>'type' = ?) ",
48 Object.change(%Object{}, %{data: data})
52 def change(struct, params \\ %{}) do
54 |> cast(params, [:data])
55 |> validate_required([:data])
56 |> unique_constraint(:ap_id, name: :objects_unique_apid_index)
59 def get_by_id(nil), do: nil
60 def get_by_id(id), do: Repo.get(Object, id)
62 def get_by_id_and_maybe_refetch(id, opts \\ []) do
63 %{updated_at: updated_at} = object = get_by_id(id)
66 NaiveDateTime.diff(NaiveDateTime.utc_now(), updated_at) > opts[:interval] do
67 case Fetcher.refetch_object(object) do
68 {:ok, %Object{} = object} ->
72 Logger.error("Couldn't refresh #{object.data["id"]}:\n#{inspect(e)}")
80 def get_by_ap_id(nil), do: nil
82 def get_by_ap_id(ap_id) do
83 Repo.one(from(object in Object, where: fragment("(?)->>'id' = ?", object.data, ^ap_id)))
87 Get a single attachment by it's name and href
89 @spec get_attachment_by_name_and_href(String.t(), String.t()) :: Object.t() | nil
90 def get_attachment_by_name_and_href(name, href) do
93 where: fragment("(?)->>'name' = ?", o.data, ^name),
94 where: fragment("(?)->>'href' = ?", o.data, ^href)
100 defp warn_on_no_object_preloaded(ap_id) do
101 "Object.normalize() called without preloaded object (#{inspect(ap_id)}). Consider preloading the object"
104 Logger.debug("Backtrace: #{inspect(Process.info(:erlang.self(), :current_stacktrace))}")
107 def normalize(_, fetch_remote \\ true, options \\ [])
109 # If we pass an Activity to Object.normalize(), we can try to use the preloaded object.
110 # Use this whenever possible, especially when walking graphs in an O(N) loop!
111 def normalize(%Object{} = object, _, _), do: object
112 def normalize(%Activity{object: %Object{} = object}, _, _), do: object
114 # A hack for fake activities
115 def normalize(%Activity{data: %{"object" => %{"fake" => true} = data}}, _, _) do
116 %Object{id: "pleroma:fake_object_id", data: data}
119 # No preloaded object
120 def normalize(%Activity{data: %{"object" => %{"id" => ap_id}}}, fetch_remote, _) do
121 warn_on_no_object_preloaded(ap_id)
122 normalize(ap_id, fetch_remote)
125 # No preloaded object
126 def normalize(%Activity{data: %{"object" => ap_id}}, fetch_remote, _) do
127 warn_on_no_object_preloaded(ap_id)
128 normalize(ap_id, fetch_remote)
131 # Old way, try fetching the object through cache.
132 def normalize(%{"id" => ap_id}, fetch_remote, _), do: normalize(ap_id, fetch_remote)
133 def normalize(ap_id, false, _) when is_binary(ap_id), do: get_cached_by_ap_id(ap_id)
135 def normalize(ap_id, true, options) when is_binary(ap_id) do
136 Fetcher.fetch_object_from_id!(ap_id, options)
139 def normalize(_, _, _), do: nil
141 # Owned objects can only be mutated by their owner
142 def authorize_mutation(%Object{data: %{"actor" => actor}}, %User{ap_id: ap_id}),
145 # Legacy objects can be mutated by anybody
146 def authorize_mutation(%Object{}, %User{}), do: true
148 @spec get_cached_by_ap_id(String.t()) :: Object.t() | nil
149 def get_cached_by_ap_id(ap_id) do
150 key = "object:#{ap_id}"
152 with {:ok, nil} <- Cachex.get(:object_cache, key),
153 object when not is_nil(object) <- get_by_ap_id(ap_id),
154 {:ok, true} <- Cachex.put(:object_cache, key, object) do
157 {:ok, object} -> object
162 def context_mapping(context) do
163 Object.change(%Object{}, %{data: %{"id" => context}})
166 def make_tombstone(%Object{data: %{"id" => id, "type" => type}}, deleted \\ DateTime.utc_now()) do
175 def swap_object_with_tombstone(object) do
176 tombstone = make_tombstone(object)
179 |> Object.change(%{data: tombstone})
183 def delete(%Object{data: %{"id" => id}} = object) do
184 with {:ok, _obj} = swap_object_with_tombstone(object),
185 deleted_activity = Activity.delete_all_by_object_ap_id(id),
186 {:ok, true} <- Cachex.del(:object_cache, "object:#{id}"),
187 {:ok, _} <- Cachex.del(:web_resp_cache, URI.parse(id).path) do
188 with true <- Pleroma.Config.get([:instance, :cleanup_attachments]) do
190 Pleroma.Workers.AttachmentsCleanupWorker.enqueue("cleanup_attachments", %{
195 {:ok, object, deleted_activity}
199 def prune(%Object{data: %{"id" => id}} = object) do
200 with {:ok, object} <- Repo.delete(object),
201 {:ok, true} <- Cachex.del(:object_cache, "object:#{id}"),
202 {:ok, _} <- Cachex.del(:web_resp_cache, URI.parse(id).path) do
207 def set_cache(%Object{data: %{"id" => ap_id}} = object) do
208 Cachex.put(:object_cache, "object:#{ap_id}", object)
212 def update_and_set_cache(changeset) do
213 with {:ok, object} <- Repo.update(changeset) do
218 def increase_replies_count(ap_id) do
220 |> where([o], fragment("?->>'id' = ?::text", o.data, ^to_string(ap_id)))
226 safe_jsonb_set(?, '{repliesCount}',
227 (coalesce((?->>'repliesCount')::int, 0) + 1)::varchar::jsonb, true)
234 |> Repo.update_all([])
236 {1, [object]} -> set_cache(object)
237 _ -> {:error, "Not found"}
241 def decrease_replies_count(ap_id) do
243 |> where([o], fragment("?->>'id' = ?::text", o.data, ^to_string(ap_id)))
249 safe_jsonb_set(?, '{repliesCount}',
250 (greatest(0, (?->>'repliesCount')::int - 1))::varchar::jsonb, true)
257 |> Repo.update_all([])
259 {1, [object]} -> set_cache(object)
260 _ -> {:error, "Not found"}
264 def increase_vote_count(ap_id, name, actor) do
265 with %Object{} = object <- Object.normalize(ap_id),
266 "Question" <- object.data["type"] do
267 multiple = Map.has_key?(object.data, "anyOf")
270 (object.data["anyOf"] || object.data["oneOf"] || [])
272 %{"name" => ^name} = option ->
273 Kernel.update_in(option["replies"]["totalItems"], &(&1 + 1))
279 voters = [actor | object.data["voters"] || []] |> Enum.uniq()
283 Map.put(object.data, "anyOf", options)
285 Map.put(object.data, "oneOf", options)
287 |> Map.put("voters", voters)
290 |> Object.change(%{data: data})
291 |> update_and_set_cache()
297 @doc "Updates data field of an object"
298 def update_data(%Object{data: data} = object, attrs \\ %{}) do
300 |> Object.change(%{data: Map.merge(data || %{}, attrs)})
304 def local?(%Object{data: %{"id" => id}}) do
305 String.starts_with?(id, Pleroma.Web.base_url() <> "/")
308 def replies(object, opts \\ []) do
309 object = Object.normalize(object)
315 fragment("(?)->>'inReplyTo' = ?", o.data, ^object.data["id"])
317 |> order_by([o], asc: o.id)
319 if opts[:self_only] do
320 actor = object.data["actor"]
321 where(query, [o], fragment("(?)->>'actor' = ?", o.data, ^actor))
327 def self_replies(object, opts \\ []),
328 do: replies(object, Keyword.put(opts, :self_only, true))