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