Merge branch 'following-relationships-optimizations' into 'develop'
[akkoma] / lib / pleroma / web / activity_pub / transmogrifier.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.Web.ActivityPub.Transmogrifier do
6 @moduledoc """
7 A module to handle coding from internal to wire ActivityPub and back.
8 """
9 alias Pleroma.Activity
10 alias Pleroma.FollowingRelationship
11 alias Pleroma.Object
12 alias Pleroma.Object.Containment
13 alias Pleroma.Repo
14 alias Pleroma.User
15 alias Pleroma.Web.ActivityPub.ActivityPub
16 alias Pleroma.Web.ActivityPub.ObjectValidator
17 alias Pleroma.Web.ActivityPub.ObjectValidators.LikeValidator
18 alias Pleroma.Web.ActivityPub.Pipeline
19 alias Pleroma.Web.ActivityPub.Utils
20 alias Pleroma.Web.ActivityPub.Visibility
21 alias Pleroma.Web.Federator
22 alias Pleroma.Workers.TransmogrifierWorker
23
24 import Ecto.Query
25
26 require Logger
27 require Pleroma.Constants
28
29 @doc """
30 Modifies an incoming AP object (mastodon format) to our internal format.
31 """
32 def fix_object(object, options \\ []) do
33 object
34 |> strip_internal_fields
35 |> fix_actor
36 |> fix_url
37 |> fix_attachments
38 |> fix_context
39 |> fix_in_reply_to(options)
40 |> fix_emoji
41 |> fix_tag
42 |> fix_content_map
43 |> fix_addressing
44 |> fix_summary
45 |> fix_type(options)
46 end
47
48 def fix_summary(%{"summary" => nil} = object) do
49 Map.put(object, "summary", "")
50 end
51
52 def fix_summary(%{"summary" => _} = object) do
53 # summary is present, nothing to do
54 object
55 end
56
57 def fix_summary(object), do: Map.put(object, "summary", "")
58
59 def fix_addressing_list(map, field) do
60 cond do
61 is_binary(map[field]) ->
62 Map.put(map, field, [map[field]])
63
64 is_nil(map[field]) ->
65 Map.put(map, field, [])
66
67 true ->
68 map
69 end
70 end
71
72 def fix_explicit_addressing(
73 %{"to" => to, "cc" => cc} = object,
74 explicit_mentions,
75 follower_collection
76 ) do
77 explicit_to = Enum.filter(to, fn x -> x in explicit_mentions end)
78
79 explicit_cc = Enum.filter(to, fn x -> x not in explicit_mentions end)
80
81 final_cc =
82 (cc ++ explicit_cc)
83 |> Enum.reject(fn x -> String.ends_with?(x, "/followers") and x != follower_collection end)
84 |> Enum.uniq()
85
86 object
87 |> Map.put("to", explicit_to)
88 |> Map.put("cc", final_cc)
89 end
90
91 def fix_explicit_addressing(object, _explicit_mentions, _followers_collection), do: object
92
93 # if directMessage flag is set to true, leave the addressing alone
94 def fix_explicit_addressing(%{"directMessage" => true} = object), do: object
95
96 def fix_explicit_addressing(object) do
97 explicit_mentions = Utils.determine_explicit_mentions(object)
98
99 %User{follower_address: follower_collection} =
100 object
101 |> Containment.get_actor()
102 |> User.get_cached_by_ap_id()
103
104 explicit_mentions =
105 explicit_mentions ++
106 [
107 Pleroma.Constants.as_public(),
108 follower_collection
109 ]
110
111 fix_explicit_addressing(object, explicit_mentions, follower_collection)
112 end
113
114 # if as:Public is addressed, then make sure the followers collection is also addressed
115 # so that the activities will be delivered to local users.
116 def fix_implicit_addressing(%{"to" => to, "cc" => cc} = object, followers_collection) do
117 recipients = to ++ cc
118
119 if followers_collection not in recipients do
120 cond do
121 Pleroma.Constants.as_public() in cc ->
122 to = to ++ [followers_collection]
123 Map.put(object, "to", to)
124
125 Pleroma.Constants.as_public() in to ->
126 cc = cc ++ [followers_collection]
127 Map.put(object, "cc", cc)
128
129 true ->
130 object
131 end
132 else
133 object
134 end
135 end
136
137 def fix_implicit_addressing(object, _), do: object
138
139 def fix_addressing(object) do
140 {:ok, %User{} = user} = User.get_or_fetch_by_ap_id(object["actor"])
141 followers_collection = User.ap_followers(user)
142
143 object
144 |> fix_addressing_list("to")
145 |> fix_addressing_list("cc")
146 |> fix_addressing_list("bto")
147 |> fix_addressing_list("bcc")
148 |> fix_explicit_addressing()
149 |> fix_implicit_addressing(followers_collection)
150 end
151
152 def fix_actor(%{"attributedTo" => actor} = object) do
153 Map.put(object, "actor", Containment.get_actor(%{"actor" => actor}))
154 end
155
156 def fix_in_reply_to(object, options \\ [])
157
158 def fix_in_reply_to(%{"inReplyTo" => in_reply_to} = object, options)
159 when not is_nil(in_reply_to) do
160 in_reply_to_id = prepare_in_reply_to(in_reply_to)
161 object = Map.put(object, "inReplyToAtomUri", in_reply_to_id)
162 depth = (options[:depth] || 0) + 1
163
164 if Federator.allowed_thread_distance?(depth) do
165 with {:ok, replied_object} <- get_obj_helper(in_reply_to_id, options),
166 %Activity{} <- Activity.get_create_by_object_ap_id(replied_object.data["id"]) do
167 object
168 |> Map.put("inReplyTo", replied_object.data["id"])
169 |> Map.put("inReplyToAtomUri", object["inReplyToAtomUri"] || in_reply_to_id)
170 |> Map.put("conversation", replied_object.data["context"] || object["conversation"])
171 |> Map.put("context", replied_object.data["context"] || object["conversation"])
172 else
173 e ->
174 Logger.error("Couldn't fetch #{inspect(in_reply_to_id)}, error: #{inspect(e)}")
175 object
176 end
177 else
178 object
179 end
180 end
181
182 def fix_in_reply_to(object, _options), do: object
183
184 defp prepare_in_reply_to(in_reply_to) do
185 cond do
186 is_bitstring(in_reply_to) ->
187 in_reply_to
188
189 is_map(in_reply_to) && is_bitstring(in_reply_to["id"]) ->
190 in_reply_to["id"]
191
192 is_list(in_reply_to) && is_bitstring(Enum.at(in_reply_to, 0)) ->
193 Enum.at(in_reply_to, 0)
194
195 true ->
196 ""
197 end
198 end
199
200 def fix_context(object) do
201 context = object["context"] || object["conversation"] || Utils.generate_context_id()
202
203 object
204 |> Map.put("context", context)
205 |> Map.put("conversation", context)
206 end
207
208 defp add_if_present(map, _key, nil), do: map
209
210 defp add_if_present(map, key, value) do
211 Map.put(map, key, value)
212 end
213
214 def fix_attachments(%{"attachment" => attachment} = object) when is_list(attachment) do
215 attachments =
216 Enum.map(attachment, fn data ->
217 url =
218 cond do
219 is_list(data["url"]) -> List.first(data["url"])
220 is_map(data["url"]) -> data["url"]
221 true -> nil
222 end
223
224 media_type =
225 cond do
226 is_map(url) && is_binary(url["mediaType"]) -> url["mediaType"]
227 is_binary(data["mediaType"]) -> data["mediaType"]
228 is_binary(data["mimeType"]) -> data["mimeType"]
229 true -> nil
230 end
231
232 href =
233 cond do
234 is_map(url) && is_binary(url["href"]) -> url["href"]
235 is_binary(data["url"]) -> data["url"]
236 is_binary(data["href"]) -> data["href"]
237 end
238
239 attachment_url =
240 %{"href" => href}
241 |> add_if_present("mediaType", media_type)
242 |> add_if_present("type", Map.get(url || %{}, "type"))
243
244 %{"url" => [attachment_url]}
245 |> add_if_present("mediaType", media_type)
246 |> add_if_present("type", data["type"])
247 |> add_if_present("name", data["name"])
248 end)
249
250 Map.put(object, "attachment", attachments)
251 end
252
253 def fix_attachments(%{"attachment" => attachment} = object) when is_map(attachment) do
254 object
255 |> Map.put("attachment", [attachment])
256 |> fix_attachments()
257 end
258
259 def fix_attachments(object), do: object
260
261 def fix_url(%{"url" => url} = object) when is_map(url) do
262 Map.put(object, "url", url["href"])
263 end
264
265 def fix_url(%{"type" => object_type, "url" => url} = object)
266 when object_type in ["Video", "Audio"] and is_list(url) do
267 first_element = Enum.at(url, 0)
268
269 link_element = Enum.find(url, fn x -> is_map(x) and x["mimeType"] == "text/html" end)
270
271 object
272 |> Map.put("attachment", [first_element])
273 |> Map.put("url", link_element["href"])
274 end
275
276 def fix_url(%{"type" => object_type, "url" => url} = object)
277 when object_type != "Video" and is_list(url) do
278 first_element = Enum.at(url, 0)
279
280 url_string =
281 cond do
282 is_bitstring(first_element) -> first_element
283 is_map(first_element) -> first_element["href"] || ""
284 true -> ""
285 end
286
287 Map.put(object, "url", url_string)
288 end
289
290 def fix_url(object), do: object
291
292 def fix_emoji(%{"tag" => tags} = object) when is_list(tags) do
293 emoji =
294 tags
295 |> Enum.filter(fn data -> data["type"] == "Emoji" and data["icon"] end)
296 |> Enum.reduce(%{}, fn data, mapping ->
297 name = String.trim(data["name"], ":")
298
299 Map.put(mapping, name, data["icon"]["url"])
300 end)
301
302 # we merge mastodon and pleroma emoji into a single mapping, to allow for both wire formats
303 emoji = Map.merge(object["emoji"] || %{}, emoji)
304
305 Map.put(object, "emoji", emoji)
306 end
307
308 def fix_emoji(%{"tag" => %{"type" => "Emoji"} = tag} = object) do
309 name = String.trim(tag["name"], ":")
310 emoji = %{name => tag["icon"]["url"]}
311
312 Map.put(object, "emoji", emoji)
313 end
314
315 def fix_emoji(object), do: object
316
317 def fix_tag(%{"tag" => tag} = object) when is_list(tag) do
318 tags =
319 tag
320 |> Enum.filter(fn data -> data["type"] == "Hashtag" and data["name"] end)
321 |> Enum.map(fn data -> String.slice(data["name"], 1..-1) end)
322
323 Map.put(object, "tag", tag ++ tags)
324 end
325
326 def fix_tag(%{"tag" => %{"type" => "Hashtag", "name" => hashtag} = tag} = object) do
327 combined = [tag, String.slice(hashtag, 1..-1)]
328
329 Map.put(object, "tag", combined)
330 end
331
332 def fix_tag(%{"tag" => %{} = tag} = object), do: Map.put(object, "tag", [tag])
333
334 def fix_tag(object), do: object
335
336 # content map usually only has one language so this will do for now.
337 def fix_content_map(%{"contentMap" => content_map} = object) do
338 content_groups = Map.to_list(content_map)
339 {_, content} = Enum.at(content_groups, 0)
340
341 Map.put(object, "content", content)
342 end
343
344 def fix_content_map(object), do: object
345
346 def fix_type(object, options \\ [])
347
348 def fix_type(%{"inReplyTo" => reply_id, "name" => _} = object, options)
349 when is_binary(reply_id) do
350 with true <- Federator.allowed_thread_distance?(options[:depth]),
351 {:ok, %{data: %{"type" => "Question"} = _} = _} <- get_obj_helper(reply_id, options) do
352 Map.put(object, "type", "Answer")
353 else
354 _ -> object
355 end
356 end
357
358 def fix_type(object, _), do: object
359
360 defp mastodon_follow_hack(%{"id" => id, "actor" => follower_id}, followed) do
361 with true <- id =~ "follows",
362 %User{local: true} = follower <- User.get_cached_by_ap_id(follower_id),
363 %Activity{} = activity <- Utils.fetch_latest_follow(follower, followed) do
364 {:ok, activity}
365 else
366 _ -> {:error, nil}
367 end
368 end
369
370 defp mastodon_follow_hack(_, _), do: {:error, nil}
371
372 defp get_follow_activity(follow_object, followed) do
373 with object_id when not is_nil(object_id) <- Utils.get_ap_id(follow_object),
374 {_, %Activity{} = activity} <- {:activity, Activity.get_by_ap_id(object_id)} do
375 {:ok, activity}
376 else
377 # Can't find the activity. This might a Mastodon 2.3 "Accept"
378 {:activity, nil} ->
379 mastodon_follow_hack(follow_object, followed)
380
381 _ ->
382 {:error, nil}
383 end
384 end
385
386 # Reduce the object list to find the reported user.
387 defp get_reported(objects) do
388 Enum.reduce_while(objects, nil, fn ap_id, _ ->
389 with %User{} = user <- User.get_cached_by_ap_id(ap_id) do
390 {:halt, user}
391 else
392 _ -> {:cont, nil}
393 end
394 end)
395 end
396
397 def handle_incoming(data, options \\ [])
398
399 # Flag objects are placed ahead of the ID check because Mastodon 2.8 and earlier send them
400 # with nil ID.
401 def handle_incoming(%{"type" => "Flag", "object" => objects, "actor" => actor} = data, _options) do
402 with context <- data["context"] || Utils.generate_context_id(),
403 content <- data["content"] || "",
404 %User{} = actor <- User.get_cached_by_ap_id(actor),
405 # Reduce the object list to find the reported user.
406 %User{} = account <- get_reported(objects),
407 # Remove the reported user from the object list.
408 statuses <- Enum.filter(objects, fn ap_id -> ap_id != account.ap_id end) do
409 %{
410 actor: actor,
411 context: context,
412 account: account,
413 statuses: statuses,
414 content: content,
415 additional: %{"cc" => [account.ap_id]}
416 }
417 |> ActivityPub.flag()
418 end
419 end
420
421 # disallow objects with bogus IDs
422 def handle_incoming(%{"id" => nil}, _options), do: :error
423 def handle_incoming(%{"id" => ""}, _options), do: :error
424 # length of https:// = 8, should validate better, but good enough for now.
425 def handle_incoming(%{"id" => id}, _options) when is_binary(id) and byte_size(id) < 8,
426 do: :error
427
428 # TODO: validate those with a Ecto scheme
429 # - tags
430 # - emoji
431 def handle_incoming(
432 %{"type" => "Create", "object" => %{"type" => objtype} = object} = data,
433 options
434 )
435 when objtype in ["Article", "Event", "Note", "Video", "Page", "Question", "Answer", "Audio"] do
436 actor = Containment.get_actor(data)
437
438 data =
439 Map.put(data, "actor", actor)
440 |> fix_addressing
441
442 with nil <- Activity.get_create_by_object_ap_id(object["id"]),
443 {:ok, %User{} = user} <- User.get_or_fetch_by_ap_id(data["actor"]) do
444 object = fix_object(object, options)
445
446 params = %{
447 to: data["to"],
448 object: object,
449 actor: user,
450 context: object["conversation"],
451 local: false,
452 published: data["published"],
453 additional:
454 Map.take(data, [
455 "cc",
456 "directMessage",
457 "id"
458 ])
459 }
460
461 with {:ok, created_activity} <- ActivityPub.create(params) do
462 reply_depth = (options[:depth] || 0) + 1
463
464 if Federator.allowed_thread_distance?(reply_depth) do
465 for reply_id <- replies(object) do
466 Pleroma.Workers.RemoteFetcherWorker.enqueue("fetch_remote", %{
467 "id" => reply_id,
468 "depth" => reply_depth
469 })
470 end
471 end
472
473 {:ok, created_activity}
474 end
475 else
476 %Activity{} = activity -> {:ok, activity}
477 _e -> :error
478 end
479 end
480
481 def handle_incoming(
482 %{"type" => "Listen", "object" => %{"type" => "Audio"} = object} = data,
483 options
484 ) do
485 actor = Containment.get_actor(data)
486
487 data =
488 Map.put(data, "actor", actor)
489 |> fix_addressing
490
491 with {:ok, %User{} = user} <- User.get_or_fetch_by_ap_id(data["actor"]) do
492 reply_depth = (options[:depth] || 0) + 1
493 options = Keyword.put(options, :depth, reply_depth)
494 object = fix_object(object, options)
495
496 params = %{
497 to: data["to"],
498 object: object,
499 actor: user,
500 context: nil,
501 local: false,
502 published: data["published"],
503 additional: Map.take(data, ["cc", "id"])
504 }
505
506 ActivityPub.listen(params)
507 else
508 _e -> :error
509 end
510 end
511
512 def handle_incoming(
513 %{"type" => "Follow", "object" => followed, "actor" => follower, "id" => id} = data,
514 _options
515 ) do
516 with %User{local: true} = followed <-
517 User.get_cached_by_ap_id(Containment.get_actor(%{"actor" => followed})),
518 {:ok, %User{} = follower} <-
519 User.get_or_fetch_by_ap_id(Containment.get_actor(%{"actor" => follower})),
520 {:ok, activity} <- ActivityPub.follow(follower, followed, id, false) do
521 with deny_follow_blocked <- Pleroma.Config.get([:user, :deny_follow_blocked]),
522 {_, false} <- {:user_blocked, User.blocks?(followed, follower) && deny_follow_blocked},
523 {_, false} <- {:user_locked, User.locked?(followed)},
524 {_, {:ok, follower}} <- {:follow, User.follow(follower, followed)},
525 {_, {:ok, _}} <-
526 {:follow_state_update, Utils.update_follow_state_for_all(activity, "accept")},
527 {:ok, _relationship} <-
528 FollowingRelationship.update(follower, followed, :follow_accept) do
529 ActivityPub.accept(%{
530 to: [follower.ap_id],
531 actor: followed,
532 object: data,
533 local: true
534 })
535 else
536 {:user_blocked, true} ->
537 {:ok, _} = Utils.update_follow_state_for_all(activity, "reject")
538 {:ok, _relationship} = FollowingRelationship.update(follower, followed, :follow_reject)
539
540 ActivityPub.reject(%{
541 to: [follower.ap_id],
542 actor: followed,
543 object: data,
544 local: true
545 })
546
547 {:follow, {:error, _}} ->
548 {:ok, _} = Utils.update_follow_state_for_all(activity, "reject")
549 {:ok, _relationship} = FollowingRelationship.update(follower, followed, :follow_reject)
550
551 ActivityPub.reject(%{
552 to: [follower.ap_id],
553 actor: followed,
554 object: data,
555 local: true
556 })
557
558 {:user_locked, true} ->
559 {:ok, _relationship} = FollowingRelationship.update(follower, followed, :follow_pending)
560 :noop
561 end
562
563 {:ok, activity}
564 else
565 _e ->
566 :error
567 end
568 end
569
570 def handle_incoming(
571 %{"type" => "Accept", "object" => follow_object, "actor" => _actor, "id" => id} = data,
572 _options
573 ) do
574 with actor <- Containment.get_actor(data),
575 {:ok, %User{} = followed} <- User.get_or_fetch_by_ap_id(actor),
576 {:ok, follow_activity} <- get_follow_activity(follow_object, followed),
577 {:ok, follow_activity} <- Utils.update_follow_state_for_all(follow_activity, "accept"),
578 %User{local: true} = follower <- User.get_cached_by_ap_id(follow_activity.data["actor"]),
579 {:ok, _relationship} <- FollowingRelationship.update(follower, followed, :follow_accept) do
580 ActivityPub.accept(%{
581 to: follow_activity.data["to"],
582 type: "Accept",
583 actor: followed,
584 object: follow_activity.data["id"],
585 local: false,
586 activity_id: id
587 })
588 else
589 _e -> :error
590 end
591 end
592
593 def handle_incoming(
594 %{"type" => "Reject", "object" => follow_object, "actor" => _actor, "id" => id} = data,
595 _options
596 ) do
597 with actor <- Containment.get_actor(data),
598 {:ok, %User{} = followed} <- User.get_or_fetch_by_ap_id(actor),
599 {:ok, follow_activity} <- get_follow_activity(follow_object, followed),
600 {:ok, follow_activity} <- Utils.update_follow_state_for_all(follow_activity, "reject"),
601 %User{local: true} = follower <- User.get_cached_by_ap_id(follow_activity.data["actor"]),
602 {:ok, _relationship} <- FollowingRelationship.update(follower, followed, :follow_reject),
603 {:ok, activity} <-
604 ActivityPub.reject(%{
605 to: follow_activity.data["to"],
606 type: "Reject",
607 actor: followed,
608 object: follow_activity.data["id"],
609 local: false,
610 activity_id: id
611 }) do
612 {:ok, activity}
613 else
614 _e -> :error
615 end
616 end
617
618 @misskey_reactions %{
619 "like" => "👍",
620 "love" => "❤️",
621 "laugh" => "😆",
622 "hmm" => "🤔",
623 "surprise" => "😮",
624 "congrats" => "🎉",
625 "angry" => "💢",
626 "confused" => "😥",
627 "rip" => "😇",
628 "pudding" => "🍮",
629 "star" => "⭐"
630 }
631
632 @doc "Rewrite misskey likes into EmojiReacts"
633 def handle_incoming(
634 %{
635 "type" => "Like",
636 "_misskey_reaction" => reaction
637 } = data,
638 options
639 ) do
640 data
641 |> Map.put("type", "EmojiReact")
642 |> Map.put("content", @misskey_reactions[reaction] || reaction)
643 |> handle_incoming(options)
644 end
645
646 def handle_incoming(%{"type" => "Like"} = data, _options) do
647 with {_, {:ok, cast_data_sym}} <-
648 {:casting_data,
649 data |> LikeValidator.cast_data() |> Ecto.Changeset.apply_action(:insert)},
650 cast_data = ObjectValidator.stringify_keys(Map.from_struct(cast_data_sym)),
651 :ok <- ObjectValidator.fetch_actor_and_object(cast_data),
652 {_, {:ok, cast_data}} <- {:ensure_context_presence, ensure_context_presence(cast_data)},
653 {_, {:ok, cast_data}} <-
654 {:ensure_recipients_presence, ensure_recipients_presence(cast_data)},
655 {_, {:ok, activity, _meta}} <-
656 {:common_pipeline, Pipeline.common_pipeline(cast_data, local: false)} do
657 {:ok, activity}
658 else
659 e -> {:error, e}
660 end
661 end
662
663 def handle_incoming(
664 %{
665 "type" => "EmojiReact",
666 "object" => object_id,
667 "actor" => _actor,
668 "id" => id,
669 "content" => emoji
670 } = data,
671 _options
672 ) do
673 with actor <- Containment.get_actor(data),
674 {:ok, %User{} = actor} <- User.get_or_fetch_by_ap_id(actor),
675 {:ok, object} <- get_obj_helper(object_id),
676 {:ok, activity, _object} <-
677 ActivityPub.react_with_emoji(actor, object, emoji, activity_id: id, local: false) do
678 {:ok, activity}
679 else
680 _e -> :error
681 end
682 end
683
684 def handle_incoming(
685 %{"type" => "Announce", "object" => object_id, "actor" => _actor, "id" => id} = data,
686 _options
687 ) do
688 with actor <- Containment.get_actor(data),
689 {:ok, %User{} = actor} <- User.get_or_fetch_by_ap_id(actor),
690 {:ok, object} <- get_embedded_obj_helper(object_id, actor),
691 public <- Visibility.is_public?(data),
692 {:ok, activity, _object} <- ActivityPub.announce(actor, object, id, false, public) do
693 {:ok, activity}
694 else
695 _e -> :error
696 end
697 end
698
699 def handle_incoming(
700 %{"type" => "Update", "object" => %{"type" => object_type} = object, "actor" => actor_id} =
701 data,
702 _options
703 )
704 when object_type in [
705 "Person",
706 "Application",
707 "Service",
708 "Organization"
709 ] do
710 with %User{ap_id: ^actor_id} = actor <- User.get_cached_by_ap_id(object["id"]) do
711 {:ok, new_user_data} = ActivityPub.user_data_from_user_object(object)
712
713 actor
714 |> User.upgrade_changeset(new_user_data, true)
715 |> User.update_and_set_cache()
716
717 ActivityPub.update(%{
718 local: false,
719 to: data["to"] || [],
720 cc: data["cc"] || [],
721 object: object,
722 actor: actor_id,
723 activity_id: data["id"]
724 })
725 else
726 e ->
727 Logger.error(e)
728 :error
729 end
730 end
731
732 # TODO: We presently assume that any actor on the same origin domain as the object being
733 # deleted has the rights to delete that object. A better way to validate whether or not
734 # the object should be deleted is to refetch the object URI, which should return either
735 # an error or a tombstone. This would allow us to verify that a deletion actually took
736 # place.
737 def handle_incoming(
738 %{"type" => "Delete", "object" => object_id, "actor" => actor, "id" => id} = data,
739 _options
740 ) do
741 object_id = Utils.get_ap_id(object_id)
742
743 with actor <- Containment.get_actor(data),
744 {:ok, %User{} = actor} <- User.get_or_fetch_by_ap_id(actor),
745 {:ok, object} <- get_obj_helper(object_id),
746 :ok <- Containment.contain_origin(actor.ap_id, object.data),
747 {:ok, activity} <-
748 ActivityPub.delete(object, local: false, activity_id: id, actor: actor.ap_id) do
749 {:ok, activity}
750 else
751 nil ->
752 case User.get_cached_by_ap_id(object_id) do
753 %User{ap_id: ^actor} = user ->
754 User.delete(user)
755
756 nil ->
757 :error
758 end
759
760 _e ->
761 :error
762 end
763 end
764
765 def handle_incoming(
766 %{
767 "type" => "Undo",
768 "object" => %{"type" => "Announce", "object" => object_id},
769 "actor" => _actor,
770 "id" => id
771 } = data,
772 _options
773 ) do
774 with actor <- Containment.get_actor(data),
775 {:ok, %User{} = actor} <- User.get_or_fetch_by_ap_id(actor),
776 {:ok, object} <- get_obj_helper(object_id),
777 {:ok, activity, _} <- ActivityPub.unannounce(actor, object, id, false) do
778 {:ok, activity}
779 else
780 _e -> :error
781 end
782 end
783
784 def handle_incoming(
785 %{
786 "type" => "Undo",
787 "object" => %{"type" => "Follow", "object" => followed},
788 "actor" => follower,
789 "id" => id
790 } = _data,
791 _options
792 ) do
793 with %User{local: true} = followed <- User.get_cached_by_ap_id(followed),
794 {:ok, %User{} = follower} <- User.get_or_fetch_by_ap_id(follower),
795 {:ok, activity} <- ActivityPub.unfollow(follower, followed, id, false) do
796 User.unfollow(follower, followed)
797 {:ok, activity}
798 else
799 _e -> :error
800 end
801 end
802
803 def handle_incoming(
804 %{
805 "type" => "Undo",
806 "object" => %{"type" => "EmojiReact", "id" => reaction_activity_id},
807 "actor" => _actor,
808 "id" => id
809 } = data,
810 _options
811 ) do
812 with actor <- Containment.get_actor(data),
813 {:ok, %User{} = actor} <- User.get_or_fetch_by_ap_id(actor),
814 {:ok, activity, _} <-
815 ActivityPub.unreact_with_emoji(actor, reaction_activity_id,
816 activity_id: id,
817 local: false
818 ) do
819 {:ok, activity}
820 else
821 _e -> :error
822 end
823 end
824
825 def handle_incoming(
826 %{
827 "type" => "Undo",
828 "object" => %{"type" => "Block", "object" => blocked},
829 "actor" => blocker,
830 "id" => id
831 } = _data,
832 _options
833 ) do
834 with %User{local: true} = blocked <- User.get_cached_by_ap_id(blocked),
835 {:ok, %User{} = blocker} <- User.get_or_fetch_by_ap_id(blocker),
836 {:ok, activity} <- ActivityPub.unblock(blocker, blocked, id, false) do
837 User.unblock(blocker, blocked)
838 {:ok, activity}
839 else
840 _e -> :error
841 end
842 end
843
844 def handle_incoming(
845 %{"type" => "Block", "object" => blocked, "actor" => blocker, "id" => id} = _data,
846 _options
847 ) do
848 with %User{local: true} = blocked = User.get_cached_by_ap_id(blocked),
849 {:ok, %User{} = blocker} = User.get_or_fetch_by_ap_id(blocker),
850 {:ok, activity} <- ActivityPub.block(blocker, blocked, id, false) do
851 User.unfollow(blocker, blocked)
852 User.block(blocker, blocked)
853 {:ok, activity}
854 else
855 _e -> :error
856 end
857 end
858
859 def handle_incoming(
860 %{
861 "type" => "Undo",
862 "object" => %{"type" => "Like", "object" => object_id},
863 "actor" => _actor,
864 "id" => id
865 } = data,
866 _options
867 ) do
868 with actor <- Containment.get_actor(data),
869 {:ok, %User{} = actor} <- User.get_or_fetch_by_ap_id(actor),
870 {:ok, object} <- get_obj_helper(object_id),
871 {:ok, activity, _, _} <- ActivityPub.unlike(actor, object, id, false) do
872 {:ok, activity}
873 else
874 _e -> :error
875 end
876 end
877
878 # For Undos that don't have the complete object attached, try to find it in our database.
879 def handle_incoming(
880 %{
881 "type" => "Undo",
882 "object" => object
883 } = activity,
884 options
885 )
886 when is_binary(object) do
887 with %Activity{data: data} <- Activity.get_by_ap_id(object) do
888 activity
889 |> Map.put("object", data)
890 |> handle_incoming(options)
891 else
892 _e -> :error
893 end
894 end
895
896 def handle_incoming(
897 %{
898 "type" => "Move",
899 "actor" => origin_actor,
900 "object" => origin_actor,
901 "target" => target_actor
902 },
903 _options
904 ) do
905 with %User{} = origin_user <- User.get_cached_by_ap_id(origin_actor),
906 {:ok, %User{} = target_user} <- User.get_or_fetch_by_ap_id(target_actor),
907 true <- origin_actor in target_user.also_known_as do
908 ActivityPub.move(origin_user, target_user, false)
909 else
910 _e -> :error
911 end
912 end
913
914 def handle_incoming(_, _), do: :error
915
916 @spec get_obj_helper(String.t(), Keyword.t()) :: {:ok, Object.t()} | nil
917 def get_obj_helper(id, options \\ []) do
918 case Object.normalize(id, true, options) do
919 %Object{} = object -> {:ok, object}
920 _ -> nil
921 end
922 end
923
924 @spec get_embedded_obj_helper(String.t() | Object.t(), User.t()) :: {:ok, Object.t()} | nil
925 def get_embedded_obj_helper(%{"attributedTo" => attributed_to, "id" => object_id} = data, %User{
926 ap_id: ap_id
927 })
928 when attributed_to == ap_id do
929 with {:ok, activity} <-
930 handle_incoming(%{
931 "type" => "Create",
932 "to" => data["to"],
933 "cc" => data["cc"],
934 "actor" => attributed_to,
935 "object" => data
936 }) do
937 {:ok, Object.normalize(activity)}
938 else
939 _ -> get_obj_helper(object_id)
940 end
941 end
942
943 def get_embedded_obj_helper(object_id, _) do
944 get_obj_helper(object_id)
945 end
946
947 def set_reply_to_uri(%{"inReplyTo" => in_reply_to} = object) when is_binary(in_reply_to) do
948 with false <- String.starts_with?(in_reply_to, "http"),
949 {:ok, %{data: replied_to_object}} <- get_obj_helper(in_reply_to) do
950 Map.put(object, "inReplyTo", replied_to_object["external_url"] || in_reply_to)
951 else
952 _e -> object
953 end
954 end
955
956 def set_reply_to_uri(obj), do: obj
957
958 @doc """
959 Serialized Mastodon-compatible `replies` collection containing _self-replies_.
960 Based on Mastodon's ActivityPub::NoteSerializer#replies.
961 """
962 def set_replies(obj_data) do
963 replies_uris =
964 with limit when limit > 0 <-
965 Pleroma.Config.get([:activitypub, :note_replies_output_limit], 0),
966 %Object{} = object <- Object.get_cached_by_ap_id(obj_data["id"]) do
967 object
968 |> Object.self_replies()
969 |> select([o], fragment("?->>'id'", o.data))
970 |> limit(^limit)
971 |> Repo.all()
972 else
973 _ -> []
974 end
975
976 set_replies(obj_data, replies_uris)
977 end
978
979 defp set_replies(obj, []) do
980 obj
981 end
982
983 defp set_replies(obj, replies_uris) do
984 replies_collection = %{
985 "type" => "Collection",
986 "items" => replies_uris
987 }
988
989 Map.merge(obj, %{"replies" => replies_collection})
990 end
991
992 def replies(%{"replies" => %{"first" => %{"items" => items}}}) when not is_nil(items) do
993 items
994 end
995
996 def replies(%{"replies" => %{"items" => items}}) when not is_nil(items) do
997 items
998 end
999
1000 def replies(_), do: []
1001
1002 # Prepares the object of an outgoing create activity.
1003 def prepare_object(object) do
1004 object
1005 |> set_sensitive
1006 |> add_hashtags
1007 |> add_mention_tags
1008 |> add_emoji_tags
1009 |> add_attributed_to
1010 |> prepare_attachments
1011 |> set_conversation
1012 |> set_reply_to_uri
1013 |> set_replies
1014 |> strip_internal_fields
1015 |> strip_internal_tags
1016 |> set_type
1017 end
1018
1019 # @doc
1020 # """
1021 # internal -> Mastodon
1022 # """
1023
1024 def prepare_outgoing(%{"type" => activity_type, "object" => object_id} = data)
1025 when activity_type in ["Create", "Listen"] do
1026 object =
1027 object_id
1028 |> Object.normalize()
1029 |> Map.get(:data)
1030 |> prepare_object
1031
1032 data =
1033 data
1034 |> Map.put("object", object)
1035 |> Map.merge(Utils.make_json_ld_header())
1036 |> Map.delete("bcc")
1037
1038 {:ok, data}
1039 end
1040
1041 def prepare_outgoing(%{"type" => "Announce", "actor" => ap_id, "object" => object_id} = data) do
1042 object =
1043 object_id
1044 |> Object.normalize()
1045
1046 data =
1047 if Visibility.is_private?(object) && object.data["actor"] == ap_id do
1048 data |> Map.put("object", object |> Map.get(:data) |> prepare_object)
1049 else
1050 data |> maybe_fix_object_url
1051 end
1052
1053 data =
1054 data
1055 |> strip_internal_fields
1056 |> Map.merge(Utils.make_json_ld_header())
1057 |> Map.delete("bcc")
1058
1059 {:ok, data}
1060 end
1061
1062 # Mastodon Accept/Reject requires a non-normalized object containing the actor URIs,
1063 # because of course it does.
1064 def prepare_outgoing(%{"type" => "Accept"} = data) do
1065 with follow_activity <- Activity.normalize(data["object"]) do
1066 object = %{
1067 "actor" => follow_activity.actor,
1068 "object" => follow_activity.data["object"],
1069 "id" => follow_activity.data["id"],
1070 "type" => "Follow"
1071 }
1072
1073 data =
1074 data
1075 |> Map.put("object", object)
1076 |> Map.merge(Utils.make_json_ld_header())
1077
1078 {:ok, data}
1079 end
1080 end
1081
1082 def prepare_outgoing(%{"type" => "Reject"} = data) do
1083 with follow_activity <- Activity.normalize(data["object"]) do
1084 object = %{
1085 "actor" => follow_activity.actor,
1086 "object" => follow_activity.data["object"],
1087 "id" => follow_activity.data["id"],
1088 "type" => "Follow"
1089 }
1090
1091 data =
1092 data
1093 |> Map.put("object", object)
1094 |> Map.merge(Utils.make_json_ld_header())
1095
1096 {:ok, data}
1097 end
1098 end
1099
1100 def prepare_outgoing(%{"type" => _type} = data) do
1101 data =
1102 data
1103 |> strip_internal_fields
1104 |> maybe_fix_object_url
1105 |> Map.merge(Utils.make_json_ld_header())
1106
1107 {:ok, data}
1108 end
1109
1110 def maybe_fix_object_url(%{"object" => object} = data) when is_binary(object) do
1111 with false <- String.starts_with?(object, "http"),
1112 {:fetch, {:ok, relative_object}} <- {:fetch, get_obj_helper(object)},
1113 %{data: %{"external_url" => external_url}} when not is_nil(external_url) <-
1114 relative_object do
1115 Map.put(data, "object", external_url)
1116 else
1117 {:fetch, e} ->
1118 Logger.error("Couldn't fetch #{object} #{inspect(e)}")
1119 data
1120
1121 _ ->
1122 data
1123 end
1124 end
1125
1126 def maybe_fix_object_url(data), do: data
1127
1128 def add_hashtags(object) do
1129 tags =
1130 (object["tag"] || [])
1131 |> Enum.map(fn
1132 # Expand internal representation tags into AS2 tags.
1133 tag when is_binary(tag) ->
1134 %{
1135 "href" => Pleroma.Web.Endpoint.url() <> "/tags/#{tag}",
1136 "name" => "##{tag}",
1137 "type" => "Hashtag"
1138 }
1139
1140 # Do not process tags which are already AS2 tag objects.
1141 tag when is_map(tag) ->
1142 tag
1143 end)
1144
1145 Map.put(object, "tag", tags)
1146 end
1147
1148 def add_mention_tags(object) do
1149 {enabled_receivers, disabled_receivers} = Utils.get_notified_from_object(object)
1150 potential_receivers = enabled_receivers ++ disabled_receivers
1151 mentions = Enum.map(potential_receivers, &build_mention_tag/1)
1152
1153 tags = object["tag"] || []
1154 Map.put(object, "tag", tags ++ mentions)
1155 end
1156
1157 defp build_mention_tag(%{ap_id: ap_id, nickname: nickname} = _) do
1158 %{"type" => "Mention", "href" => ap_id, "name" => "@#{nickname}"}
1159 end
1160
1161 def take_emoji_tags(%User{emoji: emoji}) do
1162 emoji
1163 |> Enum.flat_map(&Map.to_list/1)
1164 |> Enum.map(&build_emoji_tag/1)
1165 end
1166
1167 # TODO: we should probably send mtime instead of unix epoch time for updated
1168 def add_emoji_tags(%{"emoji" => emoji} = object) do
1169 tags = object["tag"] || []
1170
1171 out = Enum.map(emoji, &build_emoji_tag/1)
1172
1173 Map.put(object, "tag", tags ++ out)
1174 end
1175
1176 def add_emoji_tags(object), do: object
1177
1178 defp build_emoji_tag({name, url}) do
1179 %{
1180 "icon" => %{"url" => url, "type" => "Image"},
1181 "name" => ":" <> name <> ":",
1182 "type" => "Emoji",
1183 "updated" => "1970-01-01T00:00:00Z",
1184 "id" => url
1185 }
1186 end
1187
1188 def set_conversation(object) do
1189 Map.put(object, "conversation", object["context"])
1190 end
1191
1192 def set_sensitive(object) do
1193 tags = object["tag"] || []
1194 Map.put(object, "sensitive", "nsfw" in tags)
1195 end
1196
1197 def set_type(%{"type" => "Answer"} = object) do
1198 Map.put(object, "type", "Note")
1199 end
1200
1201 def set_type(object), do: object
1202
1203 def add_attributed_to(object) do
1204 attributed_to = object["attributedTo"] || object["actor"]
1205 Map.put(object, "attributedTo", attributed_to)
1206 end
1207
1208 def prepare_attachments(object) do
1209 attachments =
1210 (object["attachment"] || [])
1211 |> Enum.map(fn data ->
1212 [%{"mediaType" => media_type, "href" => href} | _] = data["url"]
1213 %{"url" => href, "mediaType" => media_type, "name" => data["name"], "type" => "Document"}
1214 end)
1215
1216 Map.put(object, "attachment", attachments)
1217 end
1218
1219 def strip_internal_fields(object) do
1220 object
1221 |> Map.drop(Pleroma.Constants.object_internal_fields())
1222 end
1223
1224 defp strip_internal_tags(%{"tag" => tags} = object) do
1225 tags = Enum.filter(tags, fn x -> is_map(x) end)
1226
1227 Map.put(object, "tag", tags)
1228 end
1229
1230 defp strip_internal_tags(object), do: object
1231
1232 def perform(:user_upgrade, user) do
1233 # we pass a fake user so that the followers collection is stripped away
1234 old_follower_address = User.ap_followers(%User{nickname: user.nickname})
1235
1236 from(
1237 a in Activity,
1238 where: ^old_follower_address in a.recipients,
1239 update: [
1240 set: [
1241 recipients:
1242 fragment(
1243 "array_replace(?,?,?)",
1244 a.recipients,
1245 ^old_follower_address,
1246 ^user.follower_address
1247 )
1248 ]
1249 ]
1250 )
1251 |> Repo.update_all([])
1252 end
1253
1254 def upgrade_user_from_ap_id(ap_id) do
1255 with %User{local: false} = user <- User.get_cached_by_ap_id(ap_id),
1256 {:ok, data} <- ActivityPub.fetch_and_prepare_user_from_ap_id(ap_id),
1257 already_ap <- User.ap_enabled?(user),
1258 {:ok, user} <- upgrade_user(user, data) do
1259 if not already_ap do
1260 TransmogrifierWorker.enqueue("user_upgrade", %{"user_id" => user.id})
1261 end
1262
1263 {:ok, user}
1264 else
1265 %User{} = user -> {:ok, user}
1266 e -> e
1267 end
1268 end
1269
1270 defp upgrade_user(user, data) do
1271 user
1272 |> User.upgrade_changeset(data, true)
1273 |> User.update_and_set_cache()
1274 end
1275
1276 def maybe_fix_user_url(%{"url" => url} = data) when is_map(url) do
1277 Map.put(data, "url", url["href"])
1278 end
1279
1280 def maybe_fix_user_url(data), do: data
1281
1282 def maybe_fix_user_object(data), do: maybe_fix_user_url(data)
1283
1284 defp ensure_context_presence(%{"context" => context} = data) when is_binary(context),
1285 do: {:ok, data}
1286
1287 defp ensure_context_presence(%{"object" => object} = data) when is_binary(object) do
1288 with %{data: %{"context" => context}} when is_binary(context) <- Object.normalize(object) do
1289 {:ok, Map.put(data, "context", context)}
1290 else
1291 _ ->
1292 {:error, :no_context}
1293 end
1294 end
1295
1296 defp ensure_context_presence(_) do
1297 {:error, :no_context}
1298 end
1299
1300 defp ensure_recipients_presence(%{"to" => [_ | _], "cc" => [_ | _]} = data),
1301 do: {:ok, data}
1302
1303 defp ensure_recipients_presence(%{"object" => object} = data) do
1304 case Object.normalize(object) do
1305 %{data: %{"actor" => actor}} ->
1306 data =
1307 data
1308 |> Map.put("to", [actor])
1309 |> Map.put("cc", data["cc"] || [])
1310
1311 {:ok, data}
1312
1313 nil ->
1314 {:error, :no_object}
1315
1316 _ ->
1317 {:error, :no_actor}
1318 end
1319 end
1320
1321 defp ensure_recipients_presence(_) do
1322 {:error, :no_object}
1323 end
1324 end