Merge branch 'develop' into feature/new-registrations-digest
[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.Object.Fetcher
11 alias Pleroma.ObjectTombstone
12 alias Pleroma.Repo
13 alias Pleroma.User
14
15 import Ecto.Query
16 import Ecto.Changeset
17
18 require Logger
19
20 @type t() :: %__MODULE__{}
21
22 @derive {Jason.Encoder, only: [:data]}
23
24 schema "objects" do
25 field(:data, :map)
26
27 timestamps()
28 end
29
30 def with_joined_activity(query, activity_type \\ "Create", join_type \\ :inner) do
31 object_position = Map.get(query.aliases, :object, 0)
32
33 join(query, join_type, [{object, object_position}], a in Activity,
34 on:
35 fragment(
36 "COALESCE(?->'object'->>'id', ?->>'object') = (? ->> 'id') AND (?->>'type' = ?) ",
37 a.data,
38 a.data,
39 object.data,
40 a.data,
41 ^activity_type
42 ),
43 as: :object_activity
44 )
45 end
46
47 def create(data) do
48 Object.change(%Object{}, %{data: data})
49 |> Repo.insert()
50 end
51
52 def change(struct, params \\ %{}) do
53 struct
54 |> cast(params, [:data])
55 |> validate_required([:data])
56 |> unique_constraint(:ap_id, name: :objects_unique_apid_index)
57 end
58
59 def get_by_id(nil), do: nil
60 def get_by_id(id), do: Repo.get(Object, id)
61
62 def get_by_id_and_maybe_refetch(id, opts \\ []) do
63 %{updated_at: updated_at} = object = get_by_id(id)
64
65 if opts[:interval] &&
66 NaiveDateTime.diff(NaiveDateTime.utc_now(), updated_at) > opts[:interval] do
67 case Fetcher.refetch_object(object) do
68 {:ok, %Object{} = object} ->
69 object
70
71 e ->
72 Logger.error("Couldn't refresh #{object.data["id"]}:\n#{inspect(e)}")
73 object
74 end
75 else
76 object
77 end
78 end
79
80 def get_by_ap_id(nil), do: nil
81
82 def get_by_ap_id(ap_id) do
83 Repo.one(from(object in Object, where: fragment("(?)->>'id' = ?", object.data, ^ap_id)))
84 end
85
86 @doc """
87 Get a single attachment by it's name and href
88 """
89 @spec get_attachment_by_name_and_href(String.t(), String.t()) :: Object.t() | nil
90 def get_attachment_by_name_and_href(name, href) do
91 query =
92 from(o in Object,
93 where: fragment("(?)->>'name' = ?", o.data, ^name),
94 where: fragment("(?)->>'href' = ?", o.data, ^href)
95 )
96
97 Repo.one(query)
98 end
99
100 defp warn_on_no_object_preloaded(ap_id) do
101 "Object.normalize() called without preloaded object (#{inspect(ap_id)}). Consider preloading the object"
102 |> Logger.debug()
103
104 Logger.debug("Backtrace: #{inspect(Process.info(:erlang.self(), :current_stacktrace))}")
105 end
106
107 def normalize(_, fetch_remote \\ true, options \\ [])
108
109 # If we pass an Activity to Object.normalize(), we can try to use the preloaded object.
110 # Use this whenever possible, especially when walking graphs in an O(N) loop!
111 def normalize(%Object{} = object, _, _), do: object
112 def normalize(%Activity{object: %Object{} = object}, _, _), do: object
113
114 # A hack for fake activities
115 def normalize(%Activity{data: %{"object" => %{"fake" => true} = data}}, _, _) do
116 %Object{id: "pleroma:fake_object_id", data: data}
117 end
118
119 # No preloaded object
120 def normalize(%Activity{data: %{"object" => %{"id" => ap_id}}}, fetch_remote, _) do
121 warn_on_no_object_preloaded(ap_id)
122 normalize(ap_id, fetch_remote)
123 end
124
125 # No preloaded object
126 def normalize(%Activity{data: %{"object" => ap_id}}, fetch_remote, _) do
127 warn_on_no_object_preloaded(ap_id)
128 normalize(ap_id, fetch_remote)
129 end
130
131 # Old way, try fetching the object through cache.
132 def normalize(%{"id" => ap_id}, fetch_remote, _), do: normalize(ap_id, fetch_remote)
133 def normalize(ap_id, false, _) when is_binary(ap_id), do: get_cached_by_ap_id(ap_id)
134
135 def normalize(ap_id, true, options) when is_binary(ap_id) do
136 Fetcher.fetch_object_from_id!(ap_id, options)
137 end
138
139 def normalize(_, _, _), do: nil
140
141 # Owned objects can only be mutated by their owner
142 def authorize_mutation(%Object{data: %{"actor" => actor}}, %User{ap_id: ap_id}),
143 do: actor == ap_id
144
145 # Legacy objects can be mutated by anybody
146 def authorize_mutation(%Object{}, %User{}), do: true
147
148 def get_cached_by_ap_id(ap_id) do
149 key = "object:#{ap_id}"
150
151 Cachex.fetch!(:object_cache, key, fn _ ->
152 object = get_by_ap_id(ap_id)
153
154 if object do
155 {:commit, object}
156 else
157 {:ignore, object}
158 end
159 end)
160 end
161
162 def context_mapping(context) do
163 Object.change(%Object{}, %{data: %{"id" => context}})
164 end
165
166 def make_tombstone(%Object{data: %{"id" => id, "type" => type}}, deleted \\ DateTime.utc_now()) do
167 %ObjectTombstone{
168 id: id,
169 formerType: type,
170 deleted: deleted
171 }
172 |> Map.from_struct()
173 end
174
175 def swap_object_with_tombstone(object) do
176 tombstone = make_tombstone(object)
177
178 object
179 |> Object.change(%{data: tombstone})
180 |> Repo.update()
181 end
182
183 def delete(%Object{data: %{"id" => id}} = object) do
184 with {:ok, _obj} = swap_object_with_tombstone(object),
185 deleted_activity = Activity.delete_all_by_object_ap_id(id),
186 {:ok, true} <- Cachex.del(:object_cache, "object:#{id}"),
187 {:ok, _} <- Cachex.del(:web_resp_cache, URI.parse(id).path),
188 {:ok, _} <-
189 Pleroma.Workers.AttachmentsCleanupWorker.enqueue("cleanup_attachments", %{
190 "object" => object
191 }) do
192 {:ok, object, deleted_activity}
193 end
194 end
195
196 def prune(%Object{data: %{"id" => id}} = object) do
197 with {:ok, object} <- Repo.delete(object),
198 {:ok, true} <- Cachex.del(:object_cache, "object:#{id}"),
199 {:ok, _} <- Cachex.del(:web_resp_cache, URI.parse(id).path) do
200 {:ok, object}
201 end
202 end
203
204 def set_cache(%Object{data: %{"id" => ap_id}} = object) do
205 Cachex.put(:object_cache, "object:#{ap_id}", object)
206 {:ok, object}
207 end
208
209 def update_and_set_cache(changeset) do
210 with {:ok, object} <- Repo.update(changeset) do
211 set_cache(object)
212 end
213 end
214
215 def increase_replies_count(ap_id) do
216 Object
217 |> where([o], fragment("?->>'id' = ?::text", o.data, ^to_string(ap_id)))
218 |> update([o],
219 set: [
220 data:
221 fragment(
222 """
223 safe_jsonb_set(?, '{repliesCount}',
224 (coalesce((?->>'repliesCount')::int, 0) + 1)::varchar::jsonb, true)
225 """,
226 o.data,
227 o.data
228 )
229 ]
230 )
231 |> Repo.update_all([])
232 |> case do
233 {1, [object]} -> set_cache(object)
234 _ -> {:error, "Not found"}
235 end
236 end
237
238 def decrease_replies_count(ap_id) do
239 Object
240 |> where([o], fragment("?->>'id' = ?::text", o.data, ^to_string(ap_id)))
241 |> update([o],
242 set: [
243 data:
244 fragment(
245 """
246 safe_jsonb_set(?, '{repliesCount}',
247 (greatest(0, (?->>'repliesCount')::int - 1))::varchar::jsonb, true)
248 """,
249 o.data,
250 o.data
251 )
252 ]
253 )
254 |> Repo.update_all([])
255 |> case do
256 {1, [object]} -> set_cache(object)
257 _ -> {:error, "Not found"}
258 end
259 end
260
261 def increase_vote_count(ap_id, name) do
262 with %Object{} = object <- Object.normalize(ap_id),
263 "Question" <- object.data["type"] do
264 multiple = Map.has_key?(object.data, "anyOf")
265
266 options =
267 (object.data["anyOf"] || object.data["oneOf"] || [])
268 |> Enum.map(fn
269 %{"name" => ^name} = option ->
270 Kernel.update_in(option["replies"]["totalItems"], &(&1 + 1))
271
272 option ->
273 option
274 end)
275
276 data =
277 if multiple do
278 Map.put(object.data, "anyOf", options)
279 else
280 Map.put(object.data, "oneOf", options)
281 end
282
283 object
284 |> Object.change(%{data: data})
285 |> update_and_set_cache()
286 else
287 _ -> :noop
288 end
289 end
290
291 @doc "Updates data field of an object"
292 def update_data(%Object{data: data} = object, attrs \\ %{}) do
293 object
294 |> Object.change(%{data: Map.merge(data || %{}, attrs)})
295 |> Repo.update()
296 end
297
298 def local?(%Object{data: %{"id" => id}}) do
299 String.starts_with?(id, Pleroma.Web.base_url() <> "/")
300 end
301 end