Merge branch 'develop' into csaurus/pleroma-feature/mstdn-direct-api
[akkoma] / lib / pleroma / object.ex
1 defmodule Pleroma.Object do
2 use Ecto.Schema
3 alias Pleroma.{Repo, Object}
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 get_cached_by_ap_id(ap_id) do
31 if Mix.env() == :test do
32 get_by_ap_id(ap_id)
33 else
34 key = "object:#{ap_id}"
35
36 Cachex.fetch!(:user_cache, key, fn _ ->
37 object = get_by_ap_id(ap_id)
38
39 if object do
40 {:commit, object}
41 else
42 {:ignore, object}
43 end
44 end)
45 end
46 end
47
48 def context_mapping(context) do
49 Object.change(%Object{}, %{data: %{"id" => context}})
50 end
51 end