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)
50 def fix_summary(%{"summary" => nil} = object) do
51 Map.put(object, "summary", "")
54 def fix_summary(%{"summary" => _} = object) do
55 # summary is present, nothing to do
59 def fix_summary(object), do: Map.put(object, "summary", "")
61 def fix_addressing_list(map, field) do
66 Map.put(map, field, Enum.filter(addrs, &is_binary/1))
69 Map.put(map, field, [addrs])
72 Map.put(map, field, [])
76 def fix_explicit_addressing(
77 %{"to" => to, "cc" => cc} = object,
81 explicit_to = Enum.filter(to, fn x -> x in explicit_mentions end)
83 explicit_cc = Enum.filter(to, fn x -> x not in explicit_mentions end)
87 |> Enum.reject(fn x -> String.ends_with?(x, "/followers") and x != follower_collection end)
91 |> Map.put("to", explicit_to)
92 |> Map.put("cc", final_cc)
95 def fix_explicit_addressing(object, _explicit_mentions, _followers_collection), do: object
97 # if directMessage flag is set to true, leave the addressing alone
98 def fix_explicit_addressing(%{"directMessage" => true} = object), do: object
100 def fix_explicit_addressing(object) do
101 explicit_mentions = Utils.determine_explicit_mentions(object)
103 %User{follower_address: follower_collection} =
105 |> Containment.get_actor()
106 |> User.get_cached_by_ap_id()
111 Pleroma.Constants.as_public(),
115 fix_explicit_addressing(object, explicit_mentions, follower_collection)
118 # if as:Public is addressed, then make sure the followers collection is also addressed
119 # so that the activities will be delivered to local users.
120 def fix_implicit_addressing(%{"to" => to, "cc" => cc} = object, followers_collection) do
121 recipients = to ++ cc
123 if followers_collection not in recipients do
125 Pleroma.Constants.as_public() in cc ->
126 to = to ++ [followers_collection]
127 Map.put(object, "to", to)
129 Pleroma.Constants.as_public() in to ->
130 cc = cc ++ [followers_collection]
131 Map.put(object, "cc", cc)
141 def fix_implicit_addressing(object, _), do: object
143 def fix_addressing(object) do
144 {:ok, %User{} = user} = User.get_or_fetch_by_ap_id(object["actor"])
145 followers_collection = User.ap_followers(user)
148 |> fix_addressing_list("to")
149 |> fix_addressing_list("cc")
150 |> fix_addressing_list("bto")
151 |> fix_addressing_list("bcc")
152 |> fix_explicit_addressing()
153 |> fix_implicit_addressing(followers_collection)
156 def fix_actor(%{"attributedTo" => actor} = object) do
157 actor = Containment.get_actor(%{"actor" => actor})
159 # TODO: Remove actor field for Objects
161 |> Map.put("actor", actor)
162 |> Map.put("attributedTo", actor)
165 def fix_in_reply_to(object, options \\ [])
167 def fix_in_reply_to(%{"inReplyTo" => in_reply_to} = object, options)
168 when not is_nil(in_reply_to) do
169 in_reply_to_id = prepare_in_reply_to(in_reply_to)
170 depth = (options[:depth] || 0) + 1
172 if Federator.allowed_thread_distance?(depth) do
173 with {:ok, replied_object} <- get_obj_helper(in_reply_to_id, options),
174 %Activity{} <- Activity.get_create_by_object_ap_id(replied_object.data["id"]) do
176 |> Map.put("inReplyTo", replied_object.data["id"])
177 |> Map.put("context", replied_object.data["context"] || object["conversation"])
178 |> Map.drop(["conversation", "inReplyToAtomUri"])
181 Logger.warn("Couldn't fetch #{inspect(in_reply_to_id)}, error: #{inspect(e)}")
189 def fix_in_reply_to(object, _options), do: object
191 defp prepare_in_reply_to(in_reply_to) do
193 is_bitstring(in_reply_to) ->
196 is_map(in_reply_to) && is_bitstring(in_reply_to["id"]) ->
199 is_list(in_reply_to) && is_bitstring(Enum.at(in_reply_to, 0)) ->
200 Enum.at(in_reply_to, 0)
207 def fix_context(object) do
208 context = object["context"] || object["conversation"] || Utils.generate_context_id()
211 |> Map.put("context", context)
212 |> Map.drop(["conversation"])
215 def fix_attachments(%{"attachment" => attachment} = object) when is_list(attachment) do
217 Enum.map(attachment, fn data ->
220 is_list(data["url"]) -> List.first(data["url"])
221 is_map(data["url"]) -> data["url"]
227 is_map(url) && MIME.valid?(url["mediaType"]) -> url["mediaType"]
228 MIME.valid?(data["mediaType"]) -> data["mediaType"]
229 MIME.valid?(data["mimeType"]) -> data["mimeType"]
235 is_map(url) && is_binary(url["href"]) -> url["href"]
236 is_binary(data["url"]) -> data["url"]
237 is_binary(data["href"]) -> data["href"]
245 "type" => Map.get(url || %{}, "type", "Link")
247 |> Maps.put_if_present("mediaType", media_type)
248 |> Maps.put_if_present("width", (url || %{})["width"])
249 |> Maps.put_if_present("height", (url || %{})["height"])
252 "url" => [attachment_url],
253 "type" => data["type"] || "Document"
255 |> Maps.put_if_present("mediaType", media_type)
256 |> Maps.put_if_present("name", data["name"])
257 |> Maps.put_if_present("blurhash", data["blurhash"])
264 Map.put(object, "attachment", attachments)
267 def fix_attachments(%{"attachment" => attachment} = object) when is_map(attachment) do
269 |> Map.put("attachment", [attachment])
273 def fix_attachments(object), do: object
275 def fix_url(%{"url" => url} = object) when is_map(url) do
276 Map.put(object, "url", url["href"])
279 def fix_url(%{"url" => url} = object) when is_list(url) do
280 first_element = Enum.at(url, 0)
284 is_bitstring(first_element) -> first_element
285 is_map(first_element) -> first_element["href"] || ""
289 Map.put(object, "url", url_string)
292 def fix_url(object), do: object
294 def fix_emoji(%{"tag" => tags} = object) when is_list(tags) do
297 |> Enum.filter(fn data -> is_map(data) and data["type"] == "Emoji" and data["icon"] end)
298 |> Enum.reduce(%{}, fn data, mapping ->
299 name = String.trim(data["name"], ":")
301 Map.put(mapping, name, data["icon"]["url"])
304 Map.put(object, "emoji", emoji)
307 def fix_emoji(%{"tag" => %{"type" => "Emoji"} = tag} = object) do
308 name = String.trim(tag["name"], ":")
309 emoji = %{name => tag["icon"]["url"]}
311 Map.put(object, "emoji", emoji)
314 def fix_emoji(object), do: object
316 def fix_tag(%{"tag" => tag} = object) when is_list(tag) do
319 |> Enum.filter(fn data -> data["type"] == "Hashtag" and data["name"] end)
320 |> Enum.map(fn %{"name" => name} ->
322 |> String.slice(1..-1)
326 Map.put(object, "tag", tag ++ tags)
329 def fix_tag(%{"tag" => %{} = tag} = object) do
331 |> Map.put("tag", [tag])
335 def fix_tag(object), do: object
337 # content map usually only has one language so this will do for now.
338 def fix_content_map(%{"contentMap" => content_map} = object) do
339 content_groups = Map.to_list(content_map)
340 {_, content} = Enum.at(content_groups, 0)
342 Map.put(object, "content", content)
345 def fix_content_map(object), do: object
347 def fix_type(object, options \\ [])
349 def fix_type(%{"inReplyTo" => reply_id, "name" => _} = object, options)
350 when is_binary(reply_id) do
351 with true <- Federator.allowed_thread_distance?(options[:depth]),
352 {:ok, %{data: %{"type" => "Question"} = _} = _} <- get_obj_helper(reply_id, options) do
353 Map.put(object, "type", "Answer")
359 def fix_type(object, _), do: object
361 # Reduce the object list to find the reported user.
362 defp get_reported(objects) do
363 Enum.reduce_while(objects, nil, fn ap_id, _ ->
364 with %User{} = user <- User.get_cached_by_ap_id(ap_id) do
372 # Compatibility wrapper for Mastodon votes
373 defp handle_create(%{"object" => %{"type" => "Answer"}} = data, _user) do
374 handle_incoming(data)
377 defp handle_create(%{"object" => object} = data, user) do
382 context: object["context"],
384 published: data["published"],
392 |> ActivityPub.create()
395 def handle_incoming(data, options \\ [])
397 # Flag objects are placed ahead of the ID check because Mastodon 2.8 and earlier send them
399 def handle_incoming(%{"type" => "Flag", "object" => objects, "actor" => actor} = data, _options) do
400 with context <- data["context"] || Utils.generate_context_id(),
401 content <- data["content"] || "",
402 %User{} = actor <- User.get_cached_by_ap_id(actor),
403 # Reduce the object list to find the reported user.
404 %User{} = account <- get_reported(objects),
405 # Remove the reported user from the object list.
406 statuses <- Enum.filter(objects, fn ap_id -> ap_id != account.ap_id end) do
413 additional: %{"cc" => [account.ap_id]}
415 |> ActivityPub.flag()
419 # disallow objects with bogus IDs
420 def handle_incoming(%{"id" => nil}, _options), do: :error
421 def handle_incoming(%{"id" => ""}, _options), do: :error
422 # length of https:// = 8, should validate better, but good enough for now.
423 def handle_incoming(%{"id" => id}, _options) when is_binary(id) and byte_size(id) < 8,
426 # TODO: validate those with a Ecto scheme
430 %{"type" => "Create", "object" => %{"type" => objtype} = object} = data,
433 when objtype in ~w{Note Page} do
434 actor = Containment.get_actor(data)
436 with nil <- Activity.get_create_by_object_ap_id(object["id"]),
437 {:ok, %User{} = user} <- User.get_or_fetch_by_ap_id(actor) do
440 |> Map.put("object", fix_object(object, options))
441 |> Map.put("actor", actor)
444 with {:ok, created_activity} <- handle_create(data, user) do
445 reply_depth = (options[:depth] || 0) + 1
447 if Federator.allowed_thread_distance?(reply_depth) do
448 for reply_id <- replies(object) do
449 Pleroma.Workers.RemoteFetcherWorker.enqueue("fetch_remote", %{
451 "depth" => reply_depth
456 {:ok, created_activity}
459 %Activity{} = activity -> {:ok, activity}
465 %{"type" => "Listen", "object" => %{"type" => "Audio"} = object} = data,
468 actor = Containment.get_actor(data)
471 Map.put(data, "actor", actor)
474 with {:ok, %User{} = user} <- User.get_or_fetch_by_ap_id(data["actor"]) do
475 reply_depth = (options[:depth] || 0) + 1
476 options = Keyword.put(options, :depth, reply_depth)
477 object = fix_object(object, options)
485 published: data["published"],
486 additional: Map.take(data, ["cc", "id"])
489 ActivityPub.listen(params)
495 @misskey_reactions %{
509 @doc "Rewrite misskey likes into EmojiReacts"
513 "_misskey_reaction" => reaction
518 |> Map.put("type", "EmojiReact")
519 |> Map.put("content", @misskey_reactions[reaction] || reaction)
520 |> handle_incoming(options)
524 %{"type" => "Create", "object" => %{"type" => objtype, "id" => obj_id}} = data,
527 when objtype in ~w{Question Answer ChatMessage Audio Video Event Article} do
528 data = Map.put(data, "object", strip_internal_fields(data["object"]))
530 with {:ok, %User{}} <- ObjectValidator.fetch_actor(data),
531 nil <- Activity.get_create_by_object_ap_id(obj_id),
532 {:ok, activity, _} <- Pipeline.common_pipeline(data, local: false) do
535 %Activity{} = activity -> {:ok, activity}
540 def handle_incoming(%{"type" => type} = data, _options)
541 when type in ~w{Like EmojiReact Announce} do
542 with :ok <- ObjectValidator.fetch_actor_and_object(data),
543 {:ok, activity, _meta} <-
544 Pipeline.common_pipeline(data, local: false) do
552 %{"type" => type} = data,
555 when type in ~w{Update Block Follow Accept Reject} do
556 with {:ok, %User{}} <- ObjectValidator.fetch_actor(data),
557 {:ok, activity, _} <-
558 Pipeline.common_pipeline(data, local: false) do
564 %{"type" => "Delete"} = data,
567 with {:ok, activity, _} <-
568 Pipeline.common_pipeline(data, local: false) do
571 {:error, {:validate_object, _}} = e ->
572 # Check if we have a create activity for this
573 with {:ok, object_id} <- ObjectValidators.ObjectID.cast(data["object"]),
574 %Activity{data: %{"actor" => actor}} <-
575 Activity.create_by_object_ap_id(object_id) |> Repo.one(),
576 # We have one, insert a tombstone and retry
577 {:ok, tombstone_data, _} <- Builder.tombstone(actor, object_id),
578 {:ok, _tombstone} <- Object.create(tombstone_data) do
579 handle_incoming(data)
589 "object" => %{"type" => "Follow", "object" => followed},
595 with %User{local: true} = followed <- User.get_cached_by_ap_id(followed),
596 {:ok, %User{} = follower} <- User.get_or_fetch_by_ap_id(follower),
597 {:ok, activity} <- ActivityPub.unfollow(follower, followed, id, false) do
598 User.unfollow(follower, followed)
608 "object" => %{"type" => type}
612 when type in ["Like", "EmojiReact", "Announce", "Block"] do
613 with {:ok, activity, _} <- Pipeline.common_pipeline(data, local: false) do
618 # For Undos that don't have the complete object attached, try to find it in our database.
626 when is_binary(object) do
627 with %Activity{data: data} <- Activity.get_by_ap_id(object) do
629 |> Map.put("object", data)
630 |> handle_incoming(options)
639 "actor" => origin_actor,
640 "object" => origin_actor,
641 "target" => target_actor
645 with %User{} = origin_user <- User.get_cached_by_ap_id(origin_actor),
646 {:ok, %User{} = target_user} <- User.get_or_fetch_by_ap_id(target_actor),
647 true <- origin_actor in target_user.also_known_as do
648 ActivityPub.move(origin_user, target_user, false)
654 def handle_incoming(_, _), do: :error
656 @spec get_obj_helper(String.t(), Keyword.t()) :: {:ok, Object.t()} | nil
657 def get_obj_helper(id, options \\ []) do
658 options = Keyword.put(options, :fetch, true)
660 case Object.normalize(id, options) do
661 %Object{} = object -> {:ok, object}
666 @spec get_embedded_obj_helper(String.t() | Object.t(), User.t()) :: {:ok, Object.t()} | nil
667 def get_embedded_obj_helper(%{"attributedTo" => attributed_to, "id" => object_id} = data, %User{
670 when attributed_to == ap_id do
671 with {:ok, activity} <-
676 "actor" => attributed_to,
679 {:ok, Object.normalize(activity, fetch: false)}
681 _ -> get_obj_helper(object_id)
685 def get_embedded_obj_helper(object_id, _) do
686 get_obj_helper(object_id)
689 def set_reply_to_uri(%{"inReplyTo" => in_reply_to} = object) when is_binary(in_reply_to) do
690 with false <- String.starts_with?(in_reply_to, "http"),
691 {:ok, %{data: replied_to_object}} <- get_obj_helper(in_reply_to) do
692 Map.put(object, "inReplyTo", replied_to_object["external_url"] || in_reply_to)
698 def set_reply_to_uri(obj), do: obj
701 Serialized Mastodon-compatible `replies` collection containing _self-replies_.
702 Based on Mastodon's ActivityPub::NoteSerializer#replies.
704 def set_replies(obj_data) do
706 with limit when limit > 0 <-
707 Pleroma.Config.get([:activitypub, :note_replies_output_limit], 0),
708 %Object{} = object <- Object.get_cached_by_ap_id(obj_data["id"]) do
710 |> Object.self_replies()
711 |> select([o], fragment("?->>'id'", o.data))
718 set_replies(obj_data, replies_uris)
721 defp set_replies(obj, []) do
725 defp set_replies(obj, replies_uris) do
726 replies_collection = %{
727 "type" => "Collection",
728 "items" => replies_uris
731 Map.merge(obj, %{"replies" => replies_collection})
734 def replies(%{"replies" => %{"first" => %{"items" => items}}}) when not is_nil(items) do
738 def replies(%{"replies" => %{"items" => items}}) when not is_nil(items) do
742 def replies(_), do: []
744 # Prepares the object of an outgoing create activity.
745 def prepare_object(object) do
752 |> prepare_attachments
756 |> strip_internal_fields
757 |> strip_internal_tags
763 # internal -> Mastodon
766 def prepare_outgoing(%{"type" => activity_type, "object" => object_id} = data)
767 when activity_type in ["Create", "Listen"] do
770 |> Object.normalize(fetch: false)
776 |> Map.put("object", object)
777 |> Map.merge(Utils.make_json_ld_header())
783 def prepare_outgoing(%{"type" => "Announce", "actor" => ap_id, "object" => object_id} = data) do
786 |> Object.normalize(fetch: false)
789 if Visibility.is_private?(object) && object.data["actor"] == ap_id do
790 data |> Map.put("object", object |> Map.get(:data) |> prepare_object)
792 data |> maybe_fix_object_url
797 |> strip_internal_fields
798 |> Map.merge(Utils.make_json_ld_header())
804 # Mastodon Accept/Reject requires a non-normalized object containing the actor URIs,
805 # because of course it does.
806 def prepare_outgoing(%{"type" => "Accept"} = 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" => "Reject"} = data) do
825 with follow_activity <- Activity.normalize(data["object"]) do
827 "actor" => follow_activity.actor,
828 "object" => follow_activity.data["object"],
829 "id" => follow_activity.data["id"],
835 |> Map.put("object", object)
836 |> Map.merge(Utils.make_json_ld_header())
842 def prepare_outgoing(%{"type" => _type} = data) do
845 |> strip_internal_fields
846 |> maybe_fix_object_url
847 |> Map.merge(Utils.make_json_ld_header())
852 def maybe_fix_object_url(%{"object" => object} = data) when is_binary(object) do
853 with false <- String.starts_with?(object, "http"),
854 {:fetch, {:ok, relative_object}} <- {:fetch, get_obj_helper(object)},
855 %{data: %{"external_url" => external_url}} when not is_nil(external_url) <-
857 Map.put(data, "object", external_url)
860 Logger.error("Couldn't fetch #{object} #{inspect(e)}")
868 def maybe_fix_object_url(data), do: data
870 def add_hashtags(object) do
872 (object["tag"] || [])
874 # Expand internal representation tags into AS2 tags.
875 tag when is_binary(tag) ->
877 "href" => Pleroma.Web.Endpoint.url() <> "/tags/#{tag}",
882 # Do not process tags which are already AS2 tag objects.
883 tag when is_map(tag) ->
887 Map.put(object, "tag", tags)
890 # TODO These should be added on our side on insertion, it doesn't make much
891 # sense to regenerate these all the time
892 def add_mention_tags(object) do
893 to = object["to"] || []
894 cc = object["cc"] || []
895 mentioned = User.get_users_from_set(to ++ cc, local_only: false)
897 mentions = Enum.map(mentioned, &build_mention_tag/1)
899 tags = object["tag"] || []
900 Map.put(object, "tag", tags ++ mentions)
903 defp build_mention_tag(%{ap_id: ap_id, nickname: nickname} = _) do
904 %{"type" => "Mention", "href" => ap_id, "name" => "@#{nickname}"}
907 def take_emoji_tags(%User{emoji: emoji}) do
910 |> Enum.map(&build_emoji_tag/1)
913 # TODO: we should probably send mtime instead of unix epoch time for updated
914 def add_emoji_tags(%{"emoji" => emoji} = object) do
915 tags = object["tag"] || []
917 out = Enum.map(emoji, &build_emoji_tag/1)
919 Map.put(object, "tag", tags ++ out)
922 def add_emoji_tags(object), do: object
924 defp build_emoji_tag({name, url}) do
926 "icon" => %{"url" => "#{URI.encode(url)}", "type" => "Image"},
927 "name" => ":" <> name <> ":",
929 "updated" => "1970-01-01T00:00:00Z",
934 def set_conversation(object) do
935 Map.put(object, "conversation", object["context"])
938 def set_sensitive(%{"sensitive" => _} = object) do
942 def set_sensitive(object) do
943 tags = object["tag"] || []
944 Map.put(object, "sensitive", "nsfw" in tags)
947 def set_type(%{"type" => "Answer"} = object) do
948 Map.put(object, "type", "Note")
951 def set_type(object), do: object
953 def add_attributed_to(object) do
954 attributed_to = object["attributedTo"] || object["actor"]
955 Map.put(object, "attributedTo", attributed_to)
959 def prepare_attachments(%{"type" => "ChatMessage"} = object), do: object
961 def prepare_attachments(object) do
964 |> Map.get("attachment", [])
965 |> Enum.map(fn data ->
966 [%{"mediaType" => media_type, "href" => href} | _] = data["url"]
970 "mediaType" => media_type,
971 "name" => data["name"],
976 Map.put(object, "attachment", attachments)
979 def strip_internal_fields(object) do
980 Map.drop(object, Pleroma.Constants.object_internal_fields())
983 defp strip_internal_tags(%{"tag" => tags} = object) do
984 tags = Enum.filter(tags, fn x -> is_map(x) end)
986 Map.put(object, "tag", tags)
989 defp strip_internal_tags(object), do: object
991 def perform(:user_upgrade, user) do
992 # we pass a fake user so that the followers collection is stripped away
993 old_follower_address = User.ap_followers(%User{nickname: user.nickname})
997 where: ^old_follower_address in a.recipients,
1002 "array_replace(?,?,?)",
1004 ^old_follower_address,
1005 ^user.follower_address
1010 |> Repo.update_all([])
1013 def upgrade_user_from_ap_id(ap_id) do
1014 with %User{local: false} = user <- User.get_cached_by_ap_id(ap_id),
1015 {:ok, data} <- ActivityPub.fetch_and_prepare_user_from_ap_id(ap_id),
1016 {:ok, user} <- update_user(user, data) do
1017 TransmogrifierWorker.enqueue("user_upgrade", %{"user_id" => user.id})
1020 %User{} = user -> {:ok, user}
1025 defp update_user(user, data) do
1027 |> User.remote_user_changeset(data)
1028 |> User.update_and_set_cache()
1031 def maybe_fix_user_url(%{"url" => url} = data) when is_map(url) do
1032 Map.put(data, "url", url["href"])
1035 def maybe_fix_user_url(data), do: data
1037 def maybe_fix_user_object(data), do: maybe_fix_user_url(data)