013d6215710ec42858ab18ed3be69e6775e405ed
[akkoma] / lib / pleroma / object.ex
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2019 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
4
5 defmodule Pleroma.Object do
6 use Ecto.Schema
7
8 alias Pleroma.Activity
9 alias Pleroma.Object
10 alias Pleroma.ObjectTombstone
11 alias Pleroma.Repo
12 alias Pleroma.User
13
14 import Ecto.Query
15 import Ecto.Changeset
16
17 require Logger
18
19 schema "objects" do
20 field(:data, :map)
21
22 timestamps()
23 end
24
25 def create(data) do
26 Object.change(%Object{}, %{data: data})
27 |> Repo.insert()
28 end
29
30 def change(struct, params \\ %{}) do
31 struct
32 |> cast(params, [:data])
33 |> validate_required([:data])
34 |> unique_constraint(:ap_id, name: :objects_unique_apid_index)
35 end
36
37 def get_by_ap_id(nil), do: nil
38
39 def get_by_ap_id(ap_id) do
40 Repo.one(from(object in Object, where: fragment("(?)->>'id' = ?", object.data, ^ap_id)))
41 end
42
43 # If we pass an Activity to Object.normalize(), we can try to use the preloaded object.
44 # Use this whenever possible, especially when walking graphs in an O(N) loop!
45 def normalize(%Activity{object: %Object{} = object}), do: object
46
47 # A hack for fake activities
48 def normalize(%Activity{data: %{"object" => %{"fake" => true} = data}}) do
49 %Object{id: "pleroma:fake_object_id", data: data}
50 end
51
52 # Catch and log Object.normalize() calls where the Activity's child object is not
53 # preloaded.
54 def normalize(%Activity{data: %{"object" => %{"id" => ap_id}}}) do
55 Logger.debug(
56 "Object.normalize() called without preloaded object (#{ap_id}). Consider preloading the object!"
57 )
58
59 Logger.debug("Backtrace: #{inspect(Process.info(:erlang.self(), :current_stacktrace))}")
60
61 normalize(ap_id)
62 end
63
64 def normalize(%Activity{data: %{"object" => ap_id}}) do
65 Logger.debug(
66 "Object.normalize() called without preloaded object (#{ap_id}). Consider preloading the object!"
67 )
68
69 Logger.debug("Backtrace: #{inspect(Process.info(:erlang.self(), :current_stacktrace))}")
70
71 normalize(ap_id)
72 end
73
74 # Old way, try fetching the object through cache.
75 def normalize(%{"id" => ap_id}), do: normalize(ap_id)
76 def normalize(ap_id) when is_binary(ap_id), do: get_cached_by_ap_id(ap_id)
77 def normalize(_), do: nil
78
79 # Owned objects can only be mutated by their owner
80 def authorize_mutation(%Object{data: %{"actor" => actor}}, %User{ap_id: ap_id}),
81 do: actor == ap_id
82
83 # Legacy objects can be mutated by anybody
84 def authorize_mutation(%Object{}, %User{}), do: true
85
86 def get_cached_by_ap_id(ap_id) do
87 key = "object:#{ap_id}"
88
89 Cachex.fetch!(:object_cache, key, fn _ ->
90 object = get_by_ap_id(ap_id)
91
92 if object do
93 {:commit, object}
94 else
95 {:ignore, object}
96 end
97 end)
98 end
99
100 def context_mapping(context) do
101 Object.change(%Object{}, %{data: %{"id" => context}})
102 end
103
104 def make_tombstone(%Object{data: %{"id" => id, "type" => type}}, deleted \\ DateTime.utc_now()) do
105 %ObjectTombstone{
106 id: id,
107 formerType: type,
108 deleted: deleted
109 }
110 |> Map.from_struct()
111 end
112
113 def swap_object_with_tombstone(object) do
114 tombstone = make_tombstone(object)
115
116 object
117 |> Object.change(%{data: tombstone})
118 |> Repo.update()
119 end
120
121 def delete(%Object{data: %{"id" => id}} = object) do
122 with {:ok, _obj} = swap_object_with_tombstone(object),
123 deleted_activity = Activity.delete_by_ap_id(id),
124 {:ok, true} <- Cachex.del(:object_cache, "object:#{id}") do
125 {:ok, object, deleted_activity}
126 end
127 end
128
129 def set_cache(%Object{data: %{"id" => ap_id}} = object) do
130 Cachex.put(:object_cache, "object:#{ap_id}", object)
131 {:ok, object}
132 end
133
134 def update_and_set_cache(changeset) do
135 with {:ok, object} <- Repo.update(changeset) do
136 set_cache(object)
137 else
138 e -> e
139 end
140 end
141
142 def increase_replies_count(ap_id) do
143 Object
144 |> where([o], fragment("?->>'id' = ?::text", o.data, ^to_string(ap_id)))
145 |> update([o],
146 set: [
147 data:
148 fragment(
149 """
150 jsonb_set(?, '{repliesCount}',
151 (coalesce((?->>'repliesCount')::int, 0) + 1)::varchar::jsonb, true)
152 """,
153 o.data,
154 o.data
155 )
156 ]
157 )
158 |> Repo.update_all([])
159 |> case do
160 {1, [object]} -> set_cache(object)
161 _ -> {:error, "Not found"}
162 end
163 end
164
165 def decrease_replies_count(ap_id) do
166 Object
167 |> where([o], fragment("?->>'id' = ?::text", o.data, ^to_string(ap_id)))
168 |> update([o],
169 set: [
170 data:
171 fragment(
172 """
173 jsonb_set(?, '{repliesCount}',
174 (greatest(0, (?->>'repliesCount')::int - 1))::varchar::jsonb, true)
175 """,
176 o.data,
177 o.data
178 )
179 ]
180 )
181 |> Repo.update_all([])
182 |> case do
183 {1, [object]} -> set_cache(object)
184 _ -> {:error, "Not found"}
185 end
186 end
187 end