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}
16 def insert_or_get(cng) do
17 {_, data} = fetch_field(cng, :data)
18 id = data["id"] || data[:id]
22 with nil <- get_by_ap_id(id),
23 {:ok, object} <- Repo.insert(cng) do
26 %Object{} = object -> {:commit, object}
31 with {state, object} when state in [:commit, :ok] <- Cachex.fetch(:object_cache, key, fetcher) do
37 Object.change(%Object{}, %{data: data})
41 def change(struct, params \\ %{}) do
43 |> cast(params, [:data])
44 |> validate_required([:data])
45 |> unique_constraint(:ap_id, name: :objects_unique_apid_index)
48 def get_by_ap_id(nil), do: nil
50 def get_by_ap_id(ap_id) do
51 Repo.one(from(object in Object, where: fragment("(?)->>'id' = ?", object.data, ^ap_id)))
54 def normalize(%{"id" => ap_id}), do: normalize(ap_id)
55 def normalize(ap_id) when is_binary(ap_id), do: get_cached_by_ap_id(ap_id)
56 def normalize(_), do: nil
58 # Owned objects can only be mutated by their owner
59 def authorize_mutation(%Object{data: %{"actor" => actor}}, %User{ap_id: ap_id}),
62 # Legacy objects can be mutated by anybody
63 def authorize_mutation(%Object{}, %User{}), do: true
65 def get_cached_by_ap_id(ap_id) do
66 key = "object:#{ap_id}"
68 Cachex.fetch!(:object_cache, key, fn _ ->
69 object = get_by_ap_id(ap_id)
79 def context_mapping(context) do
80 Object.change(%Object{}, %{data: %{"id" => context}})
83 def make_tombstone(%Object{data: %{"id" => id, "type" => type}}, deleted \\ DateTime.utc_now()) do
92 def swap_object_with_tombstone(object) do
93 tombstone = make_tombstone(object)
96 |> Object.change(%{data: tombstone})
100 def delete(%Object{data: %{"id" => id}} = object) do
101 with {:ok, _obj} = swap_object_with_tombstone(object),
102 Repo.delete_all(Activity.by_object_ap_id(id)),
103 {:ok, true} <- Cachex.del(:object_cache, "object:#{id}") do
108 def set_cache(%Object{data: %{"id" => ap_id}} = object) do
109 Cachex.put(:object_cache, "object:#{ap_id}", object)
113 def update_and_set_cache(changeset) do
114 with {:ok, object} <- Repo.update(changeset) do