Merge branch 'develop' into openapi/account
[akkoma] / lib / pleroma / object.ex
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2020 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 import Ecto.Query
9 import Ecto.Changeset
10
11 alias Pleroma.Activity
12 alias Pleroma.Object
13 alias Pleroma.Object.Fetcher
14 alias Pleroma.ObjectTombstone
15 alias Pleroma.Repo
16 alias Pleroma.User
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 @spec get_cached_by_ap_id(String.t()) :: Object.t() | nil
149 def get_cached_by_ap_id(ap_id) do
150 key = "object:#{ap_id}"
151
152 with {:ok, nil} <- Cachex.get(:object_cache, key),
153 object when not is_nil(object) <- get_by_ap_id(ap_id),
154 {:ok, true} <- Cachex.put(:object_cache, key, object) do
155 object
156 else
157 {:ok, object} -> object
158 nil -> nil
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) do
188 with true <- Pleroma.Config.get([:instance, :cleanup_attachments]) do
189 {:ok, _} =
190 Pleroma.Workers.AttachmentsCleanupWorker.enqueue("cleanup_attachments", %{
191 "object" => object
192 })
193 end
194
195 {:ok, object, deleted_activity}
196 end
197 end
198
199 def prune(%Object{data: %{"id" => id}} = object) do
200 with {:ok, object} <- Repo.delete(object),
201 {:ok, true} <- Cachex.del(:object_cache, "object:#{id}"),
202 {:ok, _} <- Cachex.del(:web_resp_cache, URI.parse(id).path) do
203 {:ok, object}
204 end
205 end
206
207 def set_cache(%Object{data: %{"id" => ap_id}} = object) do
208 Cachex.put(:object_cache, "object:#{ap_id}", object)
209 {:ok, object}
210 end
211
212 def update_and_set_cache(changeset) do
213 with {:ok, object} <- Repo.update(changeset) do
214 set_cache(object)
215 end
216 end
217
218 def increase_replies_count(ap_id) do
219 Object
220 |> where([o], fragment("?->>'id' = ?::text", o.data, ^to_string(ap_id)))
221 |> update([o],
222 set: [
223 data:
224 fragment(
225 """
226 safe_jsonb_set(?, '{repliesCount}',
227 (coalesce((?->>'repliesCount')::int, 0) + 1)::varchar::jsonb, true)
228 """,
229 o.data,
230 o.data
231 )
232 ]
233 )
234 |> Repo.update_all([])
235 |> case do
236 {1, [object]} -> set_cache(object)
237 _ -> {:error, "Not found"}
238 end
239 end
240
241 def decrease_replies_count(ap_id) do
242 Object
243 |> where([o], fragment("?->>'id' = ?::text", o.data, ^to_string(ap_id)))
244 |> update([o],
245 set: [
246 data:
247 fragment(
248 """
249 safe_jsonb_set(?, '{repliesCount}',
250 (greatest(0, (?->>'repliesCount')::int - 1))::varchar::jsonb, true)
251 """,
252 o.data,
253 o.data
254 )
255 ]
256 )
257 |> Repo.update_all([])
258 |> case do
259 {1, [object]} -> set_cache(object)
260 _ -> {:error, "Not found"}
261 end
262 end
263
264 def increase_vote_count(ap_id, name, actor) do
265 with %Object{} = object <- Object.normalize(ap_id),
266 "Question" <- object.data["type"] do
267 multiple = Map.has_key?(object.data, "anyOf")
268
269 options =
270 (object.data["anyOf"] || object.data["oneOf"] || [])
271 |> Enum.map(fn
272 %{"name" => ^name} = option ->
273 Kernel.update_in(option["replies"]["totalItems"], &(&1 + 1))
274
275 option ->
276 option
277 end)
278
279 voters = [actor | object.data["voters"] || []] |> Enum.uniq()
280
281 data =
282 if multiple do
283 Map.put(object.data, "anyOf", options)
284 else
285 Map.put(object.data, "oneOf", options)
286 end
287 |> Map.put("voters", voters)
288
289 object
290 |> Object.change(%{data: data})
291 |> update_and_set_cache()
292 else
293 _ -> :noop
294 end
295 end
296
297 @doc "Updates data field of an object"
298 def update_data(%Object{data: data} = object, attrs \\ %{}) do
299 object
300 |> Object.change(%{data: Map.merge(data || %{}, attrs)})
301 |> Repo.update()
302 end
303
304 def local?(%Object{data: %{"id" => id}}) do
305 String.starts_with?(id, Pleroma.Web.base_url() <> "/")
306 end
307
308 def replies(object, opts \\ []) do
309 object = Object.normalize(object)
310
311 query =
312 Object
313 |> where(
314 [o],
315 fragment("(?)->>'inReplyTo' = ?", o.data, ^object.data["id"])
316 )
317 |> order_by([o], asc: o.id)
318
319 if opts[:self_only] do
320 actor = object.data["actor"]
321 where(query, [o], fragment("(?)->>'actor' = ?", o.data, ^actor))
322 else
323 query
324 end
325 end
326
327 def self_replies(object, opts \\ []),
328 do: replies(object, Keyword.put(opts, :self_only, true))
329 end