+
+ def make_tombstone(%Object{data: %{"id" => id, "type" => type}}, deleted \\ DateTime.utc_now()) do
+ %ObjectTombstone{
+ id: id,
+ formerType: type,
+ deleted: deleted
+ }
+ |> Map.from_struct()
+ end
+
+ def swap_object_with_tombstone(object) do
+ tombstone = make_tombstone(object)
+
+ object
+ |> Object.change(%{data: tombstone})
+ |> Repo.update()
+ end
+
+ def delete(%Object{data: %{"id" => id}} = object) do
+ with {:ok, _obj} = swap_object_with_tombstone(object),
+ deleted_activity = Activity.delete_by_ap_id(id),
+ {:ok, true} <- Cachex.del(:object_cache, "object:#{id}") do
+ {:ok, object, deleted_activity}
+ end
+ end
+
+ def set_cache(%Object{data: %{"id" => ap_id}} = object) do
+ Cachex.put(:object_cache, "object:#{ap_id}", object)
+ {:ok, object}
+ end
+
+ def update_and_set_cache(changeset) do
+ with {:ok, object} <- Repo.update(changeset) do
+ set_cache(object)
+ else
+ e -> e
+ end
+ end
+
+ def increase_replies_count(ap_id) do
+ Object
+ |> where([o], fragment("?->>'id' = ?::text", o.data, ^to_string(ap_id)))
+ |> update([o],
+ set: [
+ data:
+ fragment(
+ """
+ jsonb_set(?, '{repliesCount}',
+ (coalesce((?->>'repliesCount')::int, 0) + 1)::varchar::jsonb, true)
+ """,
+ o.data,
+ o.data
+ )
+ ]
+ )
+ |> Repo.update_all([])
+ |> case do
+ {1, [object]} -> set_cache(object)
+ _ -> {:error, "Not found"}
+ end
+ end
+
+ def decrease_replies_count(ap_id) do
+ Object
+ |> where([o], fragment("?->>'id' = ?::text", o.data, ^to_string(ap_id)))
+ |> update([o],
+ set: [
+ data:
+ fragment(
+ """
+ jsonb_set(?, '{repliesCount}',
+ (greatest(0, (?->>'repliesCount')::int - 1))::varchar::jsonb, true)
+ """,
+ o.data,
+ o.data
+ )
+ ]
+ )
+ |> Repo.update_all([])
+ |> case do
+ {1, [object]} -> set_cache(object)
+ _ -> {:error, "Not found"}
+ end
+ end