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)
227 |> Maps.put_if_present("width", (url || %{})["width"] || data["width"])
228 |> Maps.put_if_present("height", (url || %{})["height"] || data["height"])
231 "url" => [attachment_url],
232 "type" => data["type"] || "Document"
234 |> Maps.put_if_present("mediaType", media_type)
235 |> Maps.put_if_present("name", data["name"])
236 |> Maps.put_if_present("blurhash", data["blurhash"])
243 Map.put(object, "attachment", attachments)
246 def fix_attachments(%{"attachment" => attachment} = object) when is_map(attachment) do
248 |> Map.put("attachment", [attachment])
252 def fix_attachments(object), do: object
254 def fix_url(%{"url" => url} = object) when is_map(url) do
255 Map.put(object, "url", url["href"])
258 def fix_url(%{"url" => url} = object) when is_list(url) do
259 first_element = Enum.at(url, 0)
263 is_bitstring(first_element) -> first_element
264 is_map(first_element) -> first_element["href"] || ""
268 Map.put(object, "url", url_string)
271 def fix_url(object), do: object
273 def fix_emoji(%{"tag" => tags} = object) when is_list(tags) do
276 |> Enum.filter(fn data -> is_map(data) and data["type"] == "Emoji" and data["icon"] end)
277 |> Enum.reduce(%{}, fn data, mapping ->
278 name = String.trim(data["name"], ":")
280 Map.put(mapping, name, data["icon"]["url"])
283 Map.put(object, "emoji", emoji)
286 def fix_emoji(%{"tag" => %{"type" => "Emoji"} = tag} = object) do
287 name = String.trim(tag["name"], ":")
288 emoji = %{name => tag["icon"]["url"]}
290 Map.put(object, "emoji", emoji)
293 def fix_emoji(object), do: object
295 def fix_tag(%{"tag" => tag} = object) when is_list(tag) do
298 |> Enum.filter(fn data -> data["type"] == "Hashtag" and data["name"] end)
300 %{"name" => "#" <> hashtag} -> String.downcase(hashtag)
301 %{"name" => hashtag} -> String.downcase(hashtag)
304 Map.put(object, "tag", tag ++ tags)
307 def fix_tag(%{"tag" => %{} = tag} = object) do
309 |> Map.put("tag", [tag])
313 def fix_tag(object), do: object
315 # content map usually only has one language so this will do for now.
316 def fix_content_map(%{"contentMap" => content_map} = object) do
317 content_groups = Map.to_list(content_map)
318 {_, content} = Enum.at(content_groups, 0)
320 Map.put(object, "content", content)
323 def fix_content_map(object), do: object
325 defp fix_type(%{"type" => "Note", "inReplyTo" => reply_id, "name" => _} = object, options)
326 when is_binary(reply_id) do
327 options = Keyword.put(options, :fetch, true)
329 with %Object{data: %{"type" => "Question"}} <- Object.normalize(reply_id, options) do
330 Map.put(object, "type", "Answer")
336 defp fix_type(object, _options), do: object
338 # Reduce the object list to find the reported user.
339 defp get_reported(objects) do
340 Enum.reduce_while(objects, nil, fn ap_id, _ ->
341 with %User{} = user <- User.get_cached_by_ap_id(ap_id) do
349 # Compatibility wrapper for Mastodon votes
350 defp handle_create(%{"object" => %{"type" => "Answer"}} = data, _user) do
351 handle_incoming(data)
354 defp handle_create(%{"object" => object} = data, user) do
359 context: object["context"],
361 published: data["published"],
369 |> ActivityPub.create()
372 def handle_incoming(data, options \\ [])
374 # Flag objects are placed ahead of the ID check because Mastodon 2.8 and earlier send them
376 def handle_incoming(%{"type" => "Flag", "object" => objects, "actor" => actor} = data, _options) do
377 with context <- data["context"] || Utils.generate_context_id(),
378 content <- data["content"] || "",
379 %User{} = actor <- User.get_cached_by_ap_id(actor),
380 # Reduce the object list to find the reported user.
381 %User{} = account <- get_reported(objects),
382 # Remove the reported user from the object list.
383 statuses <- Enum.filter(objects, fn ap_id -> ap_id != account.ap_id end) do
390 additional: %{"cc" => [account.ap_id]}
392 |> ActivityPub.flag()
396 # disallow objects with bogus IDs
397 def handle_incoming(%{"id" => nil}, _options), do: :error
398 def handle_incoming(%{"id" => ""}, _options), do: :error
399 # length of https:// = 8, should validate better, but good enough for now.
400 def handle_incoming(%{"id" => id}, _options) when is_binary(id) and byte_size(id) < 8,
403 # TODO: validate those with a Ecto scheme
407 %{"type" => "Create", "object" => %{"type" => "Page"} = object} = data,
410 actor = Containment.get_actor(data)
412 with nil <- Activity.get_create_by_object_ap_id(object["id"]),
413 {:ok, %User{} = user} <- User.get_or_fetch_by_ap_id(actor) do
416 |> Map.put("object", fix_object(object, options))
417 |> Map.put("actor", actor)
420 with {:ok, created_activity} <- handle_create(data, user) do
421 reply_depth = (options[:depth] || 0) + 1
423 if Federator.allowed_thread_distance?(reply_depth) do
424 for reply_id <- replies(object) do
425 Pleroma.Workers.RemoteFetcherWorker.enqueue("fetch_remote", %{
427 "depth" => reply_depth
432 {:ok, created_activity}
435 %Activity{} = activity -> {:ok, activity}
441 %{"type" => "Listen", "object" => %{"type" => "Audio"} = object} = data,
444 actor = Containment.get_actor(data)
447 Map.put(data, "actor", actor)
450 with {:ok, %User{} = user} <- User.get_or_fetch_by_ap_id(data["actor"]) do
451 reply_depth = (options[:depth] || 0) + 1
452 options = Keyword.put(options, :depth, reply_depth)
453 object = fix_object(object, options)
461 published: data["published"],
462 additional: Map.take(data, ["cc", "id"])
465 ActivityPub.listen(params)
471 @misskey_reactions %{
485 @doc "Rewrite misskey likes into EmojiReacts"
489 "_misskey_reaction" => reaction
494 |> Map.put("type", "EmojiReact")
495 |> Map.put("content", @misskey_reactions[reaction] || reaction)
496 |> handle_incoming(options)
500 %{"type" => "Create", "object" => %{"type" => objtype, "id" => obj_id}} = data,
503 when objtype in ~w{Question Answer ChatMessage Audio Video Event Article Note} do
504 fetch_options = Keyword.put(options, :depth, (options[:depth] || 0) + 1)
508 |> strip_internal_fields()
509 |> fix_type(fetch_options)
510 |> fix_in_reply_to(fetch_options)
512 data = Map.put(data, "object", object)
513 options = Keyword.put(options, :local, false)
515 with {:ok, %User{}} <- ObjectValidator.fetch_actor(data),
516 nil <- Activity.get_create_by_object_ap_id(obj_id),
517 {:ok, activity, _} <- Pipeline.common_pipeline(data, options) do
520 %Activity{} = activity -> {:ok, activity}
525 def handle_incoming(%{"type" => type} = data, _options)
526 when type in ~w{Like EmojiReact Announce Add Remove} do
527 with :ok <- ObjectValidator.fetch_actor_and_object(data),
528 {:ok, activity, _meta} <-
529 Pipeline.common_pipeline(data, local: false) do
537 %{"type" => type} = data,
540 when type in ~w{Update Block Follow Accept Reject} do
541 with {:ok, %User{}} <- ObjectValidator.fetch_actor(data),
542 {:ok, activity, _} <-
543 Pipeline.common_pipeline(data, local: false) do
549 %{"type" => "Delete"} = data,
552 with {:ok, activity, _} <-
553 Pipeline.common_pipeline(data, local: false) do
556 {:error, {:validate, _}} = e ->
557 # Check if we have a create activity for this
558 with {:ok, object_id} <- ObjectValidators.ObjectID.cast(data["object"]),
559 %Activity{data: %{"actor" => actor}} <-
560 Activity.create_by_object_ap_id(object_id) |> Repo.one(),
561 # We have one, insert a tombstone and retry
562 {:ok, tombstone_data, _} <- Builder.tombstone(actor, object_id),
563 {:ok, _tombstone} <- Object.create(tombstone_data) do
564 handle_incoming(data)
574 "object" => %{"type" => "Follow", "object" => followed},
580 with %User{local: true} = followed <- User.get_cached_by_ap_id(followed),
581 {:ok, %User{} = follower} <- User.get_or_fetch_by_ap_id(follower),
582 {:ok, activity} <- ActivityPub.unfollow(follower, followed, id, false) do
583 User.unfollow(follower, followed)
593 "object" => %{"type" => type}
597 when type in ["Like", "EmojiReact", "Announce", "Block"] do
598 with {:ok, activity, _} <- Pipeline.common_pipeline(data, local: false) do
603 # For Undos that don't have the complete object attached, try to find it in our database.
611 when is_binary(object) do
612 with %Activity{data: data} <- Activity.get_by_ap_id(object) do
614 |> Map.put("object", data)
615 |> handle_incoming(options)
624 "actor" => origin_actor,
625 "object" => origin_actor,
626 "target" => target_actor
630 with %User{} = origin_user <- User.get_cached_by_ap_id(origin_actor),
631 {:ok, %User{} = target_user} <- User.get_or_fetch_by_ap_id(target_actor),
632 true <- origin_actor in target_user.also_known_as do
633 ActivityPub.move(origin_user, target_user, false)
639 def handle_incoming(_, _), do: :error
641 @spec get_obj_helper(String.t(), Keyword.t()) :: {:ok, Object.t()} | nil
642 def get_obj_helper(id, options \\ []) do
643 options = Keyword.put(options, :fetch, true)
645 case Object.normalize(id, options) do
646 %Object{} = object -> {:ok, object}
651 @spec get_embedded_obj_helper(String.t() | Object.t(), User.t()) :: {:ok, Object.t()} | nil
652 def get_embedded_obj_helper(%{"attributedTo" => attributed_to, "id" => object_id} = data, %User{
655 when attributed_to == ap_id do
656 with {:ok, activity} <-
661 "actor" => attributed_to,
664 {:ok, Object.normalize(activity, fetch: false)}
666 _ -> get_obj_helper(object_id)
670 def get_embedded_obj_helper(object_id, _) do
671 get_obj_helper(object_id)
674 def set_reply_to_uri(%{"inReplyTo" => in_reply_to} = object) when is_binary(in_reply_to) do
675 with false <- String.starts_with?(in_reply_to, "http"),
676 {:ok, %{data: replied_to_object}} <- get_obj_helper(in_reply_to) do
677 Map.put(object, "inReplyTo", replied_to_object["external_url"] || in_reply_to)
683 def set_reply_to_uri(obj), do: obj
686 Serialized Mastodon-compatible `replies` collection containing _self-replies_.
687 Based on Mastodon's ActivityPub::NoteSerializer#replies.
689 def set_replies(obj_data) do
691 with limit when limit > 0 <-
692 Pleroma.Config.get([:activitypub, :note_replies_output_limit], 0),
693 %Object{} = object <- Object.get_cached_by_ap_id(obj_data["id"]) do
695 |> Object.self_replies()
696 |> select([o], fragment("?->>'id'", o.data))
703 set_replies(obj_data, replies_uris)
706 defp set_replies(obj, []) do
710 defp set_replies(obj, replies_uris) do
711 replies_collection = %{
712 "type" => "Collection",
713 "items" => replies_uris
716 Map.merge(obj, %{"replies" => replies_collection})
719 def replies(%{"replies" => %{"first" => %{"items" => items}}}) when not is_nil(items) do
723 def replies(%{"replies" => %{"items" => items}}) when not is_nil(items) do
727 def replies(_), do: []
729 # Prepares the object of an outgoing create activity.
730 def prepare_object(object) do
736 |> prepare_attachments
740 |> strip_internal_fields
741 |> strip_internal_tags
747 # internal -> Mastodon
750 def prepare_outgoing(%{"type" => activity_type, "object" => object_id} = data)
751 when activity_type in ["Create", "Listen"] do
754 |> Object.normalize(fetch: false)
760 |> Map.put("object", object)
761 |> Map.merge(Utils.make_json_ld_header())
767 def prepare_outgoing(%{"type" => "Announce", "actor" => ap_id, "object" => object_id} = data) do
770 |> Object.normalize(fetch: false)
773 if Visibility.is_private?(object) && object.data["actor"] == ap_id do
774 data |> Map.put("object", object |> Map.get(:data) |> prepare_object)
776 data |> maybe_fix_object_url
781 |> strip_internal_fields
782 |> Map.merge(Utils.make_json_ld_header())
788 # Mastodon Accept/Reject requires a non-normalized object containing the actor URIs,
789 # because of course it does.
790 def prepare_outgoing(%{"type" => "Accept"} = data) do
791 with follow_activity <- Activity.normalize(data["object"]) do
793 "actor" => follow_activity.actor,
794 "object" => follow_activity.data["object"],
795 "id" => follow_activity.data["id"],
801 |> Map.put("object", object)
802 |> Map.merge(Utils.make_json_ld_header())
808 def prepare_outgoing(%{"type" => "Reject"} = data) do
809 with follow_activity <- Activity.normalize(data["object"]) do
811 "actor" => follow_activity.actor,
812 "object" => follow_activity.data["object"],
813 "id" => follow_activity.data["id"],
819 |> Map.put("object", object)
820 |> Map.merge(Utils.make_json_ld_header())
826 def prepare_outgoing(%{"type" => _type} = data) do
829 |> strip_internal_fields
830 |> maybe_fix_object_url
831 |> Map.merge(Utils.make_json_ld_header())
836 def maybe_fix_object_url(%{"object" => object} = data) when is_binary(object) do
837 with false <- String.starts_with?(object, "http"),
838 {:fetch, {:ok, relative_object}} <- {:fetch, get_obj_helper(object)},
839 %{data: %{"external_url" => external_url}} when not is_nil(external_url) <-
841 Map.put(data, "object", external_url)
844 Logger.error("Couldn't fetch #{object} #{inspect(e)}")
852 def maybe_fix_object_url(data), do: data
854 def add_hashtags(object) do
856 (object["tag"] || [])
858 # Expand internal representation tags into AS2 tags.
859 tag when is_binary(tag) ->
861 "href" => Pleroma.Web.Endpoint.url() <> "/tags/#{tag}",
866 # Do not process tags which are already AS2 tag objects.
867 tag when is_map(tag) ->
871 Map.put(object, "tag", tags)
874 # TODO These should be added on our side on insertion, it doesn't make much
875 # sense to regenerate these all the time
876 def add_mention_tags(object) do
877 to = object["to"] || []
878 cc = object["cc"] || []
879 mentioned = User.get_users_from_set(to ++ cc, local_only: false)
881 mentions = Enum.map(mentioned, &build_mention_tag/1)
883 tags = object["tag"] || []
884 Map.put(object, "tag", tags ++ mentions)
887 defp build_mention_tag(%{ap_id: ap_id, nickname: nickname} = _) do
888 %{"type" => "Mention", "href" => ap_id, "name" => "@#{nickname}"}
891 def take_emoji_tags(%User{emoji: emoji}) do
894 |> Enum.map(&build_emoji_tag/1)
897 # TODO: we should probably send mtime instead of unix epoch time for updated
898 def add_emoji_tags(%{"emoji" => emoji} = object) do
899 tags = object["tag"] || []
901 out = Enum.map(emoji, &build_emoji_tag/1)
903 Map.put(object, "tag", tags ++ out)
906 def add_emoji_tags(object), do: object
908 defp build_emoji_tag({name, url}) do
910 "icon" => %{"url" => "#{URI.encode(url)}", "type" => "Image"},
911 "name" => ":" <> name <> ":",
913 "updated" => "1970-01-01T00:00:00Z",
918 def set_conversation(object) do
919 Map.put(object, "conversation", object["context"])
922 def set_type(%{"type" => "Answer"} = object) do
923 Map.put(object, "type", "Note")
926 def set_type(object), do: object
928 def add_attributed_to(object) do
929 attributed_to = object["attributedTo"] || object["actor"]
930 Map.put(object, "attributedTo", attributed_to)
934 def prepare_attachments(%{"type" => "ChatMessage"} = object), do: object
936 def prepare_attachments(object) do
939 |> Map.get("attachment", [])
940 |> Enum.map(fn data ->
941 [%{"mediaType" => media_type, "href" => href} = url | _] = data["url"]
945 "mediaType" => media_type,
946 "name" => data["name"],
949 |> Maps.put_if_present("width", url["width"])
950 |> Maps.put_if_present("height", url["height"])
951 |> Maps.put_if_present("blurhash", data["blurhash"])
954 Map.put(object, "attachment", attachments)
957 def strip_internal_fields(object) do
958 Map.drop(object, Pleroma.Constants.object_internal_fields())
961 defp strip_internal_tags(%{"tag" => tags} = object) do
962 tags = Enum.filter(tags, fn x -> is_map(x) end)
964 Map.put(object, "tag", tags)
967 defp strip_internal_tags(object), do: object
969 def perform(:user_upgrade, user) do
970 # we pass a fake user so that the followers collection is stripped away
971 old_follower_address = User.ap_followers(%User{nickname: user.nickname})
975 where: ^old_follower_address in a.recipients,
980 "array_replace(?,?,?)",
982 ^old_follower_address,
983 ^user.follower_address
988 |> Repo.update_all([])
991 def upgrade_user_from_ap_id(ap_id) do
992 with %User{local: false} = user <- User.get_cached_by_ap_id(ap_id),
993 {:ok, data} <- ActivityPub.fetch_and_prepare_user_from_ap_id(ap_id),
994 {:ok, user} <- update_user(user, data) do
995 {:ok, _pid} = Task.start(fn -> ActivityPub.pinned_fetch_task(user) end)
996 TransmogrifierWorker.enqueue("user_upgrade", %{"user_id" => user.id})
999 %User{} = user -> {:ok, user}
1004 defp update_user(user, data) do
1006 |> User.remote_user_changeset(data)
1007 |> User.update_and_set_cache()
1010 def maybe_fix_user_url(%{"url" => url} = data) when is_map(url) do
1011 Map.put(data, "url", url["href"])
1014 def maybe_fix_user_url(data), do: data
1016 def maybe_fix_user_object(data), do: maybe_fix_user_url(data)