1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
5 defmodule Pleroma.Web.ActivityPub.Transmogrifier do
7 A module to handle coding from internal to wire ActivityPub and back.
10 alias Pleroma.EctoType.ActivityPub.ObjectValidators
13 alias Pleroma.Object.Containment
16 alias Pleroma.Web.ActivityPub.ActivityPub
17 alias Pleroma.Web.ActivityPub.Builder
18 alias Pleroma.Web.ActivityPub.ObjectValidator
19 alias Pleroma.Web.ActivityPub.Pipeline
20 alias Pleroma.Web.ActivityPub.Utils
21 alias Pleroma.Web.ActivityPub.Visibility
22 alias Pleroma.Web.Federator
23 alias Pleroma.Workers.TransmogrifierWorker
28 require Pleroma.Constants
31 Modifies an incoming AP object (mastodon format) to our internal format.
33 def fix_object(object, options \\ []) do
35 |> strip_internal_fields()
40 |> fix_in_reply_to(options)
48 def fix_summary(%{"summary" => nil} = object) do
49 Map.put(object, "summary", "")
52 def fix_summary(%{"summary" => _} = object) do
53 # summary is present, nothing to do
57 def fix_summary(object), do: Map.put(object, "summary", "")
59 def fix_addressing_list(map, field) do
64 Map.put(map, field, Enum.filter(addrs, &is_binary/1))
67 Map.put(map, field, [addrs])
70 Map.put(map, field, [])
74 # if directMessage flag is set to true, leave the addressing alone
75 def fix_explicit_addressing(%{"directMessage" => true} = object, _follower_collection),
78 def fix_explicit_addressing(%{"to" => to, "cc" => cc} = object, follower_collection) do
80 Utils.determine_explicit_mentions(object) ++
81 [Pleroma.Constants.as_public(), follower_collection]
83 explicit_to = Enum.filter(to, fn x -> x in explicit_mentions end)
84 explicit_cc = Enum.filter(to, fn x -> x not in explicit_mentions end)
89 |> Enum.reject(fn x -> String.ends_with?(x, "/followers") and x != follower_collection end)
93 |> Map.put("to", explicit_to)
94 |> Map.put("cc", final_cc)
97 # if as:Public is addressed, then make sure the followers collection is also addressed
98 # so that the activities will be delivered to local users.
99 def fix_implicit_addressing(%{"to" => to, "cc" => cc} = object, followers_collection) do
100 recipients = to ++ cc
102 if followers_collection not in recipients do
104 Pleroma.Constants.as_public() in cc ->
105 to = to ++ [followers_collection]
106 Map.put(object, "to", to)
108 Pleroma.Constants.as_public() in to ->
109 cc = cc ++ [followers_collection]
110 Map.put(object, "cc", cc)
120 def fix_addressing(object) do
121 {:ok, %User{follower_address: follower_collection}} =
123 |> Containment.get_actor()
124 |> User.get_or_fetch_by_ap_id()
127 |> fix_addressing_list("to")
128 |> fix_addressing_list("cc")
129 |> fix_addressing_list("bto")
130 |> fix_addressing_list("bcc")
131 |> fix_explicit_addressing(follower_collection)
132 |> fix_implicit_addressing(follower_collection)
135 def fix_actor(%{"attributedTo" => actor} = object) do
136 actor = Containment.get_actor(%{"actor" => actor})
138 # TODO: Remove actor field for Objects
140 |> Map.put("actor", actor)
141 |> Map.put("attributedTo", actor)
144 def fix_in_reply_to(object, options \\ [])
146 def fix_in_reply_to(%{"inReplyTo" => in_reply_to} = object, options)
147 when not is_nil(in_reply_to) do
148 in_reply_to_id = prepare_in_reply_to(in_reply_to)
149 depth = (options[:depth] || 0) + 1
151 if Federator.allowed_thread_distance?(depth) do
152 with {:ok, replied_object} <- get_obj_helper(in_reply_to_id, options),
153 %Activity{} <- Activity.get_create_by_object_ap_id(replied_object.data["id"]) do
155 |> Map.put("inReplyTo", replied_object.data["id"])
156 |> Map.put("context", replied_object.data["context"] || object["conversation"])
157 |> Map.drop(["conversation", "inReplyToAtomUri"])
160 Logger.warn("Couldn't fetch #{inspect(in_reply_to_id)}, error: #{inspect(e)}")
168 def fix_in_reply_to(object, _options), do: object
170 defp prepare_in_reply_to(in_reply_to) do
172 is_bitstring(in_reply_to) ->
175 is_map(in_reply_to) && is_bitstring(in_reply_to["id"]) ->
178 is_list(in_reply_to) && is_bitstring(Enum.at(in_reply_to, 0)) ->
179 Enum.at(in_reply_to, 0)
186 def fix_context(object) do
187 context = object["context"] || object["conversation"] || Utils.generate_context_id()
190 |> Map.put("context", context)
191 |> Map.drop(["conversation"])
194 def fix_attachments(%{"attachment" => attachment} = object) when is_list(attachment) do
196 Enum.map(attachment, fn data ->
199 is_list(data["url"]) -> List.first(data["url"])
200 is_map(data["url"]) -> data["url"]
206 is_map(url) && MIME.valid?(url["mediaType"]) -> url["mediaType"]
207 MIME.valid?(data["mediaType"]) -> data["mediaType"]
208 MIME.valid?(data["mimeType"]) -> data["mimeType"]
214 is_map(url) && is_binary(url["href"]) -> url["href"]
215 is_binary(data["url"]) -> data["url"]
216 is_binary(data["href"]) -> data["href"]
224 "type" => Map.get(url || %{}, "type", "Link")
226 |> Maps.put_if_present("mediaType", media_type)
229 "url" => [attachment_url],
230 "type" => data["type"] || "Document"
232 |> Maps.put_if_present("mediaType", media_type)
233 |> Maps.put_if_present("name", data["name"])
234 |> Maps.put_if_present("blurhash", data["blurhash"])
241 Map.put(object, "attachment", attachments)
244 def fix_attachments(%{"attachment" => attachment} = object) when is_map(attachment) do
246 |> Map.put("attachment", [attachment])
250 def fix_attachments(object), do: object
252 def fix_url(%{"url" => url} = object) when is_map(url) do
253 Map.put(object, "url", url["href"])
256 def fix_url(%{"url" => url} = object) when is_list(url) do
257 first_element = Enum.at(url, 0)
261 is_bitstring(first_element) -> first_element
262 is_map(first_element) -> first_element["href"] || ""
266 Map.put(object, "url", url_string)
269 def fix_url(object), do: object
271 def fix_emoji(%{"tag" => tags} = object) when is_list(tags) do
274 |> Enum.filter(fn data -> is_map(data) and data["type"] == "Emoji" and data["icon"] end)
275 |> Enum.reduce(%{}, fn data, mapping ->
276 name = String.trim(data["name"], ":")
278 Map.put(mapping, name, data["icon"]["url"])
281 Map.put(object, "emoji", emoji)
284 def fix_emoji(%{"tag" => %{"type" => "Emoji"} = tag} = object) do
285 name = String.trim(tag["name"], ":")
286 emoji = %{name => tag["icon"]["url"]}
288 Map.put(object, "emoji", emoji)
291 def fix_emoji(object), do: object
293 def fix_tag(%{"tag" => tag} = object) when is_list(tag) do
296 |> Enum.filter(fn data -> data["type"] == "Hashtag" and data["name"] end)
298 %{"name" => "#" <> hashtag} -> String.downcase(hashtag)
299 %{"name" => hashtag} -> String.downcase(hashtag)
302 Map.put(object, "tag", tag ++ tags)
305 def fix_tag(%{"tag" => %{} = tag} = object) do
307 |> Map.put("tag", [tag])
311 def fix_tag(object), do: object
313 # content map usually only has one language so this will do for now.
314 def fix_content_map(%{"contentMap" => content_map} = object) do
315 content_groups = Map.to_list(content_map)
316 {_, content} = Enum.at(content_groups, 0)
318 Map.put(object, "content", content)
321 def fix_content_map(object), do: object
323 defp fix_type(%{"type" => "Note", "inReplyTo" => reply_id, "name" => _} = object, options)
324 when is_binary(reply_id) do
325 options = Keyword.put(options, :fetch, true)
327 with %Object{data: %{"type" => "Question"}} <- Object.normalize(reply_id, options) do
328 Map.put(object, "type", "Answer")
334 defp fix_type(object, _options), do: object
336 # Reduce the object list to find the reported user.
337 defp get_reported(objects) do
338 Enum.reduce_while(objects, nil, fn ap_id, _ ->
339 with %User{} = user <- User.get_cached_by_ap_id(ap_id) do
347 # Compatibility wrapper for Mastodon votes
348 defp handle_create(%{"object" => %{"type" => "Answer"}} = data, _user) do
349 handle_incoming(data)
352 defp handle_create(%{"object" => object} = data, user) do
357 context: object["context"],
359 published: data["published"],
367 |> ActivityPub.create()
370 def handle_incoming(data, options \\ [])
372 # Flag objects are placed ahead of the ID check because Mastodon 2.8 and earlier send them
374 def handle_incoming(%{"type" => "Flag", "object" => objects, "actor" => actor} = data, _options) do
375 with context <- data["context"] || Utils.generate_context_id(),
376 content <- data["content"] || "",
377 %User{} = actor <- User.get_cached_by_ap_id(actor),
378 # Reduce the object list to find the reported user.
379 %User{} = account <- get_reported(objects),
380 # Remove the reported user from the object list.
381 statuses <- Enum.filter(objects, fn ap_id -> ap_id != account.ap_id end) do
388 additional: %{"cc" => [account.ap_id]}
390 |> ActivityPub.flag()
394 # disallow objects with bogus IDs
395 def handle_incoming(%{"id" => nil}, _options), do: :error
396 def handle_incoming(%{"id" => ""}, _options), do: :error
397 # length of https:// = 8, should validate better, but good enough for now.
398 def handle_incoming(%{"id" => id}, _options) when is_binary(id) and byte_size(id) < 8,
401 # TODO: validate those with a Ecto scheme
405 %{"type" => "Create", "object" => %{"type" => "Page"} = object} = data,
408 actor = Containment.get_actor(data)
410 with nil <- Activity.get_create_by_object_ap_id(object["id"]),
411 {:ok, %User{} = user} <- User.get_or_fetch_by_ap_id(actor) do
414 |> Map.put("object", fix_object(object, options))
415 |> Map.put("actor", actor)
418 with {:ok, created_activity} <- handle_create(data, user) do
419 reply_depth = (options[:depth] || 0) + 1
421 if Federator.allowed_thread_distance?(reply_depth) do
422 for reply_id <- replies(object) do
423 Pleroma.Workers.RemoteFetcherWorker.enqueue("fetch_remote", %{
425 "depth" => reply_depth
430 {:ok, created_activity}
433 %Activity{} = activity -> {:ok, activity}
439 %{"type" => "Listen", "object" => %{"type" => "Audio"} = object} = data,
442 actor = Containment.get_actor(data)
445 Map.put(data, "actor", actor)
448 with {:ok, %User{} = user} <- User.get_or_fetch_by_ap_id(data["actor"]) do
449 reply_depth = (options[:depth] || 0) + 1
450 options = Keyword.put(options, :depth, reply_depth)
451 object = fix_object(object, options)
459 published: data["published"],
460 additional: Map.take(data, ["cc", "id"])
463 ActivityPub.listen(params)
469 @misskey_reactions %{
483 @doc "Rewrite misskey likes into EmojiReacts"
487 "_misskey_reaction" => reaction
492 |> Map.put("type", "EmojiReact")
493 |> Map.put("content", @misskey_reactions[reaction] || reaction)
494 |> handle_incoming(options)
498 %{"type" => "Create", "object" => %{"type" => objtype, "id" => obj_id}} = data,
501 when objtype in ~w{Question Answer ChatMessage Audio Video Event Article Note} do
502 fetch_options = Keyword.put(options, :depth, (options[:depth] || 0) + 1)
506 |> strip_internal_fields()
507 |> fix_type(fetch_options)
508 |> fix_in_reply_to(fetch_options)
510 data = Map.put(data, "object", object)
511 options = Keyword.put(options, :local, false)
513 with {:ok, %User{}} <- ObjectValidator.fetch_actor(data),
514 nil <- Activity.get_create_by_object_ap_id(obj_id),
515 {:ok, activity, _} <- Pipeline.common_pipeline(data, options) do
518 %Activity{} = activity -> {:ok, activity}
523 def handle_incoming(%{"type" => type} = data, _options)
524 when type in ~w{Like EmojiReact Announce} do
525 with :ok <- ObjectValidator.fetch_actor_and_object(data),
526 {:ok, activity, _meta} <-
527 Pipeline.common_pipeline(data, local: false) do
535 %{"type" => type} = data,
538 when type in ~w{Update Block Follow Accept Reject} do
539 with {:ok, %User{}} <- ObjectValidator.fetch_actor(data),
540 {:ok, activity, _} <-
541 Pipeline.common_pipeline(data, local: false) do
547 %{"type" => "Delete"} = data,
550 with {:ok, activity, _} <-
551 Pipeline.common_pipeline(data, local: false) do
554 {:error, {:validate, _}} = e ->
555 # Check if we have a create activity for this
556 with {:ok, object_id} <- ObjectValidators.ObjectID.cast(data["object"]),
557 %Activity{data: %{"actor" => actor}} <-
558 Activity.create_by_object_ap_id(object_id) |> Repo.one(),
559 # We have one, insert a tombstone and retry
560 {:ok, tombstone_data, _} <- Builder.tombstone(actor, object_id),
561 {:ok, _tombstone} <- Object.create(tombstone_data) do
562 handle_incoming(data)
572 "object" => %{"type" => "Follow", "object" => followed},
578 with %User{local: true} = followed <- User.get_cached_by_ap_id(followed),
579 {:ok, %User{} = follower} <- User.get_or_fetch_by_ap_id(follower),
580 {:ok, activity} <- ActivityPub.unfollow(follower, followed, id, false) do
581 User.unfollow(follower, followed)
591 "object" => %{"type" => type}
595 when type in ["Like", "EmojiReact", "Announce", "Block"] do
596 with {:ok, activity, _} <- Pipeline.common_pipeline(data, local: false) do
601 # For Undos that don't have the complete object attached, try to find it in our database.
609 when is_binary(object) do
610 with %Activity{data: data} <- Activity.get_by_ap_id(object) do
612 |> Map.put("object", data)
613 |> handle_incoming(options)
622 "actor" => origin_actor,
623 "object" => origin_actor,
624 "target" => target_actor
628 with %User{} = origin_user <- User.get_cached_by_ap_id(origin_actor),
629 {:ok, %User{} = target_user} <- User.get_or_fetch_by_ap_id(target_actor),
630 true <- origin_actor in target_user.also_known_as do
631 ActivityPub.move(origin_user, target_user, false)
637 def handle_incoming(_, _), do: :error
639 @spec get_obj_helper(String.t(), Keyword.t()) :: {:ok, Object.t()} | nil
640 def get_obj_helper(id, options \\ []) do
641 options = Keyword.put(options, :fetch, true)
643 case Object.normalize(id, options) do
644 %Object{} = object -> {:ok, object}
649 @spec get_embedded_obj_helper(String.t() | Object.t(), User.t()) :: {:ok, Object.t()} | nil
650 def get_embedded_obj_helper(%{"attributedTo" => attributed_to, "id" => object_id} = data, %User{
653 when attributed_to == ap_id do
654 with {:ok, activity} <-
659 "actor" => attributed_to,
662 {:ok, Object.normalize(activity, fetch: false)}
664 _ -> get_obj_helper(object_id)
668 def get_embedded_obj_helper(object_id, _) do
669 get_obj_helper(object_id)
672 def set_reply_to_uri(%{"inReplyTo" => in_reply_to} = object) when is_binary(in_reply_to) do
673 with false <- String.starts_with?(in_reply_to, "http"),
674 {:ok, %{data: replied_to_object}} <- get_obj_helper(in_reply_to) do
675 Map.put(object, "inReplyTo", replied_to_object["external_url"] || in_reply_to)
681 def set_reply_to_uri(obj), do: obj
684 Serialized Mastodon-compatible `replies` collection containing _self-replies_.
685 Based on Mastodon's ActivityPub::NoteSerializer#replies.
687 def set_replies(obj_data) do
689 with limit when limit > 0 <-
690 Pleroma.Config.get([:activitypub, :note_replies_output_limit], 0),
691 %Object{} = object <- Object.get_cached_by_ap_id(obj_data["id"]) do
693 |> Object.self_replies()
694 |> select([o], fragment("?->>'id'", o.data))
701 set_replies(obj_data, replies_uris)
704 defp set_replies(obj, []) do
708 defp set_replies(obj, replies_uris) do
709 replies_collection = %{
710 "type" => "Collection",
711 "items" => replies_uris
714 Map.merge(obj, %{"replies" => replies_collection})
717 def replies(%{"replies" => %{"first" => %{"items" => items}}}) when not is_nil(items) do
721 def replies(%{"replies" => %{"items" => items}}) when not is_nil(items) do
725 def replies(_), do: []
727 # Prepares the object of an outgoing create activity.
728 def prepare_object(object) do
734 |> prepare_attachments
738 |> strip_internal_fields
739 |> strip_internal_tags
745 # internal -> Mastodon
748 def prepare_outgoing(%{"type" => activity_type, "object" => object_id} = data)
749 when activity_type in ["Create", "Listen"] do
752 |> Object.normalize(fetch: false)
758 |> Map.put("object", object)
759 |> Map.merge(Utils.make_json_ld_header())
765 def prepare_outgoing(%{"type" => "Announce", "actor" => ap_id, "object" => object_id} = data) do
768 |> Object.normalize(fetch: false)
771 if Visibility.is_private?(object) && object.data["actor"] == ap_id do
772 data |> Map.put("object", object |> Map.get(:data) |> prepare_object)
774 data |> maybe_fix_object_url
779 |> strip_internal_fields
780 |> Map.merge(Utils.make_json_ld_header())
786 # Mastodon Accept/Reject requires a non-normalized object containing the actor URIs,
787 # because of course it does.
788 def prepare_outgoing(%{"type" => "Accept"} = data) do
789 with follow_activity <- Activity.normalize(data["object"]) do
791 "actor" => follow_activity.actor,
792 "object" => follow_activity.data["object"],
793 "id" => follow_activity.data["id"],
799 |> Map.put("object", object)
800 |> Map.merge(Utils.make_json_ld_header())
806 def prepare_outgoing(%{"type" => "Reject"} = data) do
807 with follow_activity <- Activity.normalize(data["object"]) do
809 "actor" => follow_activity.actor,
810 "object" => follow_activity.data["object"],
811 "id" => follow_activity.data["id"],
817 |> Map.put("object", object)
818 |> Map.merge(Utils.make_json_ld_header())
824 def prepare_outgoing(%{"type" => _type} = data) do
827 |> strip_internal_fields
828 |> maybe_fix_object_url
829 |> Map.merge(Utils.make_json_ld_header())
834 def maybe_fix_object_url(%{"object" => object} = data) when is_binary(object) do
835 with false <- String.starts_with?(object, "http"),
836 {:fetch, {:ok, relative_object}} <- {:fetch, get_obj_helper(object)},
837 %{data: %{"external_url" => external_url}} when not is_nil(external_url) <-
839 Map.put(data, "object", external_url)
842 Logger.error("Couldn't fetch #{object} #{inspect(e)}")
850 def maybe_fix_object_url(data), do: data
852 def add_hashtags(object) do
854 (object["tag"] || [])
856 # Expand internal representation tags into AS2 tags.
857 tag when is_binary(tag) ->
859 "href" => Pleroma.Web.Endpoint.url() <> "/tags/#{tag}",
864 # Do not process tags which are already AS2 tag objects.
865 tag when is_map(tag) ->
869 Map.put(object, "tag", tags)
872 # TODO These should be added on our side on insertion, it doesn't make much
873 # sense to regenerate these all the time
874 def add_mention_tags(object) do
875 to = object["to"] || []
876 cc = object["cc"] || []
877 mentioned = User.get_users_from_set(to ++ cc, local_only: false)
879 mentions = Enum.map(mentioned, &build_mention_tag/1)
881 tags = object["tag"] || []
882 Map.put(object, "tag", tags ++ mentions)
885 defp build_mention_tag(%{ap_id: ap_id, nickname: nickname} = _) do
886 %{"type" => "Mention", "href" => ap_id, "name" => "@#{nickname}"}
889 def take_emoji_tags(%User{emoji: emoji}) do
892 |> Enum.map(&build_emoji_tag/1)
895 # TODO: we should probably send mtime instead of unix epoch time for updated
896 def add_emoji_tags(%{"emoji" => emoji} = object) do
897 tags = object["tag"] || []
899 out = Enum.map(emoji, &build_emoji_tag/1)
901 Map.put(object, "tag", tags ++ out)
904 def add_emoji_tags(object), do: object
906 defp build_emoji_tag({name, url}) do
908 "icon" => %{"url" => "#{URI.encode(url)}", "type" => "Image"},
909 "name" => ":" <> name <> ":",
911 "updated" => "1970-01-01T00:00:00Z",
916 def set_conversation(object) do
917 Map.put(object, "conversation", object["context"])
920 def set_type(%{"type" => "Answer"} = object) do
921 Map.put(object, "type", "Note")
924 def set_type(object), do: object
926 def add_attributed_to(object) do
927 attributed_to = object["attributedTo"] || object["actor"]
928 Map.put(object, "attributedTo", attributed_to)
932 def prepare_attachments(%{"type" => "ChatMessage"} = object), do: object
934 def prepare_attachments(object) do
937 |> Map.get("attachment", [])
938 |> Enum.map(fn data ->
939 [%{"mediaType" => media_type, "href" => href} | _] = data["url"]
943 "mediaType" => media_type,
944 "name" => data["name"],
949 Map.put(object, "attachment", attachments)
952 def strip_internal_fields(object) do
953 Map.drop(object, Pleroma.Constants.object_internal_fields())
956 defp strip_internal_tags(%{"tag" => tags} = object) do
957 tags = Enum.filter(tags, fn x -> is_map(x) end)
959 Map.put(object, "tag", tags)
962 defp strip_internal_tags(object), do: object
964 def perform(:user_upgrade, user) do
965 # we pass a fake user so that the followers collection is stripped away
966 old_follower_address = User.ap_followers(%User{nickname: user.nickname})
970 where: ^old_follower_address in a.recipients,
975 "array_replace(?,?,?)",
977 ^old_follower_address,
978 ^user.follower_address
983 |> Repo.update_all([])
986 def upgrade_user_from_ap_id(ap_id) do
987 with %User{local: false} = user <- User.get_cached_by_ap_id(ap_id),
988 {:ok, data} <- ActivityPub.fetch_and_prepare_user_from_ap_id(ap_id),
989 {:ok, user} <- update_user(user, data) do
990 TransmogrifierWorker.enqueue("user_upgrade", %{"user_id" => user.id})
993 %User{} = user -> {:ok, user}
998 defp update_user(user, data) do
1000 |> User.remote_user_changeset(data)
1001 |> User.update_and_set_cache()
1004 def maybe_fix_user_url(%{"url" => url} = data) when is_map(url) do
1005 Map.put(data, "url", url["href"])
1008 def maybe_fix_user_url(data), do: data
1010 def maybe_fix_user_object(data), do: maybe_fix_user_url(data)