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
7 alias Pleroma.{Repo, Object, User, Activity, ObjectTombstone}
8 import Ecto.{Query, Changeset}
17 Object.change(%Object{}, %{data: data})
21 def change(struct, params \\ %{}) do
23 |> cast(params, [:data])
24 |> validate_required([:data])
25 |> unique_constraint(:ap_id, name: :objects_unique_apid_index)
28 def get_by_ap_id(nil), do: nil
30 def get_by_ap_id(ap_id) do
31 Repo.one(from(object in Object, where: fragment("(?)->>'id' = ?", object.data, ^ap_id)))
34 def normalize(%{"id" => ap_id}), do: normalize(ap_id)
35 def normalize(ap_id) when is_binary(ap_id), do: get_cached_by_ap_id(ap_id)
36 def normalize(_), do: nil
38 # Owned objects can only be mutated by their owner
39 def authorize_mutation(%Object{data: %{"actor" => actor}}, %User{ap_id: ap_id}),
42 # Legacy objects can be mutated by anybody
43 def authorize_mutation(%Object{}, %User{}), do: true
45 def get_cached_by_ap_id(ap_id) do
46 key = "object:#{ap_id}"
48 Cachex.fetch!(:object_cache, key, fn _ ->
49 object = get_by_ap_id(ap_id)
59 def context_mapping(context) do
60 Object.change(%Object{}, %{data: %{"id" => context}})
63 def make_tombstone(%Object{data: %{"id" => id, "type" => type}}, deleted \\ DateTime.utc_now()) do
72 def swap_object_with_tombstone(object) do
73 tombstone = make_tombstone(object)
76 |> Object.change(%{data: tombstone})
80 def delete(%Object{data: %{"id" => id}} = object) do
81 with {:ok, _obj} = swap_object_with_tombstone(object),
82 Repo.delete_all(Activity.by_object_ap_id(id)),
83 {:ok, true} <- Cachex.del(:object_cache, "object:#{id}") do
88 def set_cache(%Object{data: %{"id" => ap_id}} = object) do
89 Cachex.put(:object_cache, "object:#{ap_id}", object)
93 def update_and_set_cache(changeset) do
94 with {:ok, object} <- Repo.update(changeset) do