1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2019 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.
13 alias Pleroma.Web.ActivityPub.ActivityPub
14 alias Pleroma.Web.ActivityPub.Utils
15 alias Pleroma.Web.ActivityPub.Visibility
21 def get_actor(%{"actor" => actor}) when is_binary(actor) do
25 def get_actor(%{"actor" => actor}) when is_list(actor) do
26 if is_binary(Enum.at(actor, 0)) do
29 Enum.find(actor, fn %{"type" => type} -> type in ["Person", "Service", "Application"] end)
34 def get_actor(%{"actor" => %{"id" => id}}) when is_bitstring(id) do
38 def get_actor(%{"actor" => nil, "attributedTo" => actor}) when not is_nil(actor) do
39 get_actor(%{"actor" => actor})
43 Checks that an imported AP object's actor matches the domain it came from.
45 def contain_origin(_id, %{"actor" => nil}), do: :error
47 def contain_origin(id, %{"actor" => _actor} = params) do
48 id_uri = URI.parse(id)
49 actor_uri = URI.parse(get_actor(params))
51 if id_uri.host == actor_uri.host do
58 def contain_origin_from_id(_id, %{"id" => nil}), do: :error
60 def contain_origin_from_id(id, %{"id" => other_id} = _params) do
61 id_uri = URI.parse(id)
62 other_uri = URI.parse(other_id)
64 if id_uri.host == other_uri.host do
72 Modifies an incoming AP object (mastodon format) to our internal format.
74 def fix_object(object) do
88 def fix_addressing_list(map, field) do
89 if is_binary(map[field]) do
91 |> Map.put(field, [map[field]])
97 def fix_explicit_addressing(%{"to" => to, "cc" => cc} = object, explicit_mentions) do
100 |> Enum.filter(fn x -> x in explicit_mentions end)
104 |> Enum.filter(fn x -> x not in explicit_mentions end)
111 |> Map.put("to", explicit_to)
112 |> Map.put("cc", final_cc)
115 def fix_explicit_addressing(object, _explicit_mentions), do: object
117 # if directMessage flag is set to true, leave the addressing alone
118 def fix_explicit_addressing(%{"directMessage" => true} = object), do: object
120 def fix_explicit_addressing(object) do
123 |> Utils.determine_explicit_mentions()
125 explicit_mentions = explicit_mentions ++ ["https://www.w3.org/ns/activitystreams#Public"]
128 |> fix_explicit_addressing(explicit_mentions)
131 # if as:Public is addressed, then make sure the followers collection is also addressed
132 # so that the activities will be delivered to local users.
133 def fix_implicit_addressing(%{"to" => to, "cc" => cc} = object, followers_collection) do
134 recipients = to ++ cc
136 if followers_collection not in recipients do
138 "https://www.w3.org/ns/activitystreams#Public" in cc ->
139 to = to ++ [followers_collection]
140 Map.put(object, "to", to)
142 "https://www.w3.org/ns/activitystreams#Public" in to ->
143 cc = cc ++ [followers_collection]
144 Map.put(object, "cc", cc)
154 def fix_implicit_addressing(object, _), do: object
156 def fix_addressing(object) do
157 %User{} = user = User.get_cached_by_ap_id(object["actor"])
158 followers_collection = User.ap_followers(user)
161 |> fix_addressing_list("to")
162 |> fix_addressing_list("cc")
163 |> fix_addressing_list("bto")
164 |> fix_addressing_list("bcc")
165 |> fix_explicit_addressing
166 |> fix_implicit_addressing(followers_collection)
169 def fix_actor(%{"attributedTo" => actor} = object) do
171 |> Map.put("actor", get_actor(%{"actor" => actor}))
174 # Check for standardisation
175 # This is what Peertube does
176 # curl -H 'Accept: application/activity+json' $likes | jq .totalItems
177 # Prismo returns only an integer (count) as "likes"
178 def fix_likes(%{"likes" => likes} = object) when not is_map(likes) do
180 |> Map.put("likes", [])
181 |> Map.put("like_count", 0)
184 def fix_likes(object) do
188 def fix_in_reply_to(%{"inReplyTo" => in_reply_to} = object)
189 when not is_nil(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)
201 # Maybe I should output an error too?
206 case fetch_obj_helper(in_reply_to_id) do
207 {:ok, replied_object} ->
208 with %Activity{} = activity <-
209 Activity.get_create_by_object_ap_id(replied_object.data["id"]) do
211 |> Map.put("inReplyTo", replied_object.data["id"])
212 |> Map.put("inReplyToAtomUri", object["inReplyToAtomUri"] || in_reply_to_id)
213 |> Map.put("inReplyToStatusId", activity.id)
214 |> Map.put("conversation", replied_object.data["context"] || object["conversation"])
215 |> Map.put("context", replied_object.data["context"] || object["conversation"])
218 Logger.error("Couldn't fetch \"#{inspect(in_reply_to_id)}\", error: #{inspect(e)}")
223 Logger.error("Couldn't fetch \"#{inspect(in_reply_to_id)}\", error: #{inspect(e)}")
228 def fix_in_reply_to(object), do: object
230 def fix_context(object) do
231 context = object["context"] || object["conversation"] || Utils.generate_context_id()
234 |> Map.put("context", context)
235 |> Map.put("conversation", context)
238 def fix_attachments(%{"attachment" => attachment} = object) when is_list(attachment) do
241 |> Enum.map(fn data ->
242 media_type = data["mediaType"] || data["mimeType"]
243 href = data["url"] || data["href"]
245 url = [%{"type" => "Link", "mediaType" => media_type, "href" => href}]
248 |> Map.put("mediaType", media_type)
249 |> Map.put("url", url)
253 |> Map.put("attachment", attachments)
256 def fix_attachments(%{"attachment" => attachment} = object) when is_map(attachment) do
257 Map.put(object, "attachment", [attachment])
261 def fix_attachments(object), do: object
263 def fix_url(%{"url" => url} = object) when is_map(url) do
265 |> Map.put("url", url["href"])
268 def fix_url(%{"type" => "Video", "url" => url} = object) when is_list(url) do
269 first_element = Enum.at(url, 0)
273 |> Enum.filter(fn x -> is_map(x) end)
274 |> Enum.filter(fn x -> x["mimeType"] == "text/html" end)
278 |> Map.put("attachment", [first_element])
279 |> Map.put("url", link_element["href"])
282 def fix_url(%{"type" => object_type, "url" => url} = object)
283 when object_type != "Video" and is_list(url) do
284 first_element = Enum.at(url, 0)
288 is_bitstring(first_element) -> first_element
289 is_map(first_element) -> first_element["href"] || ""
294 |> Map.put("url", url_string)
297 def fix_url(object), do: object
299 def fix_emoji(%{"tag" => tags} = object) when is_list(tags) do
300 emoji = tags |> Enum.filter(fn data -> data["type"] == "Emoji" and data["icon"] end)
304 |> Enum.reduce(%{}, fn data, mapping ->
305 name = String.trim(data["name"], ":")
307 mapping |> Map.put(name, data["icon"]["url"])
310 # we merge mastodon and pleroma emoji into a single mapping, to allow for both wire formats
311 emoji = Map.merge(object["emoji"] || %{}, emoji)
314 |> Map.put("emoji", emoji)
317 def fix_emoji(%{"tag" => %{"type" => "Emoji"} = tag} = object) do
318 name = String.trim(tag["name"], ":")
319 emoji = %{name => tag["icon"]["url"]}
322 |> Map.put("emoji", emoji)
325 def fix_emoji(object), do: object
327 def fix_tag(%{"tag" => tag} = object) when is_list(tag) do
330 |> Enum.filter(fn data -> data["type"] == "Hashtag" and data["name"] end)
331 |> Enum.map(fn data -> String.slice(data["name"], 1..-1) end)
333 combined = tag ++ tags
336 |> Map.put("tag", combined)
339 def fix_tag(%{"tag" => %{"type" => "Hashtag", "name" => hashtag} = tag} = object) do
340 combined = [tag, String.slice(hashtag, 1..-1)]
343 |> Map.put("tag", combined)
346 def fix_tag(%{"tag" => %{} = tag} = object), do: Map.put(object, "tag", [tag])
348 def fix_tag(object), do: object
350 # content map usually only has one language so this will do for now.
351 def fix_content_map(%{"contentMap" => content_map} = object) do
352 content_groups = Map.to_list(content_map)
353 {_, content} = Enum.at(content_groups, 0)
356 |> Map.put("content", content)
359 def fix_content_map(object), do: object
361 defp mastodon_follow_hack(%{"id" => id, "actor" => follower_id}, followed) do
362 with true <- id =~ "follows",
363 %User{local: true} = follower <- User.get_cached_by_ap_id(follower_id),
364 %Activity{} = activity <- Utils.fetch_latest_follow(follower, followed) do
371 defp mastodon_follow_hack(_, _), do: {:error, nil}
373 defp get_follow_activity(follow_object, followed) do
374 with object_id when not is_nil(object_id) <- Utils.get_ap_id(follow_object),
375 {_, %Activity{} = activity} <- {:activity, Activity.get_by_ap_id(object_id)} do
378 # Can't find the activity. This might a Mastodon 2.3 "Accept"
380 mastodon_follow_hack(follow_object, followed)
387 # Flag objects are placed ahead of the ID check because Mastodon 2.8 and earlier send them
389 def handle_incoming(%{"type" => "Flag", "object" => objects, "actor" => actor} = data) do
390 with context <- data["context"] || Utils.generate_context_id(),
391 content <- data["content"] || "",
392 %User{} = actor <- User.get_cached_by_ap_id(actor),
394 # Reduce the object list to find the reported user.
396 Enum.reduce_while(objects, nil, fn ap_id, _ ->
397 with %User{} = user <- User.get_cached_by_ap_id(ap_id) do
404 # Remove the reported user from the object list.
405 statuses <- Enum.filter(objects, fn ap_id -> ap_id != account.ap_id end) do
413 "cc" => [account.ap_id]
417 ActivityPub.flag(params)
421 # disallow objects with bogus IDs
422 def handle_incoming(%{"id" => nil}), do: :error
423 def handle_incoming(%{"id" => ""}), do: :error
424 # length of https:// = 8, should validate better, but good enough for now.
425 def handle_incoming(%{"id" => id}) when not (is_binary(id) and length(id) > 8), do: :error
427 # TODO: validate those with a Ecto scheme
430 def handle_incoming(%{"type" => "Create", "object" => %{"type" => objtype} = object} = data)
431 when objtype in ["Article", "Note", "Video", "Page"] do
432 actor = get_actor(data)
435 Map.put(data, "actor", actor)
438 with nil <- Activity.get_create_by_object_ap_id(object["id"]),
439 %User{} = user <- User.get_or_fetch_by_ap_id(data["actor"]) do
440 object = fix_object(data["object"])
446 context: object["conversation"],
448 published: data["published"],
457 ActivityPub.create(params)
459 %Activity{} = activity -> {:ok, activity}
465 %{"type" => "Follow", "object" => followed, "actor" => follower, "id" => id} = data
467 with %User{local: true} = followed <- User.get_cached_by_ap_id(followed),
468 %User{} = follower <- User.get_or_fetch_by_ap_id(follower),
469 {:ok, activity} <- ActivityPub.follow(follower, followed, id, false) do
470 if not User.locked?(followed) do
471 ActivityPub.accept(%{
472 to: [follower.ap_id],
478 User.follow(follower, followed)
488 %{"type" => "Accept", "object" => follow_object, "actor" => _actor, "id" => _id} = data
490 with actor <- get_actor(data),
491 %User{} = followed <- User.get_or_fetch_by_ap_id(actor),
492 {:ok, follow_activity} <- get_follow_activity(follow_object, followed),
493 {:ok, follow_activity} <- Utils.update_follow_state(follow_activity, "accept"),
494 %User{local: true} = follower <- User.get_cached_by_ap_id(follow_activity.data["actor"]),
496 ActivityPub.accept(%{
497 to: follow_activity.data["to"],
500 object: follow_activity.data["id"],
503 if not User.following?(follower, followed) do
504 {:ok, _follower} = User.follow(follower, followed)
514 %{"type" => "Reject", "object" => follow_object, "actor" => _actor, "id" => _id} = data
516 with actor <- get_actor(data),
517 %User{} = followed <- User.get_or_fetch_by_ap_id(actor),
518 {:ok, follow_activity} <- get_follow_activity(follow_object, followed),
519 {:ok, follow_activity} <- Utils.update_follow_state(follow_activity, "reject"),
520 %User{local: true} = follower <- User.get_cached_by_ap_id(follow_activity.data["actor"]),
522 ActivityPub.reject(%{
523 to: follow_activity.data["to"],
526 object: follow_activity.data["id"],
529 User.unfollow(follower, followed)
538 %{"type" => "Like", "object" => object_id, "actor" => _actor, "id" => id} = data
540 with actor <- get_actor(data),
541 %User{} = actor <- User.get_or_fetch_by_ap_id(actor),
542 {:ok, object} <- get_obj_helper(object_id) || fetch_obj_helper(object_id),
543 {:ok, activity, _object} <- ActivityPub.like(actor, object, id, false) do
551 %{"type" => "Announce", "object" => object_id, "actor" => _actor, "id" => id} = data
553 with actor <- get_actor(data),
554 %User{} = actor <- User.get_or_fetch_by_ap_id(actor),
555 {:ok, object} <- get_obj_helper(object_id) || fetch_obj_helper(object_id),
556 public <- Visibility.is_public?(data),
557 {:ok, activity, _object} <- ActivityPub.announce(actor, object, id, false, public) do
565 %{"type" => "Update", "object" => %{"type" => object_type} = object, "actor" => actor_id} =
568 when object_type in ["Person", "Application", "Service", "Organization"] do
569 with %User{ap_id: ^actor_id} = actor <- User.get_by_ap_id(object["id"]) do
570 {:ok, new_user_data} = ActivityPub.user_data_from_user_object(object)
572 banner = new_user_data[:info]["banner"]
573 locked = new_user_data[:info]["locked"] || false
577 |> Map.take([:name, :bio, :avatar])
578 |> Map.put(:info, %{"banner" => banner, "locked" => locked})
581 |> User.upgrade_changeset(update_data)
582 |> User.update_and_set_cache()
584 ActivityPub.update(%{
586 to: data["to"] || [],
587 cc: data["cc"] || [],
598 # TODO: We presently assume that any actor on the same origin domain as the object being
599 # deleted has the rights to delete that object. A better way to validate whether or not
600 # the object should be deleted is to refetch the object URI, which should return either
601 # an error or a tombstone. This would allow us to verify that a deletion actually took
604 %{"type" => "Delete", "object" => object_id, "actor" => _actor, "id" => _id} = data
606 object_id = Utils.get_ap_id(object_id)
608 with actor <- get_actor(data),
609 %User{} = actor <- User.get_or_fetch_by_ap_id(actor),
610 {:ok, object} <- get_obj_helper(object_id) || fetch_obj_helper(object_id),
611 :ok <- contain_origin(actor.ap_id, object.data),
612 {:ok, activity} <- ActivityPub.delete(object, false) do
622 "object" => %{"type" => "Announce", "object" => object_id},
627 with actor <- get_actor(data),
628 %User{} = actor <- User.get_or_fetch_by_ap_id(actor),
629 {:ok, object} <- get_obj_helper(object_id) || fetch_obj_helper(object_id),
630 {:ok, activity, _} <- ActivityPub.unannounce(actor, object, id, false) do
640 "object" => %{"type" => "Follow", "object" => followed},
645 with %User{local: true} = followed <- User.get_cached_by_ap_id(followed),
646 %User{} = follower <- User.get_or_fetch_by_ap_id(follower),
647 {:ok, activity} <- ActivityPub.unfollow(follower, followed, id, false) do
648 User.unfollow(follower, followed)
658 "object" => %{"type" => "Block", "object" => blocked},
663 with true <- Pleroma.Config.get([:activitypub, :accept_blocks]),
664 %User{local: true} = blocked <- User.get_cached_by_ap_id(blocked),
665 %User{} = blocker <- User.get_or_fetch_by_ap_id(blocker),
666 {:ok, activity} <- ActivityPub.unblock(blocker, blocked, id, false) do
667 User.unblock(blocker, blocked)
675 %{"type" => "Block", "object" => blocked, "actor" => blocker, "id" => id} = _data
677 with true <- Pleroma.Config.get([:activitypub, :accept_blocks]),
678 %User{local: true} = blocked = User.get_cached_by_ap_id(blocked),
679 %User{} = blocker = User.get_or_fetch_by_ap_id(blocker),
680 {:ok, activity} <- ActivityPub.block(blocker, blocked, id, false) do
681 User.unfollow(blocker, blocked)
682 User.block(blocker, blocked)
692 "object" => %{"type" => "Like", "object" => object_id},
697 with actor <- get_actor(data),
698 %User{} = actor <- User.get_or_fetch_by_ap_id(actor),
699 {:ok, object} <- get_obj_helper(object_id) || fetch_obj_helper(object_id),
700 {:ok, activity, _, _} <- ActivityPub.unlike(actor, object, id, false) do
707 def handle_incoming(_), do: :error
709 def fetch_obj_helper(id) when is_bitstring(id), do: ActivityPub.fetch_object_from_id(id)
710 def fetch_obj_helper(obj) when is_map(obj), do: ActivityPub.fetch_object_from_id(obj["id"])
712 def get_obj_helper(id) do
713 if object = Object.normalize(id), do: {:ok, object}, else: nil
716 def set_reply_to_uri(%{"inReplyTo" => in_reply_to} = object) when is_binary(in_reply_to) do
717 with false <- String.starts_with?(in_reply_to, "http"),
718 {:ok, %{data: replied_to_object}} <- get_obj_helper(in_reply_to) do
719 Map.put(object, "inReplyTo", replied_to_object["external_url"] || in_reply_to)
725 def set_reply_to_uri(obj), do: obj
727 # Prepares the object of an outgoing create activity.
728 def prepare_object(object) do
736 |> prepare_attachments
739 |> strip_internal_fields
740 |> strip_internal_tags
745 # internal -> Mastodon
748 def prepare_outgoing(%{"type" => "Create", "object" => object} = data) do
755 |> Map.put("object", object)
756 |> Map.merge(Utils.make_json_ld_header())
761 # Mastodon Accept/Reject requires a non-normalized object containing the actor URIs,
762 # because of course it does.
763 def prepare_outgoing(%{"type" => "Accept"} = data) do
764 with follow_activity <- Activity.normalize(data["object"]) do
766 "actor" => follow_activity.actor,
767 "object" => follow_activity.data["object"],
768 "id" => follow_activity.data["id"],
774 |> Map.put("object", object)
775 |> Map.merge(Utils.make_json_ld_header())
781 def prepare_outgoing(%{"type" => "Reject"} = data) do
782 with follow_activity <- Activity.normalize(data["object"]) do
784 "actor" => follow_activity.actor,
785 "object" => follow_activity.data["object"],
786 "id" => follow_activity.data["id"],
792 |> Map.put("object", object)
793 |> Map.merge(Utils.make_json_ld_header())
799 def prepare_outgoing(%{"type" => _type} = data) do
802 |> strip_internal_fields
803 |> maybe_fix_object_url
804 |> Map.merge(Utils.make_json_ld_header())
809 def maybe_fix_object_url(data) do
810 if is_binary(data["object"]) and not String.starts_with?(data["object"], "http") do
811 case fetch_obj_helper(data["object"]) do
812 {:ok, relative_object} ->
813 if relative_object.data["external_url"] do
816 |> Map.put("object", relative_object.data["external_url"])
822 Logger.error("Couldn't fetch #{data["object"]} #{inspect(e)}")
830 def add_hashtags(object) do
832 (object["tag"] || [])
834 # Expand internal representation tags into AS2 tags.
835 tag when is_binary(tag) ->
837 "href" => Pleroma.Web.Endpoint.url() <> "/tags/#{tag}",
842 # Do not process tags which are already AS2 tag objects.
843 tag when is_map(tag) ->
848 |> Map.put("tag", tags)
851 def add_mention_tags(object) do
854 |> Utils.get_notified_from_object()
855 |> Enum.map(fn user ->
856 %{"type" => "Mention", "href" => user.ap_id, "name" => "@#{user.nickname}"}
859 tags = object["tag"] || []
862 |> Map.put("tag", tags ++ mentions)
865 # TODO: we should probably send mtime instead of unix epoch time for updated
866 def add_emoji_tags(object) do
867 tags = object["tag"] || []
868 emoji = object["emoji"] || []
872 |> Enum.map(fn {name, url} ->
874 "icon" => %{"url" => url, "type" => "Image"},
875 "name" => ":" <> name <> ":",
877 "updated" => "1970-01-01T00:00:00Z",
883 |> Map.put("tag", tags ++ out)
886 def set_conversation(object) do
887 Map.put(object, "conversation", object["context"])
890 def set_sensitive(object) do
891 tags = object["tag"] || []
892 Map.put(object, "sensitive", "nsfw" in tags)
895 def add_attributed_to(object) do
896 attributed_to = object["attributedTo"] || object["actor"]
899 |> Map.put("attributedTo", attributed_to)
902 def add_likes(%{"id" => id, "like_count" => likes} = object) do
904 "id" => "#{id}/likes",
905 "first" => "#{id}/likes?page=1",
906 "type" => "OrderedCollection",
907 "totalItems" => likes
911 |> Map.put("likes", likes)
914 def add_likes(object) do
918 def prepare_attachments(object) do
920 (object["attachment"] || [])
921 |> Enum.map(fn data ->
922 [%{"mediaType" => media_type, "href" => href} | _] = data["url"]
923 %{"url" => href, "mediaType" => media_type, "name" => data["name"], "type" => "Document"}
927 |> Map.put("attachment", attachments)
930 defp strip_internal_fields(object) do
935 "announcement_count",
938 "deleted_activity_id"
942 defp strip_internal_tags(%{"tag" => tags} = object) do
945 |> Enum.filter(fn x -> is_map(x) end)
948 |> Map.put("tag", tags)
951 defp strip_internal_tags(object), do: object
953 defp user_upgrade_task(user) do
954 old_follower_address = User.ap_followers(user)
959 where: ^old_follower_address in u.following,
964 "array_replace(?,?,?)",
966 ^old_follower_address,
967 ^user.follower_address
973 Repo.update_all(q, [])
975 maybe_retire_websub(user.ap_id)
980 where: ^old_follower_address in a.recipients,
985 "array_replace(?,?,?)",
987 ^old_follower_address,
988 ^user.follower_address
994 Repo.update_all(q, [])
997 def upgrade_user_from_ap_id(ap_id, async \\ true) do
998 with %User{local: false} = user <- User.get_by_ap_id(ap_id),
999 {:ok, data} <- ActivityPub.fetch_and_prepare_user_from_ap_id(ap_id) do
1000 already_ap = User.ap_enabled?(user)
1003 User.upgrade_changeset(user, data)
1007 # This could potentially take a long time, do it in the background
1010 user_upgrade_task(user)
1013 user_upgrade_task(user)
1023 def maybe_retire_websub(ap_id) do
1024 # some sanity checks
1025 if is_binary(ap_id) && String.length(ap_id) > 8 do
1028 ws in Pleroma.Web.Websub.WebsubClientSubscription,
1029 where: fragment("? like ?", ws.topic, ^"#{ap_id}%")
1036 def maybe_fix_user_url(data) do
1037 if is_map(data["url"]) do
1038 Map.put(data, "url", data["url"]["href"])
1044 def maybe_fix_user_object(data) do
1046 |> maybe_fix_user_url