activitypub: utils: wrap Note objects in a Create when extracting mentions
[akkoma] / lib / pleroma / web / activity_pub / utils.ex
1 defmodule Pleroma.Web.ActivityPub.Utils do
2 alias Pleroma.{Repo, Web, Object, Activity, User, Notification}
3 alias Pleroma.Web.Router.Helpers
4 alias Pleroma.Web.Endpoint
5 alias Ecto.{Changeset, UUID}
6 import Ecto.Query
7 require Logger
8
9 # Some implementations send the actor URI as the actor field, others send the entire actor object,
10 # so figure out what the actor's URI is based on what we have.
11 def get_ap_id(object) do
12 case object do
13 %{"id" => id} -> id
14 id -> id
15 end
16 end
17
18 def normalize_params(params) do
19 Map.put(params, "actor", get_ap_id(params["actor"]))
20 end
21
22 defp recipient_in_collection(ap_id, coll) when is_binary(coll), do: ap_id == coll
23 defp recipient_in_collection(ap_id, coll) when is_list(coll), do: ap_id in coll
24 defp recipient_in_collection(_, _), do: false
25
26 def recipient_in_message(ap_id, params) do
27 cond do
28 recipient_in_collection(ap_id, params["to"]) ->
29 true
30
31 recipient_in_collection(ap_id, params["cc"]) ->
32 true
33
34 recipient_in_collection(ap_id, params["bto"]) ->
35 true
36
37 recipient_in_collection(ap_id, params["bcc"]) ->
38 true
39
40 # if the message is unaddressed at all, then assume it is directly addressed
41 # to the recipient
42 !params["to"] && !params["cc"] && !params["bto"] && !params["bcc"] ->
43 true
44
45 true ->
46 false
47 end
48 end
49
50 defp extract_list(target) when is_binary(target), do: [target]
51 defp extract_list(lst) when is_list(lst), do: lst
52 defp extract_list(_), do: []
53
54 def maybe_splice_recipient(ap_id, params) do
55 need_splice =
56 !recipient_in_collection(ap_id, params["to"]) &&
57 !recipient_in_collection(ap_id, params["cc"])
58
59 cc_list = extract_list(params["cc"])
60
61 if need_splice do
62 params
63 |> Map.put("cc", [ap_id | cc_list])
64 else
65 params
66 end
67 end
68
69 def make_json_ld_header do
70 %{
71 "@context" => [
72 "https://www.w3.org/ns/activitystreams",
73 "https://litepub.github.io/litepub/context.jsonld"
74 ]
75 }
76 end
77
78 def make_date do
79 DateTime.utc_now() |> DateTime.to_iso8601()
80 end
81
82 def generate_activity_id do
83 generate_id("activities")
84 end
85
86 def generate_context_id do
87 generate_id("contexts")
88 end
89
90 def generate_object_id do
91 Helpers.o_status_url(Endpoint, :object, UUID.generate())
92 end
93
94 def generate_id(type) do
95 "#{Web.base_url()}/#{type}/#{UUID.generate()}"
96 end
97
98 def get_notified_from_object(%{"type" => type} = object) when type == "Note" do
99 fake_create_activity = %{
100 "to" => object["to"],
101 "cc" => object["cc"],
102 "type" => "Create",
103 "object" => object
104 }
105
106 Notification.get_notified_from_activity(%Activity{data: fake_create_activity}, false)
107 end
108
109 def get_notified_from_object(object) do
110 Notification.get_notified_from_activity(%Activity{data: object}, false)
111 end
112
113 def create_context(context) do
114 context = context || generate_id("contexts")
115 changeset = Object.context_mapping(context)
116
117 case Repo.insert(changeset) do
118 {:ok, object} ->
119 object
120
121 # This should be solved by an upsert, but it seems ecto
122 # has problems accessing the constraint inside the jsonb.
123 {:error, _} ->
124 Object.get_cached_by_ap_id(context)
125 end
126 end
127
128 @doc """
129 Enqueues an activity for federation if it's local
130 """
131 def maybe_federate(%Activity{local: true} = activity) do
132 priority =
133 case activity.data["type"] do
134 "Delete" -> 10
135 "Create" -> 1
136 _ -> 5
137 end
138
139 Pleroma.Web.Federator.enqueue(:publish, activity, priority)
140 :ok
141 end
142
143 def maybe_federate(_), do: :ok
144
145 @doc """
146 Adds an id and a published data if they aren't there,
147 also adds it to an included object
148 """
149 def lazy_put_activity_defaults(map) do
150 %{data: %{"id" => context}, id: context_id} = create_context(map["context"])
151
152 map =
153 map
154 |> Map.put_new_lazy("id", &generate_activity_id/0)
155 |> Map.put_new_lazy("published", &make_date/0)
156 |> Map.put_new("context", context)
157 |> Map.put_new("context_id", context_id)
158
159 if is_map(map["object"]) do
160 object = lazy_put_object_defaults(map["object"], map)
161 %{map | "object" => object}
162 else
163 map
164 end
165 end
166
167 @doc """
168 Adds an id and published date if they aren't there.
169 """
170 def lazy_put_object_defaults(map, activity \\ %{}) do
171 map
172 |> Map.put_new_lazy("id", &generate_object_id/0)
173 |> Map.put_new_lazy("published", &make_date/0)
174 |> Map.put_new("context", activity["context"])
175 |> Map.put_new("context_id", activity["context_id"])
176 end
177
178 @doc """
179 Inserts a full object if it is contained in an activity.
180 """
181 def insert_full_object(%{"object" => %{"type" => type} = object_data})
182 when is_map(object_data) and type in ["Article", "Note", "Video", "Page"] do
183 with {:ok, _} <- Object.create(object_data) do
184 :ok
185 end
186 end
187
188 def insert_full_object(_), do: :ok
189
190 def update_object_in_activities(%{data: %{"id" => id}} = object) do
191 # TODO
192 # Update activities that already had this. Could be done in a seperate process.
193 # Alternatively, just don't do this and fetch the current object each time. Most
194 # could probably be taken from cache.
195 relevant_activities = Activity.all_by_object_ap_id(id)
196
197 Enum.map(relevant_activities, fn activity ->
198 new_activity_data = activity.data |> Map.put("object", object.data)
199 changeset = Changeset.change(activity, data: new_activity_data)
200 Repo.update(changeset)
201 end)
202 end
203
204 #### Like-related helpers
205
206 @doc """
207 Returns an existing like if a user already liked an object
208 """
209 def get_existing_like(actor, %{data: %{"id" => id}}) do
210 query =
211 from(
212 activity in Activity,
213 where: fragment("(?)->>'actor' = ?", activity.data, ^actor),
214 # this is to use the index
215 where:
216 fragment(
217 "coalesce((?)->'object'->>'id', (?)->>'object') = ?",
218 activity.data,
219 activity.data,
220 ^id
221 ),
222 where: fragment("(?)->>'type' = 'Like'", activity.data)
223 )
224
225 Repo.one(query)
226 end
227
228 def make_like_data(%User{ap_id: ap_id} = actor, %{data: %{"id" => id}} = object, activity_id) do
229 data = %{
230 "type" => "Like",
231 "actor" => ap_id,
232 "object" => id,
233 "to" => [actor.follower_address, object.data["actor"]],
234 "cc" => ["https://www.w3.org/ns/activitystreams#Public"],
235 "context" => object.data["context"]
236 }
237
238 if activity_id, do: Map.put(data, "id", activity_id), else: data
239 end
240
241 def update_element_in_object(property, element, object) do
242 with new_data <-
243 object.data
244 |> Map.put("#{property}_count", length(element))
245 |> Map.put("#{property}s", element),
246 changeset <- Changeset.change(object, data: new_data),
247 {:ok, object} <- Repo.update(changeset),
248 _ <- update_object_in_activities(object) do
249 {:ok, object}
250 end
251 end
252
253 def update_likes_in_object(likes, object) do
254 update_element_in_object("like", likes, object)
255 end
256
257 def add_like_to_object(%Activity{data: %{"actor" => actor}}, object) do
258 likes = if is_list(object.data["likes"]), do: object.data["likes"], else: []
259
260 with likes <- [actor | likes] |> Enum.uniq() do
261 update_likes_in_object(likes, object)
262 end
263 end
264
265 def remove_like_from_object(%Activity{data: %{"actor" => actor}}, object) do
266 likes = if is_list(object.data["likes"]), do: object.data["likes"], else: []
267
268 with likes <- likes |> List.delete(actor) do
269 update_likes_in_object(likes, object)
270 end
271 end
272
273 #### Follow-related helpers
274
275 @doc """
276 Updates a follow activity's state (for locked accounts).
277 """
278 def update_follow_state(%Activity{} = activity, state) do
279 with new_data <-
280 activity.data
281 |> Map.put("state", state),
282 changeset <- Changeset.change(activity, data: new_data),
283 {:ok, activity} <- Repo.update(changeset) do
284 {:ok, activity}
285 end
286 end
287
288 @doc """
289 Makes a follow activity data for the given follower and followed
290 """
291 def make_follow_data(
292 %User{ap_id: follower_id},
293 %User{ap_id: followed_id} = followed,
294 activity_id
295 ) do
296 data = %{
297 "type" => "Follow",
298 "actor" => follower_id,
299 "to" => [followed_id],
300 "cc" => ["https://www.w3.org/ns/activitystreams#Public"],
301 "object" => followed_id,
302 "state" => "pending"
303 }
304
305 data = if activity_id, do: Map.put(data, "id", activity_id), else: data
306
307 data
308 end
309
310 def fetch_latest_follow(%User{ap_id: follower_id}, %User{ap_id: followed_id}) do
311 query =
312 from(
313 activity in Activity,
314 where:
315 fragment(
316 "? ->> 'type' = 'Follow'",
317 activity.data
318 ),
319 where: activity.actor == ^follower_id,
320 where:
321 fragment(
322 "? @> ?",
323 activity.data,
324 ^%{object: followed_id}
325 ),
326 order_by: [desc: :id],
327 limit: 1
328 )
329
330 Repo.one(query)
331 end
332
333 #### Announce-related helpers
334
335 @doc """
336 Retruns an existing announce activity if the notice has already been announced
337 """
338 def get_existing_announce(actor, %{data: %{"id" => id}}) do
339 query =
340 from(
341 activity in Activity,
342 where: activity.actor == ^actor,
343 # this is to use the index
344 where:
345 fragment(
346 "coalesce((?)->'object'->>'id', (?)->>'object') = ?",
347 activity.data,
348 activity.data,
349 ^id
350 ),
351 where: fragment("(?)->>'type' = 'Announce'", activity.data)
352 )
353
354 Repo.one(query)
355 end
356
357 @doc """
358 Make announce activity data for the given actor and object
359 """
360 # for relayed messages, we only want to send to subscribers
361 def make_announce_data(
362 %User{ap_id: ap_id, nickname: nil} = user,
363 %Object{data: %{"id" => id}} = object,
364 activity_id
365 ) do
366 data = %{
367 "type" => "Announce",
368 "actor" => ap_id,
369 "object" => id,
370 "to" => [user.follower_address],
371 "cc" => [],
372 "context" => object.data["context"]
373 }
374
375 if activity_id, do: Map.put(data, "id", activity_id), else: data
376 end
377
378 def make_announce_data(
379 %User{ap_id: ap_id} = user,
380 %Object{data: %{"id" => id}} = object,
381 activity_id
382 ) do
383 data = %{
384 "type" => "Announce",
385 "actor" => ap_id,
386 "object" => id,
387 "to" => [user.follower_address, object.data["actor"]],
388 "cc" => ["https://www.w3.org/ns/activitystreams#Public"],
389 "context" => object.data["context"]
390 }
391
392 if activity_id, do: Map.put(data, "id", activity_id), else: data
393 end
394
395 @doc """
396 Make unannounce activity data for the given actor and object
397 """
398 def make_unannounce_data(
399 %User{ap_id: ap_id} = user,
400 %Activity{data: %{"context" => context}} = activity,
401 activity_id
402 ) do
403 data = %{
404 "type" => "Undo",
405 "actor" => ap_id,
406 "object" => activity.data,
407 "to" => [user.follower_address, activity.data["actor"]],
408 "cc" => ["https://www.w3.org/ns/activitystreams#Public"],
409 "context" => context
410 }
411
412 if activity_id, do: Map.put(data, "id", activity_id), else: data
413 end
414
415 def make_unlike_data(
416 %User{ap_id: ap_id} = user,
417 %Activity{data: %{"context" => context}} = activity,
418 activity_id
419 ) do
420 data = %{
421 "type" => "Undo",
422 "actor" => ap_id,
423 "object" => activity.data,
424 "to" => [user.follower_address, activity.data["actor"]],
425 "cc" => ["https://www.w3.org/ns/activitystreams#Public"],
426 "context" => context
427 }
428
429 if activity_id, do: Map.put(data, "id", activity_id), else: data
430 end
431
432 def add_announce_to_object(
433 %Activity{
434 data: %{"actor" => actor, "cc" => ["https://www.w3.org/ns/activitystreams#Public"]}
435 },
436 object
437 ) do
438 announcements =
439 if is_list(object.data["announcements"]), do: object.data["announcements"], else: []
440
441 with announcements <- [actor | announcements] |> Enum.uniq() do
442 update_element_in_object("announcement", announcements, object)
443 end
444 end
445
446 def add_announce_to_object(_, object), do: {:ok, object}
447
448 def remove_announce_from_object(%Activity{data: %{"actor" => actor}}, object) do
449 announcements =
450 if is_list(object.data["announcements"]), do: object.data["announcements"], else: []
451
452 with announcements <- announcements |> List.delete(actor) do
453 update_element_in_object("announcement", announcements, object)
454 end
455 end
456
457 #### Unfollow-related helpers
458
459 def make_unfollow_data(follower, followed, follow_activity, activity_id) do
460 data = %{
461 "type" => "Undo",
462 "actor" => follower.ap_id,
463 "to" => [followed.ap_id],
464 "object" => follow_activity.data
465 }
466
467 if activity_id, do: Map.put(data, "id", activity_id), else: data
468 end
469
470 #### Block-related helpers
471 def fetch_latest_block(%User{ap_id: blocker_id}, %User{ap_id: blocked_id}) do
472 query =
473 from(
474 activity in Activity,
475 where:
476 fragment(
477 "? ->> 'type' = 'Block'",
478 activity.data
479 ),
480 where: activity.actor == ^blocker_id,
481 where:
482 fragment(
483 "? @> ?",
484 activity.data,
485 ^%{object: blocked_id}
486 ),
487 order_by: [desc: :id],
488 limit: 1
489 )
490
491 Repo.one(query)
492 end
493
494 def make_block_data(blocker, blocked, activity_id) do
495 data = %{
496 "type" => "Block",
497 "actor" => blocker.ap_id,
498 "to" => [blocked.ap_id],
499 "object" => blocked.ap_id
500 }
501
502 if activity_id, do: Map.put(data, "id", activity_id), else: data
503 end
504
505 def make_unblock_data(blocker, blocked, block_activity, activity_id) do
506 data = %{
507 "type" => "Undo",
508 "actor" => blocker.ap_id,
509 "to" => [blocked.ap_id],
510 "object" => block_activity.data
511 }
512
513 if activity_id, do: Map.put(data, "id", activity_id), else: data
514 end
515
516 #### Create-related helpers
517
518 def make_create_data(params, additional) do
519 published = params.published || make_date()
520
521 %{
522 "type" => "Create",
523 "to" => params.to |> Enum.uniq(),
524 "actor" => params.actor.ap_id,
525 "object" => params.object,
526 "published" => published,
527 "context" => params.context
528 }
529 |> Map.merge(additional)
530 end
531 end