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
11 alias Pleroma.Activity
12 alias Pleroma.ObjectTombstone
23 def insert_or_get(cng) do
24 {_, data} = fetch_field(cng, :data)
25 id = data["id"] || data[:id]
29 with nil <- get_by_ap_id(id),
30 {:ok, object} <- Repo.insert(cng) do
33 %Object{} = object -> {:commit, object}
38 with {state, object} when state in [:commit, :ok] <- Cachex.fetch(:object_cache, key, fetcher) do
44 Object.change(%Object{}, %{data: data})
48 def change(struct, params \\ %{}) do
50 |> cast(params, [:data])
51 |> validate_required([:data])
52 |> unique_constraint(:ap_id, name: :objects_unique_apid_index)
55 def get_by_ap_id(nil), do: nil
57 def get_by_ap_id(ap_id) do
58 Repo.one(from(object in Object, where: fragment("(?)->>'id' = ?", object.data, ^ap_id)))
61 def normalize(%{"id" => ap_id}), do: normalize(ap_id)
62 def normalize(ap_id) when is_binary(ap_id), do: get_cached_by_ap_id(ap_id)
63 def normalize(_), do: nil
65 # Owned objects can only be mutated by their owner
66 def authorize_mutation(%Object{data: %{"actor" => actor}}, %User{ap_id: ap_id}),
69 # Legacy objects can be mutated by anybody
70 def authorize_mutation(%Object{}, %User{}), do: true
72 def get_cached_by_ap_id(ap_id) do
73 key = "object:#{ap_id}"
75 Cachex.fetch!(:object_cache, key, fn _ ->
76 object = get_by_ap_id(ap_id)
86 def context_mapping(context) do
87 Object.change(%Object{}, %{data: %{"id" => context}})
90 def make_tombstone(%Object{data: %{"id" => id, "type" => type}}, deleted \\ DateTime.utc_now()) do
99 def swap_object_with_tombstone(object) do
100 tombstone = make_tombstone(object)
103 |> Object.change(%{data: tombstone})
107 def delete(%Object{data: %{"id" => id}} = object) do
108 with {:ok, _obj} = swap_object_with_tombstone(object),
109 Repo.delete_all(Activity.by_object_ap_id(id)),
110 {:ok, true} <- Cachex.del(:object_cache, "object:#{id}") do
115 def set_cache(%Object{data: %{"id" => ap_id}} = object) do
116 Cachex.put(:object_cache, "object:#{ap_id}", object)
120 def update_and_set_cache(changeset) do
121 with {:ok, object} <- Repo.update(changeset) do