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