1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2019 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
5 defmodule Pleroma.Object do
10 alias Pleroma.Object.Fetcher
11 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 def get_cached_by_ap_id(ap_id) do
149 key = "object:#{ap_id}"
151 Cachex.fetch!(:object_cache, key, fn _ ->
152 object = get_by_ap_id(ap_id)
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),
189 Pleroma.Workers.AttachmentsCleanupWorker.enqueue("cleanup_attachments", %{
192 {:ok, object, deleted_activity}
196 def prune(%Object{data: %{"id" => id}} = object) do
197 with {:ok, object} <- Repo.delete(object),
198 {:ok, true} <- Cachex.del(:object_cache, "object:#{id}"),
199 {:ok, _} <- Cachex.del(:web_resp_cache, URI.parse(id).path) do
204 def set_cache(%Object{data: %{"id" => ap_id}} = object) do
205 Cachex.put(:object_cache, "object:#{ap_id}", object)
209 def update_and_set_cache(changeset) do
210 with {:ok, object} <- Repo.update(changeset) do
215 def increase_replies_count(ap_id) do
217 |> where([o], fragment("?->>'id' = ?::text", o.data, ^to_string(ap_id)))
223 safe_jsonb_set(?, '{repliesCount}',
224 (coalesce((?->>'repliesCount')::int, 0) + 1)::varchar::jsonb, true)
231 |> Repo.update_all([])
233 {1, [object]} -> set_cache(object)
234 _ -> {:error, "Not found"}
238 def decrease_replies_count(ap_id) do
240 |> where([o], fragment("?->>'id' = ?::text", o.data, ^to_string(ap_id)))
246 safe_jsonb_set(?, '{repliesCount}',
247 (greatest(0, (?->>'repliesCount')::int - 1))::varchar::jsonb, true)
254 |> Repo.update_all([])
256 {1, [object]} -> set_cache(object)
257 _ -> {:error, "Not found"}
261 def increase_vote_count(ap_id, name) do
262 with %Object{} = object <- Object.normalize(ap_id),
263 "Question" <- object.data["type"] do
264 multiple = Map.has_key?(object.data, "anyOf")
267 (object.data["anyOf"] || object.data["oneOf"] || [])
269 %{"name" => ^name} = option ->
270 Kernel.update_in(option["replies"]["totalItems"], &(&1 + 1))
278 Map.put(object.data, "anyOf", options)
280 Map.put(object.data, "oneOf", options)
284 |> Object.change(%{data: data})
285 |> update_and_set_cache()
291 @doc "Updates data field of an object"
292 def update_data(%Object{data: data} = object, attrs \\ %{}) do
294 |> Object.change(%{data: Map.merge(data || %{}, attrs)})
298 def local?(%Object{data: %{"id" => id}}) do
299 String.starts_with?(id, Pleroma.Web.base_url() <> "/")