1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2020 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.EarmarkRenderer
11 alias Pleroma.EctoType.ActivityPub.ObjectValidators
14 alias Pleroma.Object.Containment
17 alias Pleroma.Web.ActivityPub.ActivityPub
18 alias Pleroma.Web.ActivityPub.Builder
19 alias Pleroma.Web.ActivityPub.ObjectValidator
20 alias Pleroma.Web.ActivityPub.Pipeline
21 alias Pleroma.Web.ActivityPub.Utils
22 alias Pleroma.Web.ActivityPub.Visibility
23 alias Pleroma.Web.Federator
24 alias Pleroma.Workers.TransmogrifierWorker
29 require Pleroma.Constants
32 Modifies an incoming AP object (mastodon format) to our internal format.
34 def fix_object(object, options \\ []) do
36 |> strip_internal_fields
41 |> fix_in_reply_to(options)
51 def fix_summary(%{"summary" => nil} = object) do
52 Map.put(object, "summary", "")
55 def fix_summary(%{"summary" => _} = object) do
56 # summary is present, nothing to do
60 def fix_summary(object), do: Map.put(object, "summary", "")
62 def fix_addressing_list(map, field) do
67 Map.put(map, field, Enum.filter(addrs, &is_binary/1))
70 Map.put(map, field, [addrs])
73 Map.put(map, field, [])
77 def fix_explicit_addressing(
78 %{"to" => to, "cc" => cc} = object,
82 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)
88 |> Enum.reject(fn x -> String.ends_with?(x, "/followers") and x != follower_collection end)
92 |> Map.put("to", explicit_to)
93 |> Map.put("cc", final_cc)
96 def fix_explicit_addressing(object, _explicit_mentions, _followers_collection), do: object
98 # if directMessage flag is set to true, leave the addressing alone
99 def fix_explicit_addressing(%{"directMessage" => true} = object), do: object
101 def fix_explicit_addressing(object) do
102 explicit_mentions = Utils.determine_explicit_mentions(object)
104 %User{follower_address: follower_collection} =
106 |> Containment.get_actor()
107 |> User.get_cached_by_ap_id()
112 Pleroma.Constants.as_public(),
116 fix_explicit_addressing(object, explicit_mentions, follower_collection)
119 # if as:Public is addressed, then make sure the followers collection is also addressed
120 # so that the activities will be delivered to local users.
121 def fix_implicit_addressing(%{"to" => to, "cc" => cc} = object, followers_collection) do
122 recipients = to ++ cc
124 if followers_collection not in recipients do
126 Pleroma.Constants.as_public() in cc ->
127 to = to ++ [followers_collection]
128 Map.put(object, "to", to)
130 Pleroma.Constants.as_public() in to ->
131 cc = cc ++ [followers_collection]
132 Map.put(object, "cc", cc)
142 def fix_implicit_addressing(object, _), do: object
144 def fix_addressing(object) do
145 {:ok, %User{} = user} = User.get_or_fetch_by_ap_id(object["actor"])
146 followers_collection = User.ap_followers(user)
149 |> fix_addressing_list("to")
150 |> fix_addressing_list("cc")
151 |> fix_addressing_list("bto")
152 |> fix_addressing_list("bcc")
153 |> fix_explicit_addressing()
154 |> fix_implicit_addressing(followers_collection)
157 def fix_actor(%{"attributedTo" => actor} = object) do
158 actor = Containment.get_actor(%{"actor" => actor})
160 # TODO: Remove actor field for Objects
162 |> Map.put("actor", actor)
163 |> Map.put("attributedTo", actor)
166 def fix_in_reply_to(object, options \\ [])
168 def fix_in_reply_to(%{"inReplyTo" => in_reply_to} = object, options)
169 when not is_nil(in_reply_to) do
170 in_reply_to_id = prepare_in_reply_to(in_reply_to)
171 object = Map.put(object, "inReplyToAtomUri", in_reply_to_id)
172 depth = (options[:depth] || 0) + 1
174 if Federator.allowed_thread_distance?(depth) do
175 with {:ok, replied_object} <- get_obj_helper(in_reply_to_id, options),
176 %Activity{} <- Activity.get_create_by_object_ap_id(replied_object.data["id"]) do
178 |> Map.put("inReplyTo", replied_object.data["id"])
179 |> Map.put("inReplyToAtomUri", object["inReplyToAtomUri"] || in_reply_to_id)
180 |> Map.put("context", replied_object.data["context"] || object["conversation"])
181 |> Map.drop(["conversation"])
184 Logger.warn("Couldn't fetch #{inspect(in_reply_to_id)}, error: #{inspect(e)}")
192 def fix_in_reply_to(object, _options), do: object
194 defp prepare_in_reply_to(in_reply_to) do
196 is_bitstring(in_reply_to) ->
199 is_map(in_reply_to) && is_bitstring(in_reply_to["id"]) ->
202 is_list(in_reply_to) && is_bitstring(Enum.at(in_reply_to, 0)) ->
203 Enum.at(in_reply_to, 0)
210 def fix_context(object) do
211 context = object["context"] || object["conversation"] || Utils.generate_context_id()
214 |> Map.put("context", context)
215 |> Map.drop(["conversation"])
218 def fix_attachments(%{"attachment" => attachment} = object) when is_list(attachment) do
220 Enum.map(attachment, fn data ->
223 is_list(data["url"]) -> List.first(data["url"])
224 is_map(data["url"]) -> data["url"]
230 is_map(url) && MIME.valid?(url["mediaType"]) -> url["mediaType"]
231 MIME.valid?(data["mediaType"]) -> data["mediaType"]
232 MIME.valid?(data["mimeType"]) -> data["mimeType"]
238 is_map(url) && is_binary(url["href"]) -> url["href"]
239 is_binary(data["url"]) -> data["url"]
240 is_binary(data["href"]) -> data["href"]
248 "type" => Map.get(url || %{}, "type", "Link")
250 |> Maps.put_if_present("mediaType", media_type)
253 "url" => [attachment_url],
254 "type" => data["type"] || "Document"
256 |> Maps.put_if_present("mediaType", media_type)
257 |> Maps.put_if_present("name", data["name"])
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(%{"type" => "Video", "url" => url} = object) when is_list(url) do
281 Enum.find(url, fn x ->
282 media_type = x["mediaType"] || x["mimeType"] || ""
284 is_map(x) and String.starts_with?(media_type, "video/")
288 Enum.find(url, fn x -> is_map(x) and (x["mediaType"] || x["mimeType"]) == "text/html" end)
291 |> Map.put("attachment", [attachment])
292 |> Map.put("url", link_element["href"])
295 def fix_url(%{"type" => object_type, "url" => url} = object)
296 when object_type != "Video" and is_list(url) do
297 first_element = Enum.at(url, 0)
301 is_bitstring(first_element) -> first_element
302 is_map(first_element) -> first_element["href"] || ""
306 Map.put(object, "url", url_string)
309 def fix_url(object), do: object
311 def fix_emoji(%{"tag" => tags} = object) when is_list(tags) do
314 |> Enum.filter(fn data -> data["type"] == "Emoji" and data["icon"] end)
315 |> Enum.reduce(%{}, fn data, mapping ->
316 name = String.trim(data["name"], ":")
318 Map.put(mapping, name, data["icon"]["url"])
321 Map.put(object, "emoji", emoji)
324 def fix_emoji(%{"tag" => %{"type" => "Emoji"} = tag} = object) do
325 name = String.trim(tag["name"], ":")
326 emoji = %{name => tag["icon"]["url"]}
328 Map.put(object, "emoji", emoji)
331 def fix_emoji(object), do: object
333 def fix_tag(%{"tag" => tag} = object) when is_list(tag) do
336 |> Enum.filter(fn data -> data["type"] == "Hashtag" and data["name"] end)
337 |> Enum.map(fn data -> String.slice(data["name"], 1..-1) end)
339 Map.put(object, "tag", tag ++ tags)
342 def fix_tag(%{"tag" => %{"type" => "Hashtag", "name" => hashtag} = tag} = object) do
343 combined = [tag, String.slice(hashtag, 1..-1)]
345 Map.put(object, "tag", combined)
348 def fix_tag(%{"tag" => %{} = tag} = object), do: Map.put(object, "tag", [tag])
350 def fix_tag(object), do: object
352 # content map usually only has one language so this will do for now.
353 def fix_content_map(%{"contentMap" => content_map} = object) do
354 content_groups = Map.to_list(content_map)
355 {_, content} = Enum.at(content_groups, 0)
357 Map.put(object, "content", content)
360 def fix_content_map(object), do: object
362 def fix_type(object, options \\ [])
364 def fix_type(%{"inReplyTo" => reply_id, "name" => _} = object, options)
365 when is_binary(reply_id) do
366 with true <- Federator.allowed_thread_distance?(options[:depth]),
367 {:ok, %{data: %{"type" => "Question"} = _} = _} <- get_obj_helper(reply_id, options) do
368 Map.put(object, "type", "Answer")
374 def fix_type(object, _), do: object
376 defp fix_content(%{"mediaType" => "text/markdown", "content" => content} = object)
377 when is_binary(content) do
380 |> Earmark.as_html!(%Earmark.Options{renderer: EarmarkRenderer})
381 |> Pleroma.HTML.filter_tags()
383 Map.merge(object, %{"content" => html_content, "mediaType" => "text/html"})
386 defp fix_content(object), do: object
388 # Reduce the object list to find the reported user.
389 defp get_reported(objects) do
390 Enum.reduce_while(objects, nil, fn ap_id, _ ->
391 with %User{} = user <- User.get_cached_by_ap_id(ap_id) do
399 # Compatibility wrapper for Mastodon votes
400 defp handle_create(%{"object" => %{"type" => "Answer"}} = data, _user) do
401 handle_incoming(data)
404 defp handle_create(%{"object" => object} = data, user) do
409 context: object["context"],
411 published: data["published"],
419 |> ActivityPub.create()
422 def handle_incoming(data, options \\ [])
424 # Flag objects are placed ahead of the ID check because Mastodon 2.8 and earlier send them
426 def handle_incoming(%{"type" => "Flag", "object" => objects, "actor" => actor} = data, _options) do
427 with context <- data["context"] || Utils.generate_context_id(),
428 content <- data["content"] || "",
429 %User{} = actor <- User.get_cached_by_ap_id(actor),
430 # Reduce the object list to find the reported user.
431 %User{} = account <- get_reported(objects),
432 # Remove the reported user from the object list.
433 statuses <- Enum.filter(objects, fn ap_id -> ap_id != account.ap_id end) do
440 additional: %{"cc" => [account.ap_id]}
442 |> ActivityPub.flag()
446 # disallow objects with bogus IDs
447 def handle_incoming(%{"id" => nil}, _options), do: :error
448 def handle_incoming(%{"id" => ""}, _options), do: :error
449 # length of https:// = 8, should validate better, but good enough for now.
450 def handle_incoming(%{"id" => id}, _options) when is_binary(id) and byte_size(id) < 8,
453 # TODO: validate those with a Ecto scheme
457 %{"type" => "Create", "object" => %{"type" => objtype} = object} = data,
460 when objtype in ~w{Article Note Video Page} do
461 actor = Containment.get_actor(data)
463 with nil <- Activity.get_create_by_object_ap_id(object["id"]),
464 {:ok, %User{} = user} <- User.get_or_fetch_by_ap_id(actor) do
467 |> Map.put("object", fix_object(object, options))
468 |> Map.put("actor", actor)
471 with {:ok, created_activity} <- handle_create(data, user) do
472 reply_depth = (options[:depth] || 0) + 1
474 if Federator.allowed_thread_distance?(reply_depth) do
475 for reply_id <- replies(object) do
476 Pleroma.Workers.RemoteFetcherWorker.enqueue("fetch_remote", %{
478 "depth" => reply_depth
483 {:ok, created_activity}
486 %Activity{} = activity -> {:ok, activity}
492 %{"type" => "Listen", "object" => %{"type" => "Audio"} = object} = data,
495 actor = Containment.get_actor(data)
498 Map.put(data, "actor", actor)
501 with {:ok, %User{} = user} <- User.get_or_fetch_by_ap_id(data["actor"]) do
502 reply_depth = (options[:depth] || 0) + 1
503 options = Keyword.put(options, :depth, reply_depth)
504 object = fix_object(object, options)
512 published: data["published"],
513 additional: Map.take(data, ["cc", "id"])
516 ActivityPub.listen(params)
522 @misskey_reactions %{
536 @doc "Rewrite misskey likes into EmojiReacts"
540 "_misskey_reaction" => reaction
545 |> Map.put("type", "EmojiReact")
546 |> Map.put("content", @misskey_reactions[reaction] || reaction)
547 |> handle_incoming(options)
551 %{"type" => "Create", "object" => %{"type" => objtype}} = data,
554 when objtype in ~w{Question Answer ChatMessage Audio Event} do
555 with {:ok, %User{}} <- ObjectValidator.fetch_actor(data),
556 {:ok, activity, _} <- Pipeline.common_pipeline(data, local: false) do
561 def handle_incoming(%{"type" => type} = data, _options)
562 when type in ~w{Like EmojiReact Announce} do
563 with :ok <- ObjectValidator.fetch_actor_and_object(data),
564 {:ok, activity, _meta} <-
565 Pipeline.common_pipeline(data, local: false) do
573 %{"type" => type} = data,
576 when type in ~w{Update Block Follow Accept Reject} do
577 with {:ok, %User{}} <- ObjectValidator.fetch_actor(data),
578 {:ok, activity, _} <-
579 Pipeline.common_pipeline(data, local: false) do
585 %{"type" => "Delete"} = data,
588 with {:ok, activity, _} <-
589 Pipeline.common_pipeline(data, local: false) do
592 {:error, {:validate_object, _}} = e ->
593 # Check if we have a create activity for this
594 with {:ok, object_id} <- ObjectValidators.ObjectID.cast(data["object"]),
595 %Activity{data: %{"actor" => actor}} <-
596 Activity.create_by_object_ap_id(object_id) |> Repo.one(),
597 # We have one, insert a tombstone and retry
598 {:ok, tombstone_data, _} <- Builder.tombstone(actor, object_id),
599 {:ok, _tombstone} <- Object.create(tombstone_data) do
600 handle_incoming(data)
610 "object" => %{"type" => "Follow", "object" => followed},
616 with %User{local: true} = followed <- User.get_cached_by_ap_id(followed),
617 {:ok, %User{} = follower} <- User.get_or_fetch_by_ap_id(follower),
618 {:ok, activity} <- ActivityPub.unfollow(follower, followed, id, false) do
619 User.unfollow(follower, followed)
629 "object" => %{"type" => type}
633 when type in ["Like", "EmojiReact", "Announce", "Block"] do
634 with {:ok, activity, _} <- Pipeline.common_pipeline(data, local: false) do
639 # For Undos that don't have the complete object attached, try to find it in our database.
647 when is_binary(object) do
648 with %Activity{data: data} <- Activity.get_by_ap_id(object) do
650 |> Map.put("object", data)
651 |> handle_incoming(options)
660 "actor" => origin_actor,
661 "object" => origin_actor,
662 "target" => target_actor
666 with %User{} = origin_user <- User.get_cached_by_ap_id(origin_actor),
667 {:ok, %User{} = target_user} <- User.get_or_fetch_by_ap_id(target_actor),
668 true <- origin_actor in target_user.also_known_as do
669 ActivityPub.move(origin_user, target_user, false)
675 def handle_incoming(_, _), do: :error
677 @spec get_obj_helper(String.t(), Keyword.t()) :: {:ok, Object.t()} | nil
678 def get_obj_helper(id, options \\ []) do
679 case Object.normalize(id, true, options) do
680 %Object{} = object -> {:ok, object}
685 @spec get_embedded_obj_helper(String.t() | Object.t(), User.t()) :: {:ok, Object.t()} | nil
686 def get_embedded_obj_helper(%{"attributedTo" => attributed_to, "id" => object_id} = data, %User{
689 when attributed_to == ap_id do
690 with {:ok, activity} <-
695 "actor" => attributed_to,
698 {:ok, Object.normalize(activity)}
700 _ -> get_obj_helper(object_id)
704 def get_embedded_obj_helper(object_id, _) do
705 get_obj_helper(object_id)
708 def set_reply_to_uri(%{"inReplyTo" => in_reply_to} = object) when is_binary(in_reply_to) do
709 with false <- String.starts_with?(in_reply_to, "http"),
710 {:ok, %{data: replied_to_object}} <- get_obj_helper(in_reply_to) do
711 Map.put(object, "inReplyTo", replied_to_object["external_url"] || in_reply_to)
717 def set_reply_to_uri(obj), do: obj
720 Serialized Mastodon-compatible `replies` collection containing _self-replies_.
721 Based on Mastodon's ActivityPub::NoteSerializer#replies.
723 def set_replies(obj_data) do
725 with limit when limit > 0 <-
726 Pleroma.Config.get([:activitypub, :note_replies_output_limit], 0),
727 %Object{} = object <- Object.get_cached_by_ap_id(obj_data["id"]) do
729 |> Object.self_replies()
730 |> select([o], fragment("?->>'id'", o.data))
737 set_replies(obj_data, replies_uris)
740 defp set_replies(obj, []) do
744 defp set_replies(obj, replies_uris) do
745 replies_collection = %{
746 "type" => "Collection",
747 "items" => replies_uris
750 Map.merge(obj, %{"replies" => replies_collection})
753 def replies(%{"replies" => %{"first" => %{"items" => items}}}) when not is_nil(items) do
757 def replies(%{"replies" => %{"items" => items}}) when not is_nil(items) do
761 def replies(_), do: []
763 # Prepares the object of an outgoing create activity.
764 def prepare_object(object) do
771 |> prepare_attachments
775 |> strip_internal_fields
776 |> strip_internal_tags
782 # internal -> Mastodon
785 def prepare_outgoing(%{"type" => activity_type, "object" => object_id} = data)
786 when activity_type in ["Create", "Listen"] do
789 |> Object.normalize()
795 |> Map.put("object", object)
796 |> Map.merge(Utils.make_json_ld_header())
802 def prepare_outgoing(%{"type" => "Announce", "actor" => ap_id, "object" => object_id} = data) do
805 |> Object.normalize()
808 if Visibility.is_private?(object) && object.data["actor"] == ap_id do
809 data |> Map.put("object", object |> Map.get(:data) |> prepare_object)
811 data |> maybe_fix_object_url
816 |> strip_internal_fields
817 |> Map.merge(Utils.make_json_ld_header())
823 # Mastodon Accept/Reject requires a non-normalized object containing the actor URIs,
824 # because of course it does.
825 def prepare_outgoing(%{"type" => "Accept"} = data) do
826 with follow_activity <- Activity.normalize(data["object"]) do
828 "actor" => follow_activity.actor,
829 "object" => follow_activity.data["object"],
830 "id" => follow_activity.data["id"],
836 |> Map.put("object", object)
837 |> Map.merge(Utils.make_json_ld_header())
843 def prepare_outgoing(%{"type" => "Reject"} = data) do
844 with follow_activity <- Activity.normalize(data["object"]) do
846 "actor" => follow_activity.actor,
847 "object" => follow_activity.data["object"],
848 "id" => follow_activity.data["id"],
854 |> Map.put("object", object)
855 |> Map.merge(Utils.make_json_ld_header())
861 def prepare_outgoing(%{"type" => _type} = data) do
864 |> strip_internal_fields
865 |> maybe_fix_object_url
866 |> Map.merge(Utils.make_json_ld_header())
871 def maybe_fix_object_url(%{"object" => object} = data) when is_binary(object) do
872 with false <- String.starts_with?(object, "http"),
873 {:fetch, {:ok, relative_object}} <- {:fetch, get_obj_helper(object)},
874 %{data: %{"external_url" => external_url}} when not is_nil(external_url) <-
876 Map.put(data, "object", external_url)
879 Logger.error("Couldn't fetch #{object} #{inspect(e)}")
887 def maybe_fix_object_url(data), do: data
889 def add_hashtags(object) do
891 (object["tag"] || [])
893 # Expand internal representation tags into AS2 tags.
894 tag when is_binary(tag) ->
896 "href" => Pleroma.Web.Endpoint.url() <> "/tags/#{tag}",
901 # Do not process tags which are already AS2 tag objects.
902 tag when is_map(tag) ->
906 Map.put(object, "tag", tags)
909 # TODO These should be added on our side on insertion, it doesn't make much
910 # sense to regenerate these all the time
911 def add_mention_tags(object) do
912 to = object["to"] || []
913 cc = object["cc"] || []
914 mentioned = User.get_users_from_set(to ++ cc, local_only: false)
916 mentions = Enum.map(mentioned, &build_mention_tag/1)
918 tags = object["tag"] || []
919 Map.put(object, "tag", tags ++ mentions)
922 defp build_mention_tag(%{ap_id: ap_id, nickname: nickname} = _) do
923 %{"type" => "Mention", "href" => ap_id, "name" => "@#{nickname}"}
926 def take_emoji_tags(%User{emoji: emoji}) do
929 |> Enum.map(&build_emoji_tag/1)
932 # TODO: we should probably send mtime instead of unix epoch time for updated
933 def add_emoji_tags(%{"emoji" => emoji} = object) do
934 tags = object["tag"] || []
936 out = Enum.map(emoji, &build_emoji_tag/1)
938 Map.put(object, "tag", tags ++ out)
941 def add_emoji_tags(object), do: object
943 defp build_emoji_tag({name, url}) do
945 "icon" => %{"url" => url, "type" => "Image"},
946 "name" => ":" <> name <> ":",
948 "updated" => "1970-01-01T00:00:00Z",
953 def set_conversation(object) do
954 Map.put(object, "conversation", object["context"])
957 def set_sensitive(%{"sensitive" => true} = object) do
961 def set_sensitive(object) do
962 tags = object["tag"] || []
963 Map.put(object, "sensitive", "nsfw" in tags)
966 def set_type(%{"type" => "Answer"} = object) do
967 Map.put(object, "type", "Note")
970 def set_type(object), do: object
972 def add_attributed_to(object) do
973 attributed_to = object["attributedTo"] || object["actor"]
974 Map.put(object, "attributedTo", attributed_to)
978 def prepare_attachments(%{"type" => "ChatMessage"} = object), do: object
980 def prepare_attachments(object) do
983 |> Map.get("attachment", [])
984 |> Enum.map(fn data ->
985 [%{"mediaType" => media_type, "href" => href} | _] = data["url"]
989 "mediaType" => media_type,
990 "name" => data["name"],
995 Map.put(object, "attachment", attachments)
998 def strip_internal_fields(object) do
999 Map.drop(object, Pleroma.Constants.object_internal_fields())
1002 defp strip_internal_tags(%{"tag" => tags} = object) do
1003 tags = Enum.filter(tags, fn x -> is_map(x) end)
1005 Map.put(object, "tag", tags)
1008 defp strip_internal_tags(object), do: object
1010 def perform(:user_upgrade, user) do
1011 # we pass a fake user so that the followers collection is stripped away
1012 old_follower_address = User.ap_followers(%User{nickname: user.nickname})
1016 where: ^old_follower_address in a.recipients,
1021 "array_replace(?,?,?)",
1023 ^old_follower_address,
1024 ^user.follower_address
1029 |> Repo.update_all([])
1032 def upgrade_user_from_ap_id(ap_id) do
1033 with %User{local: false} = user <- User.get_cached_by_ap_id(ap_id),
1034 {:ok, data} <- ActivityPub.fetch_and_prepare_user_from_ap_id(ap_id),
1035 {:ok, user} <- update_user(user, data) do
1036 TransmogrifierWorker.enqueue("user_upgrade", %{"user_id" => user.id})
1039 %User{} = user -> {:ok, user}
1044 defp update_user(user, data) do
1046 |> User.remote_user_changeset(data)
1047 |> User.update_and_set_cache()
1050 def maybe_fix_user_url(%{"url" => url} = data) when is_map(url) do
1051 Map.put(data, "url", url["href"])
1054 def maybe_fix_user_url(data), do: data
1056 def maybe_fix_user_object(data), do: maybe_fix_user_url(data)