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