object.ex 1.48 KB
Newer Older
lain's avatar
lain committed
1
2
defmodule Pleroma.Object do
  use Ecto.Schema
3
  alias Pleroma.{Repo, Object, Activity}
lain's avatar
lain committed
4
  import Ecto.{Query, Changeset}
lain's avatar
lain committed
5
6

  schema "objects" do
lain's avatar
lain committed
7
    field(:data, :map)
lain's avatar
lain committed
8
9
10

    timestamps()
  end
11

lain's avatar
lain committed
12
13
  def create(data) do
    Object.change(%Object{}, %{data: data})
lain's avatar
lain committed
14
    |> Repo.insert()
lain's avatar
lain committed
15
16
  end

lain's avatar
lain committed
17
  def change(struct, params \\ %{}) do
Thog's avatar
Thog committed
18
    struct
lain's avatar
lain committed
19
20
21
22
23
    |> cast(params, [:data])
    |> validate_required([:data])
    |> unique_constraint(:ap_id, name: :objects_unique_apid_index)
  end

lain's avatar
lain committed
24
  def get_by_ap_id(nil), do: nil
lain's avatar
lain committed
25

26
  def get_by_ap_id(ap_id) do
lain's avatar
lain committed
27
    Repo.one(from(object in Object, where: fragment("(?)->>'id' = ?", object.data, ^ap_id)))
28
  end
29

30
31
32
33
  def normalize(obj) when is_map(obj), do: Object.get_by_ap_id(obj["id"])
  def normalize(ap_id) when is_binary(ap_id), do: Object.get_by_ap_id(ap_id)
  def normalize(_), do: nil

lain's avatar
lain committed
34
  def get_cached_by_ap_id(ap_id) do
lain's avatar
lain committed
35
    if Mix.env() == :test do
lain's avatar
lain committed
36
37
38
      get_by_ap_id(ap_id)
    else
      key = "object:#{ap_id}"
lain's avatar
lain committed
39

Thog's avatar
Thog committed
40
41
42
43
44
45
46
      Cachex.fetch!(:user_cache, key, fn _ ->
        object = get_by_ap_id(ap_id)

        if object do
          {:commit, object}
        else
          {:ignore, object}
47
        end
Thog's avatar
Thog committed
48
      end)
lain's avatar
lain committed
49
50
51
    end
  end

52
  def context_mapping(context) do
53
    Object.change(%Object{}, %{data: %{"id" => context}})
54
  end
55
56
57
58
59

  def delete(%Object{data: %{"id" => id}} = object) do
    with Repo.delete(object),
         Repo.delete_all(Activity.all_non_create_by_object_ap_id_q(id)),
         {:ok, true} <- Cachex.del(:user_cache, "object:#{id}") do
60
      {:ok, object}
61
62
    end
  end
lain's avatar
lain committed
63
end