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.ObjectTombstone
26 Object.change(%Object{}, %{data: data})
30 def change(struct, params \\ %{}) do
32 |> cast(params, [:data])
33 |> validate_required([:data])
34 |> unique_constraint(:ap_id, name: :objects_unique_apid_index)
37 def get_by_ap_id(nil), do: nil
39 def get_by_ap_id(ap_id) do
40 Repo.one(from(object in Object, where: fragment("(?)->>'id' = ?", object.data, ^ap_id)))
43 # If we pass an Activity to Object.normalize(), we can try to use the preloaded object.
44 # Use this whenever possible, especially when walking graphs in an O(N) loop!
45 def normalize(%Activity{object: %Object{} = object}), do: object
47 # Catch and log Object.normalize() calls where the Activity's child object is not
49 def normalize(%Activity{data: %{"object" => %{"id" => ap_id}}}) do
51 "Object.normalize() called without preloaded object (#{ap_id}). Consider preloading the object!"
57 def normalize(%Activity{data: %{"object" => ap_id}}) do
59 "Object.normalize() called without preloaded object (#{ap_id}). Consider preloading the object!"
65 # Old way, try fetching the object through cache.
66 def normalize(%{"id" => ap_id}), do: normalize(ap_id)
67 def normalize(ap_id) when is_binary(ap_id), do: get_cached_by_ap_id(ap_id)
68 def normalize(_), do: nil
70 # Owned objects can only be mutated by their owner
71 def authorize_mutation(%Object{data: %{"actor" => actor}}, %User{ap_id: ap_id}),
74 # Legacy objects can be mutated by anybody
75 def authorize_mutation(%Object{}, %User{}), do: true
77 def get_cached_by_ap_id(ap_id) do
78 key = "object:#{ap_id}"
80 Cachex.fetch!(:object_cache, key, fn _ ->
81 object = get_by_ap_id(ap_id)
91 def context_mapping(context) do
92 Object.change(%Object{}, %{data: %{"id" => context}})
95 def make_tombstone(%Object{data: %{"id" => id, "type" => type}}, deleted \\ DateTime.utc_now()) do
104 def swap_object_with_tombstone(object) do
105 tombstone = make_tombstone(object)
108 |> Object.change(%{data: tombstone})
112 def delete(%Object{data: %{"id" => id}} = object) do
113 with {:ok, _obj} = swap_object_with_tombstone(object),
114 deleted_activity = Activity.delete_by_ap_id(id),
115 {:ok, true} <- Cachex.del(:object_cache, "object:#{id}") do
116 {:ok, object, deleted_activity}
120 def set_cache(%Object{data: %{"id" => ap_id}} = object) do
121 Cachex.put(:object_cache, "object:#{ap_id}", object)
125 def update_and_set_cache(changeset) do
126 with {:ok, object} <- Repo.update(changeset) do