formatting
[akkoma] / lib / pleroma / object.ex
1 defmodule Pleroma.Object do
2 use Ecto.Schema
3 alias Pleroma.{Repo, Object, Activity}
4 alias Pleroma.Object.Fetcher
5 import Ecto.{Query, Changeset}
6
7 schema "objects" do
8 field(:data, :map)
9
10 timestamps()
11 end
12
13 def create(data) do
14 Object.change(%Object{}, %{data: data})
15 |> Repo.insert()
16 end
17
18 def change(struct, params \\ %{}) do
19 struct
20 |> cast(params, [:data])
21 |> validate_required([:data])
22 |> unique_constraint(:ap_id, name: :objects_unique_apid_index)
23 end
24
25 def get_by_ap_id(nil), do: nil
26
27 def get_by_ap_id(ap_id) do
28 Repo.one(from(object in Object, where: fragment("(?)->>'id' = ?", object.data, ^ap_id)))
29 end
30
31 def normalize(_, fetch_remote \\ true)
32
33 def normalize(obj, fetch_remote) when is_map(obj), do: normalize(obj["id"], fetch_remote)
34 def normalize(ap_id, true) when is_binary(ap_id), do: Fetcher.fetch_object_from_id!(ap_id)
35 def normalize(ap_id, false) when is_binary(ap_id), do: get_cached_by_ap_id(ap_id)
36 def normalize(obj, _), do: nil
37
38 if Mix.env() == :test do
39 def get_cached_by_ap_id(ap_id) do
40 get_by_ap_id(ap_id)
41 end
42 else
43 def get_cached_by_ap_id(ap_id) do
44 key = "object:#{ap_id}"
45
46 Cachex.fetch!(:object_cache, key, fn _ ->
47 object = get_by_ap_id(ap_id)
48
49 if object do
50 {:commit, object}
51 else
52 {:ignore, object}
53 end
54 end)
55 end
56 end
57
58 def context_mapping(context) do
59 Object.change(%Object{}, %{data: %{"id" => context}})
60 end
61
62 def delete(%Object{data: %{"id" => id}} = object) do
63 with Repo.delete(object),
64 Repo.delete_all(Activity.all_non_create_by_object_ap_id_q(id)),
65 {:ok, true} <- Cachex.del(:object_cache, "object:#{id}") do
66 {:ok, object}
67 end
68 end
69 end