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)
49 def fix_summary(%{"summary" => nil} = object) do
50 Map.put(object, "summary", "")
53 def fix_summary(%{"summary" => _} = object) do
54 # summary is present, nothing to do
58 def fix_summary(object), do: Map.put(object, "summary", "")
60 def fix_addressing_list(map, field) do
65 Map.put(map, field, Enum.filter(addrs, &is_binary/1))
68 Map.put(map, field, [addrs])
71 Map.put(map, field, [])
75 def fix_explicit_addressing(
76 %{"to" => to, "cc" => cc} = object,
80 explicit_to = Enum.filter(to, fn x -> x in explicit_mentions end)
82 explicit_cc = Enum.filter(to, fn x -> x not in explicit_mentions end)
86 |> Enum.reject(fn x -> String.ends_with?(x, "/followers") and x != follower_collection end)
90 |> Map.put("to", explicit_to)
91 |> Map.put("cc", final_cc)
94 def fix_explicit_addressing(object, _explicit_mentions, _followers_collection), do: object
96 # if directMessage flag is set to true, leave the addressing alone
97 def fix_explicit_addressing(%{"directMessage" => true} = object), do: object
99 def fix_explicit_addressing(object) do
100 explicit_mentions = Utils.determine_explicit_mentions(object)
102 %User{follower_address: follower_collection} =
104 |> Containment.get_actor()
105 |> User.get_cached_by_ap_id()
110 Pleroma.Constants.as_public(),
114 fix_explicit_addressing(object, explicit_mentions, follower_collection)
117 # if as:Public is addressed, then make sure the followers collection is also addressed
118 # so that the activities will be delivered to local users.
119 def fix_implicit_addressing(%{"to" => to, "cc" => cc} = object, followers_collection) do
120 recipients = to ++ cc
122 if followers_collection not in recipients do
124 Pleroma.Constants.as_public() in cc ->
125 to = to ++ [followers_collection]
126 Map.put(object, "to", to)
128 Pleroma.Constants.as_public() in to ->
129 cc = cc ++ [followers_collection]
130 Map.put(object, "cc", cc)
140 def fix_implicit_addressing(object, _), do: object
142 def fix_addressing(object) do
143 {:ok, %User{} = user} = User.get_or_fetch_by_ap_id(object["actor"])
144 followers_collection = User.ap_followers(user)
147 |> fix_addressing_list("to")
148 |> fix_addressing_list("cc")
149 |> fix_addressing_list("bto")
150 |> fix_addressing_list("bcc")
151 |> fix_explicit_addressing()
152 |> fix_implicit_addressing(followers_collection)
155 def fix_actor(%{"attributedTo" => actor} = object) do
156 actor = Containment.get_actor(%{"actor" => actor})
158 # TODO: Remove actor field for Objects
160 |> Map.put("actor", actor)
161 |> Map.put("attributedTo", actor)
164 def fix_in_reply_to(object, options \\ [])
166 def fix_in_reply_to(%{"inReplyTo" => in_reply_to} = object, options)
167 when not is_nil(in_reply_to) do
168 in_reply_to_id = prepare_in_reply_to(in_reply_to)
169 depth = (options[:depth] || 0) + 1
171 if Federator.allowed_thread_distance?(depth) do
172 with {:ok, replied_object} <- get_obj_helper(in_reply_to_id, options),
173 %Activity{} <- Activity.get_create_by_object_ap_id(replied_object.data["id"]) do
175 |> Map.put("inReplyTo", replied_object.data["id"])
176 |> Map.put("context", replied_object.data["context"] || object["conversation"])
177 |> Map.drop(["conversation", "inReplyToAtomUri"])
180 Logger.warn("Couldn't fetch #{inspect(in_reply_to_id)}, error: #{inspect(e)}")
188 def fix_in_reply_to(object, _options), do: object
190 defp prepare_in_reply_to(in_reply_to) do
192 is_bitstring(in_reply_to) ->
195 is_map(in_reply_to) && is_bitstring(in_reply_to["id"]) ->
198 is_list(in_reply_to) && is_bitstring(Enum.at(in_reply_to, 0)) ->
199 Enum.at(in_reply_to, 0)
206 def fix_context(object) do
207 context = object["context"] || object["conversation"] || Utils.generate_context_id()
210 |> Map.put("context", context)
211 |> Map.drop(["conversation"])
214 def fix_attachments(%{"attachment" => attachment} = object) when is_list(attachment) do
216 Enum.map(attachment, fn data ->
219 is_list(data["url"]) -> List.first(data["url"])
220 is_map(data["url"]) -> data["url"]
226 is_map(url) && MIME.valid?(url["mediaType"]) -> url["mediaType"]
227 MIME.valid?(data["mediaType"]) -> data["mediaType"]
228 MIME.valid?(data["mimeType"]) -> data["mimeType"]
234 is_map(url) && is_binary(url["href"]) -> url["href"]
235 is_binary(data["url"]) -> data["url"]
236 is_binary(data["href"]) -> data["href"]
244 "type" => Map.get(url || %{}, "type", "Link")
246 |> Maps.put_if_present("mediaType", media_type)
249 "url" => [attachment_url],
250 "type" => data["type"] || "Document"
252 |> Maps.put_if_present("mediaType", media_type)
253 |> Maps.put_if_present("name", data["name"])
254 |> Maps.put_if_present("blurhash", data["blurhash"])
261 Map.put(object, "attachment", attachments)
264 def fix_attachments(%{"attachment" => attachment} = object) when is_map(attachment) do
266 |> Map.put("attachment", [attachment])
270 def fix_attachments(object), do: object
272 def fix_url(%{"url" => url} = object) when is_map(url) do
273 Map.put(object, "url", url["href"])
276 def fix_url(%{"url" => url} = object) when is_list(url) do
277 first_element = Enum.at(url, 0)
281 is_bitstring(first_element) -> first_element
282 is_map(first_element) -> first_element["href"] || ""
286 Map.put(object, "url", url_string)
289 def fix_url(object), do: object
291 def fix_emoji(%{"tag" => tags} = object) when is_list(tags) do
294 |> Enum.filter(fn data -> is_map(data) and data["type"] == "Emoji" and data["icon"] end)
295 |> Enum.reduce(%{}, fn data, mapping ->
296 name = String.trim(data["name"], ":")
298 Map.put(mapping, name, data["icon"]["url"])
301 Map.put(object, "emoji", emoji)
304 def fix_emoji(%{"tag" => %{"type" => "Emoji"} = tag} = object) do
305 name = String.trim(tag["name"], ":")
306 emoji = %{name => tag["icon"]["url"]}
308 Map.put(object, "emoji", emoji)
311 def fix_emoji(object), do: object
313 def fix_tag(%{"tag" => tag} = object) when is_list(tag) do
316 |> Enum.filter(fn data -> data["type"] == "Hashtag" and data["name"] end)
318 %{"name" => "#" <> hashtag} -> String.downcase(hashtag)
319 %{"name" => hashtag} -> String.downcase(hashtag)
322 Map.put(object, "tag", tag ++ tags)
325 def fix_tag(%{"tag" => %{} = tag} = object) do
327 |> Map.put("tag", [tag])
331 def fix_tag(object), do: object
333 # content map usually only has one language so this will do for now.
334 def fix_content_map(%{"contentMap" => content_map} = object) do
335 content_groups = Map.to_list(content_map)
336 {_, content} = Enum.at(content_groups, 0)
338 Map.put(object, "content", content)
341 def fix_content_map(object), do: object
343 def fix_type(object, options \\ [])
345 def fix_type(%{"inReplyTo" => reply_id, "name" => _} = object, options)
346 when is_binary(reply_id) do
347 with true <- Federator.allowed_thread_distance?(options[:depth]),
348 {:ok, %{data: %{"type" => "Question"} = _} = _} <- get_obj_helper(reply_id, options) do
349 Map.put(object, "type", "Answer")
355 def fix_type(object, _), do: object
357 # Reduce the object list to find the reported user.
358 defp get_reported(objects) do
359 Enum.reduce_while(objects, nil, fn ap_id, _ ->
360 with %User{} = user <- User.get_cached_by_ap_id(ap_id) do
368 # Compatibility wrapper for Mastodon votes
369 defp handle_create(%{"object" => %{"type" => "Answer"}} = data, _user) do
370 handle_incoming(data)
373 defp handle_create(%{"object" => object} = data, user) do
378 context: object["context"],
380 published: data["published"],
388 |> ActivityPub.create()
391 def handle_incoming(data, options \\ [])
393 # Flag objects are placed ahead of the ID check because Mastodon 2.8 and earlier send them
395 def handle_incoming(%{"type" => "Flag", "object" => objects, "actor" => actor} = data, _options) do
396 with context <- data["context"] || Utils.generate_context_id(),
397 content <- data["content"] || "",
398 %User{} = actor <- User.get_cached_by_ap_id(actor),
399 # Reduce the object list to find the reported user.
400 %User{} = account <- get_reported(objects),
401 # Remove the reported user from the object list.
402 statuses <- Enum.filter(objects, fn ap_id -> ap_id != account.ap_id end) do
409 additional: %{"cc" => [account.ap_id]}
411 |> ActivityPub.flag()
415 # disallow objects with bogus IDs
416 def handle_incoming(%{"id" => nil}, _options), do: :error
417 def handle_incoming(%{"id" => ""}, _options), do: :error
418 # length of https:// = 8, should validate better, but good enough for now.
419 def handle_incoming(%{"id" => id}, _options) when is_binary(id) and byte_size(id) < 8,
422 # TODO: validate those with a Ecto scheme
426 %{"type" => "Create", "object" => %{"type" => objtype} = object} = data,
429 when objtype in ~w{Note Page} do
430 actor = Containment.get_actor(data)
432 with nil <- Activity.get_create_by_object_ap_id(object["id"]),
433 {:ok, %User{} = user} <- User.get_or_fetch_by_ap_id(actor) do
436 |> Map.put("object", fix_object(object, options))
437 |> Map.put("actor", actor)
440 with {:ok, created_activity} <- handle_create(data, user) do
441 reply_depth = (options[:depth] || 0) + 1
443 if Federator.allowed_thread_distance?(reply_depth) do
444 for reply_id <- replies(object) do
445 Pleroma.Workers.RemoteFetcherWorker.enqueue("fetch_remote", %{
447 "depth" => reply_depth
452 {:ok, created_activity}
455 %Activity{} = activity -> {:ok, activity}
461 %{"type" => "Listen", "object" => %{"type" => "Audio"} = object} = data,
464 actor = Containment.get_actor(data)
467 Map.put(data, "actor", actor)
470 with {:ok, %User{} = user} <- User.get_or_fetch_by_ap_id(data["actor"]) do
471 reply_depth = (options[:depth] || 0) + 1
472 options = Keyword.put(options, :depth, reply_depth)
473 object = fix_object(object, options)
481 published: data["published"],
482 additional: Map.take(data, ["cc", "id"])
485 ActivityPub.listen(params)
491 @misskey_reactions %{
505 @doc "Rewrite misskey likes into EmojiReacts"
509 "_misskey_reaction" => reaction
514 |> Map.put("type", "EmojiReact")
515 |> Map.put("content", @misskey_reactions[reaction] || reaction)
516 |> handle_incoming(options)
520 %{"type" => "Create", "object" => %{"type" => objtype, "id" => obj_id}} = data,
523 when objtype in ~w{Question Answer ChatMessage Audio Video Event Article} do
524 data = Map.put(data, "object", strip_internal_fields(data["object"]))
526 with {:ok, %User{}} <- ObjectValidator.fetch_actor(data),
527 nil <- Activity.get_create_by_object_ap_id(obj_id),
528 {:ok, activity, _} <- Pipeline.common_pipeline(data, local: false) do
531 %Activity{} = activity -> {:ok, activity}
536 def handle_incoming(%{"type" => type} = data, _options)
537 when type in ~w{Like EmojiReact Announce} do
538 with :ok <- ObjectValidator.fetch_actor_and_object(data),
539 {:ok, activity, _meta} <-
540 Pipeline.common_pipeline(data, local: false) do
548 %{"type" => type} = data,
551 when type in ~w{Update Block Follow Accept Reject} do
552 with {:ok, %User{}} <- ObjectValidator.fetch_actor(data),
553 {:ok, activity, _} <-
554 Pipeline.common_pipeline(data, local: false) do
559 def handle_incoming(%{"type" => type} = data, _options) when type in ~w(Add Remove) do
560 with {:ok, %User{} = user} <- ObjectValidator.fetch_actor(data),
561 %Object{} <- Object.normalize(data["object"], fetch: true) do
562 # Mastodon sends pin/unpin objects without id, to, cc fields
565 |> Map.put_new("id", Utils.generate_activity_id())
566 |> Map.put_new("to", [Pleroma.Constants.as_public()])
567 |> Map.put_new("cc", [user.follower_address])
569 case Pipeline.common_pipeline(data,
571 featured_address: user.featured_address
573 {:ok, activity, _meta} -> {:ok, activity}
580 %{"type" => "Delete"} = data,
583 with {:ok, activity, _} <-
584 Pipeline.common_pipeline(data, local: false) do
587 {:error, {:validate_object, _}} = e ->
588 # Check if we have a create activity for this
589 with {:ok, object_id} <- ObjectValidators.ObjectID.cast(data["object"]),
590 %Activity{data: %{"actor" => actor}} <-
591 Activity.create_by_object_ap_id(object_id) |> Repo.one(),
592 # We have one, insert a tombstone and retry
593 {:ok, tombstone_data, _} <- Builder.tombstone(actor, object_id),
594 {:ok, _tombstone} <- Object.create(tombstone_data) do
595 handle_incoming(data)
605 "object" => %{"type" => "Follow", "object" => followed},
611 with %User{local: true} = followed <- User.get_cached_by_ap_id(followed),
612 {:ok, %User{} = follower} <- User.get_or_fetch_by_ap_id(follower),
613 {:ok, activity} <- ActivityPub.unfollow(follower, followed, id, false) do
614 User.unfollow(follower, followed)
624 "object" => %{"type" => type}
628 when type in ["Like", "EmojiReact", "Announce", "Block"] do
629 with {:ok, activity, _} <- Pipeline.common_pipeline(data, local: false) do
634 # For Undos that don't have the complete object attached, try to find it in our database.
642 when is_binary(object) do
643 with %Activity{data: data} <- Activity.get_by_ap_id(object) do
645 |> Map.put("object", data)
646 |> handle_incoming(options)
655 "actor" => origin_actor,
656 "object" => origin_actor,
657 "target" => target_actor
661 with %User{} = origin_user <- User.get_cached_by_ap_id(origin_actor),
662 {:ok, %User{} = target_user} <- User.get_or_fetch_by_ap_id(target_actor),
663 true <- origin_actor in target_user.also_known_as do
664 ActivityPub.move(origin_user, target_user, false)
670 def handle_incoming(_, _), do: :error
672 @spec get_obj_helper(String.t(), Keyword.t()) :: {:ok, Object.t()} | nil
673 def get_obj_helper(id, options \\ []) do
674 options = Keyword.put(options, :fetch, true)
676 case Object.normalize(id, options) do
677 %Object{} = object -> {:ok, object}
682 @spec get_embedded_obj_helper(String.t() | Object.t(), User.t()) :: {:ok, Object.t()} | nil
683 def get_embedded_obj_helper(%{"attributedTo" => attributed_to, "id" => object_id} = data, %User{
686 when attributed_to == ap_id do
687 with {:ok, activity} <-
692 "actor" => attributed_to,
695 {:ok, Object.normalize(activity, fetch: false)}
697 _ -> get_obj_helper(object_id)
701 def get_embedded_obj_helper(object_id, _) do
702 get_obj_helper(object_id)
705 def set_reply_to_uri(%{"inReplyTo" => in_reply_to} = object) when is_binary(in_reply_to) do
706 with false <- String.starts_with?(in_reply_to, "http"),
707 {:ok, %{data: replied_to_object}} <- get_obj_helper(in_reply_to) do
708 Map.put(object, "inReplyTo", replied_to_object["external_url"] || in_reply_to)
714 def set_reply_to_uri(obj), do: obj
717 Serialized Mastodon-compatible `replies` collection containing _self-replies_.
718 Based on Mastodon's ActivityPub::NoteSerializer#replies.
720 def set_replies(obj_data) do
722 with limit when limit > 0 <-
723 Pleroma.Config.get([:activitypub, :note_replies_output_limit], 0),
724 %Object{} = object <- Object.get_cached_by_ap_id(obj_data["id"]) do
726 |> Object.self_replies()
727 |> select([o], fragment("?->>'id'", o.data))
734 set_replies(obj_data, replies_uris)
737 defp set_replies(obj, []) do
741 defp set_replies(obj, replies_uris) do
742 replies_collection = %{
743 "type" => "Collection",
744 "items" => replies_uris
747 Map.merge(obj, %{"replies" => replies_collection})
750 def replies(%{"replies" => %{"first" => %{"items" => items}}}) when not is_nil(items) do
754 def replies(%{"replies" => %{"items" => items}}) when not is_nil(items) do
758 def replies(_), do: []
760 # Prepares the object of an outgoing create activity.
761 def prepare_object(object) do
767 |> prepare_attachments
771 |> strip_internal_fields
772 |> strip_internal_tags
778 # internal -> Mastodon
781 def prepare_outgoing(%{"type" => activity_type, "object" => object_id} = data)
782 when activity_type in ["Create", "Listen"] do
785 |> Object.normalize(fetch: false)
791 |> Map.put("object", object)
792 |> Map.merge(Utils.make_json_ld_header())
798 def prepare_outgoing(%{"type" => "Announce", "actor" => ap_id, "object" => object_id} = data) do
801 |> Object.normalize(fetch: false)
804 if Visibility.is_private?(object) && object.data["actor"] == ap_id do
805 data |> Map.put("object", object |> Map.get(:data) |> prepare_object)
807 data |> maybe_fix_object_url
812 |> strip_internal_fields
813 |> Map.merge(Utils.make_json_ld_header())
819 # Mastodon Accept/Reject requires a non-normalized object containing the actor URIs,
820 # because of course it does.
821 def prepare_outgoing(%{"type" => "Accept"} = data) do
822 with follow_activity <- Activity.normalize(data["object"]) do
824 "actor" => follow_activity.actor,
825 "object" => follow_activity.data["object"],
826 "id" => follow_activity.data["id"],
832 |> Map.put("object", object)
833 |> Map.merge(Utils.make_json_ld_header())
839 def prepare_outgoing(%{"type" => "Reject"} = data) do
840 with follow_activity <- Activity.normalize(data["object"]) do
842 "actor" => follow_activity.actor,
843 "object" => follow_activity.data["object"],
844 "id" => follow_activity.data["id"],
850 |> Map.put("object", object)
851 |> Map.merge(Utils.make_json_ld_header())
857 def prepare_outgoing(%{"type" => _type} = data) do
860 |> strip_internal_fields
861 |> maybe_fix_object_url
862 |> Map.merge(Utils.make_json_ld_header())
867 def maybe_fix_object_url(%{"object" => object} = data) when is_binary(object) do
868 with false <- String.starts_with?(object, "http"),
869 {:fetch, {:ok, relative_object}} <- {:fetch, get_obj_helper(object)},
870 %{data: %{"external_url" => external_url}} when not is_nil(external_url) <-
872 Map.put(data, "object", external_url)
875 Logger.error("Couldn't fetch #{object} #{inspect(e)}")
883 def maybe_fix_object_url(data), do: data
885 def add_hashtags(object) do
887 (object["tag"] || [])
889 # Expand internal representation tags into AS2 tags.
890 tag when is_binary(tag) ->
892 "href" => Pleroma.Web.Endpoint.url() <> "/tags/#{tag}",
897 # Do not process tags which are already AS2 tag objects.
898 tag when is_map(tag) ->
902 Map.put(object, "tag", tags)
905 # TODO These should be added on our side on insertion, it doesn't make much
906 # sense to regenerate these all the time
907 def add_mention_tags(object) do
908 to = object["to"] || []
909 cc = object["cc"] || []
910 mentioned = User.get_users_from_set(to ++ cc, local_only: false)
912 mentions = Enum.map(mentioned, &build_mention_tag/1)
914 tags = object["tag"] || []
915 Map.put(object, "tag", tags ++ mentions)
918 defp build_mention_tag(%{ap_id: ap_id, nickname: nickname} = _) do
919 %{"type" => "Mention", "href" => ap_id, "name" => "@#{nickname}"}
922 def take_emoji_tags(%User{emoji: emoji}) do
925 |> Enum.map(&build_emoji_tag/1)
928 # TODO: we should probably send mtime instead of unix epoch time for updated
929 def add_emoji_tags(%{"emoji" => emoji} = object) do
930 tags = object["tag"] || []
932 out = Enum.map(emoji, &build_emoji_tag/1)
934 Map.put(object, "tag", tags ++ out)
937 def add_emoji_tags(object), do: object
939 defp build_emoji_tag({name, url}) do
941 "icon" => %{"url" => "#{URI.encode(url)}", "type" => "Image"},
942 "name" => ":" <> name <> ":",
944 "updated" => "1970-01-01T00:00:00Z",
949 def set_conversation(object) do
950 Map.put(object, "conversation", object["context"])
953 def set_type(%{"type" => "Answer"} = object) do
954 Map.put(object, "type", "Note")
957 def set_type(object), do: object
959 def add_attributed_to(object) do
960 attributed_to = object["attributedTo"] || object["actor"]
961 Map.put(object, "attributedTo", attributed_to)
965 def prepare_attachments(%{"type" => "ChatMessage"} = object), do: object
967 def prepare_attachments(object) do
970 |> Map.get("attachment", [])
971 |> Enum.map(fn data ->
972 [%{"mediaType" => media_type, "href" => href} | _] = data["url"]
976 "mediaType" => media_type,
977 "name" => data["name"],
982 Map.put(object, "attachment", attachments)
985 def strip_internal_fields(object) do
986 Map.drop(object, Pleroma.Constants.object_internal_fields())
989 defp strip_internal_tags(%{"tag" => tags} = object) do
990 tags = Enum.filter(tags, fn x -> is_map(x) end)
992 Map.put(object, "tag", tags)
995 defp strip_internal_tags(object), do: object
997 def perform(:user_upgrade, user) do
998 # we pass a fake user so that the followers collection is stripped away
999 old_follower_address = User.ap_followers(%User{nickname: user.nickname})
1003 where: ^old_follower_address in a.recipients,
1008 "array_replace(?,?,?)",
1010 ^old_follower_address,
1011 ^user.follower_address
1016 |> Repo.update_all([])
1019 def upgrade_user_from_ap_id(ap_id) do
1020 with %User{local: false} = user <- User.get_cached_by_ap_id(ap_id),
1021 {:ok, data} <- ActivityPub.fetch_and_prepare_user_from_ap_id(ap_id),
1022 {:ok, user} <- update_user(user, data) do
1023 {:ok, _pid} = Task.start(fn -> ActivityPub.pinned_fetch_task(user) end)
1024 TransmogrifierWorker.enqueue("user_upgrade", %{"user_id" => user.id})
1027 %User{} = user -> {:ok, user}
1032 defp update_user(user, data) do
1034 |> User.remote_user_changeset(data)
1035 |> User.update_and_set_cache()
1038 def maybe_fix_user_url(%{"url" => url} = data) when is_map(url) do
1039 Map.put(data, "url", url["href"])
1042 def maybe_fix_user_url(data), do: data
1044 def maybe_fix_user_object(data), do: maybe_fix_user_url(data)