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
90 is_binary(map[field]) ->
91 Map.put(map, field, [map[field]])
94 Map.put(map, field, [])
101 def fix_explicit_addressing(%{"to" => to, "cc" => cc} = object, explicit_mentions) do
104 |> Enum.filter(fn x -> x in explicit_mentions end)
108 |> Enum.filter(fn x -> x not in explicit_mentions end)
115 |> Map.put("to", explicit_to)
116 |> Map.put("cc", final_cc)
119 def fix_explicit_addressing(object, _explicit_mentions), do: object
121 # if directMessage flag is set to true, leave the addressing alone
122 def fix_explicit_addressing(%{"directMessage" => true} = object), do: object
124 def fix_explicit_addressing(object) do
127 |> Utils.determine_explicit_mentions()
129 explicit_mentions = explicit_mentions ++ ["https://www.w3.org/ns/activitystreams#Public"]
132 |> fix_explicit_addressing(explicit_mentions)
135 # if as:Public is addressed, then make sure the followers collection is also addressed
136 # so that the activities will be delivered to local users.
137 def fix_implicit_addressing(%{"to" => to, "cc" => cc} = object, followers_collection) do
138 recipients = to ++ cc
140 if followers_collection not in recipients do
142 "https://www.w3.org/ns/activitystreams#Public" in cc ->
143 to = to ++ [followers_collection]
144 Map.put(object, "to", to)
146 "https://www.w3.org/ns/activitystreams#Public" in to ->
147 cc = cc ++ [followers_collection]
148 Map.put(object, "cc", cc)
158 def fix_implicit_addressing(object, _), do: object
160 def fix_addressing(object) do
161 %User{} = user = User.get_or_fetch_by_ap_id(object["actor"])
162 followers_collection = User.ap_followers(user)
165 |> fix_addressing_list("to")
166 |> fix_addressing_list("cc")
167 |> fix_addressing_list("bto")
168 |> fix_addressing_list("bcc")
169 |> fix_explicit_addressing
170 |> fix_implicit_addressing(followers_collection)
173 def fix_actor(%{"attributedTo" => actor} = object) do
175 |> Map.put("actor", get_actor(%{"actor" => actor}))
178 # Check for standardisation
179 # This is what Peertube does
180 # curl -H 'Accept: application/activity+json' $likes | jq .totalItems
181 # Prismo returns only an integer (count) as "likes"
182 def fix_likes(%{"likes" => likes} = object) when not is_map(likes) do
184 |> Map.put("likes", [])
185 |> Map.put("like_count", 0)
188 def fix_likes(object) do
192 def fix_in_reply_to(%{"inReplyTo" => in_reply_to} = object)
193 when not is_nil(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)
205 # Maybe I should output an error too?
210 case fetch_obj_helper(in_reply_to_id) do
211 {:ok, replied_object} ->
212 with %Activity{} = activity <-
213 Activity.get_create_by_object_ap_id(replied_object.data["id"]) do
215 |> Map.put("inReplyTo", replied_object.data["id"])
216 |> Map.put("inReplyToAtomUri", object["inReplyToAtomUri"] || in_reply_to_id)
217 |> Map.put("inReplyToStatusId", activity.id)
218 |> Map.put("conversation", replied_object.data["context"] || object["conversation"])
219 |> Map.put("context", replied_object.data["context"] || object["conversation"])
222 Logger.error("Couldn't fetch \"#{inspect(in_reply_to_id)}\", error: #{inspect(e)}")
227 Logger.error("Couldn't fetch \"#{inspect(in_reply_to_id)}\", error: #{inspect(e)}")
232 def fix_in_reply_to(object), do: object
234 def fix_context(object) do
235 context = object["context"] || object["conversation"] || Utils.generate_context_id()
238 |> Map.put("context", context)
239 |> Map.put("conversation", context)
242 def fix_attachments(%{"attachment" => attachment} = object) when is_list(attachment) do
245 |> Enum.map(fn data ->
246 media_type = data["mediaType"] || data["mimeType"]
247 href = data["url"] || data["href"]
249 url = [%{"type" => "Link", "mediaType" => media_type, "href" => href}]
252 |> Map.put("mediaType", media_type)
253 |> Map.put("url", url)
257 |> Map.put("attachment", attachments)
260 def fix_attachments(%{"attachment" => attachment} = object) when is_map(attachment) do
261 Map.put(object, "attachment", [attachment])
265 def fix_attachments(object), do: object
267 def fix_url(%{"url" => url} = object) when is_map(url) do
269 |> Map.put("url", url["href"])
272 def fix_url(%{"type" => "Video", "url" => url} = object) when is_list(url) do
273 first_element = Enum.at(url, 0)
277 |> Enum.filter(fn x -> is_map(x) end)
278 |> Enum.filter(fn x -> x["mimeType"] == "text/html" end)
282 |> Map.put("attachment", [first_element])
283 |> Map.put("url", link_element["href"])
286 def fix_url(%{"type" => object_type, "url" => url} = object)
287 when object_type != "Video" and is_list(url) do
288 first_element = Enum.at(url, 0)
292 is_bitstring(first_element) -> first_element
293 is_map(first_element) -> first_element["href"] || ""
298 |> Map.put("url", url_string)
301 def fix_url(object), do: object
303 def fix_emoji(%{"tag" => tags} = object) when is_list(tags) do
304 emoji = tags |> Enum.filter(fn data -> data["type"] == "Emoji" and data["icon"] end)
308 |> Enum.reduce(%{}, fn data, mapping ->
309 name = String.trim(data["name"], ":")
311 mapping |> Map.put(name, data["icon"]["url"])
314 # we merge mastodon and pleroma emoji into a single mapping, to allow for both wire formats
315 emoji = Map.merge(object["emoji"] || %{}, emoji)
318 |> Map.put("emoji", emoji)
321 def fix_emoji(%{"tag" => %{"type" => "Emoji"} = tag} = object) do
322 name = String.trim(tag["name"], ":")
323 emoji = %{name => tag["icon"]["url"]}
326 |> Map.put("emoji", emoji)
329 def fix_emoji(object), do: object
331 def fix_tag(%{"tag" => tag} = object) when is_list(tag) do
334 |> Enum.filter(fn data -> data["type"] == "Hashtag" and data["name"] end)
335 |> Enum.map(fn data -> String.slice(data["name"], 1..-1) end)
337 combined = tag ++ tags
340 |> Map.put("tag", combined)
343 def fix_tag(%{"tag" => %{"type" => "Hashtag", "name" => hashtag} = tag} = object) do
344 combined = [tag, String.slice(hashtag, 1..-1)]
347 |> Map.put("tag", combined)
350 def fix_tag(%{"tag" => %{} = tag} = object), do: Map.put(object, "tag", [tag])
352 def fix_tag(object), do: object
354 # content map usually only has one language so this will do for now.
355 def fix_content_map(%{"contentMap" => content_map} = object) do
356 content_groups = Map.to_list(content_map)
357 {_, content} = Enum.at(content_groups, 0)
360 |> Map.put("content", content)
363 def fix_content_map(object), do: object
365 defp mastodon_follow_hack(%{"id" => id, "actor" => follower_id}, followed) do
366 with true <- id =~ "follows",
367 %User{local: true} = follower <- User.get_cached_by_ap_id(follower_id),
368 %Activity{} = activity <- Utils.fetch_latest_follow(follower, followed) do
375 defp mastodon_follow_hack(_, _), do: {:error, nil}
377 defp get_follow_activity(follow_object, followed) do
378 with object_id when not is_nil(object_id) <- Utils.get_ap_id(follow_object),
379 {_, %Activity{} = activity} <- {:activity, Activity.get_by_ap_id(object_id)} do
382 # Can't find the activity. This might a Mastodon 2.3 "Accept"
384 mastodon_follow_hack(follow_object, followed)
391 # Flag objects are placed ahead of the ID check because Mastodon 2.8 and earlier send them
393 def handle_incoming(%{"type" => "Flag", "object" => objects, "actor" => actor} = data) do
394 with context <- data["context"] || Utils.generate_context_id(),
395 content <- data["content"] || "",
396 %User{} = actor <- User.get_cached_by_ap_id(actor),
398 # Reduce the object list to find the reported user.
400 Enum.reduce_while(objects, nil, fn ap_id, _ ->
401 with %User{} = user <- User.get_cached_by_ap_id(ap_id) do
408 # Remove the reported user from the object list.
409 statuses <- Enum.filter(objects, fn ap_id -> ap_id != account.ap_id end) do
417 "cc" => [account.ap_id]
421 ActivityPub.flag(params)
425 # disallow objects with bogus IDs
426 def handle_incoming(%{"id" => nil}), do: :error
427 def handle_incoming(%{"id" => ""}), do: :error
428 # length of https:// = 8, should validate better, but good enough for now.
429 def handle_incoming(%{"id" => id}) when not (is_binary(id) and length(id) > 8), do: :error
431 # TODO: validate those with a Ecto scheme
434 def handle_incoming(%{"type" => "Create", "object" => %{"type" => objtype} = object} = data)
435 when objtype in ["Article", "Note", "Video", "Page"] do
436 actor = get_actor(data)
439 Map.put(data, "actor", actor)
442 with nil <- Activity.get_create_by_object_ap_id(object["id"]),
443 %User{} = user <- User.get_or_fetch_by_ap_id(data["actor"]) do
444 object = fix_object(data["object"])
450 context: object["conversation"],
452 published: data["published"],
461 ActivityPub.create(params)
463 %Activity{} = activity -> {:ok, activity}
469 %{"type" => "Follow", "object" => followed, "actor" => follower, "id" => id} = data
471 with %User{local: true} = followed <- User.get_cached_by_ap_id(followed),
472 %User{} = follower <- User.get_or_fetch_by_ap_id(follower),
473 {:ok, activity} <- ActivityPub.follow(follower, followed, id, false) do
474 if not User.locked?(followed) do
475 ActivityPub.accept(%{
476 to: [follower.ap_id],
482 User.follow(follower, followed)
492 %{"type" => "Accept", "object" => follow_object, "actor" => _actor, "id" => _id} = data
494 with actor <- get_actor(data),
495 %User{} = followed <- User.get_or_fetch_by_ap_id(actor),
496 {:ok, follow_activity} <- get_follow_activity(follow_object, followed),
497 {:ok, follow_activity} <- Utils.update_follow_state(follow_activity, "accept"),
498 %User{local: true} = follower <- User.get_cached_by_ap_id(follow_activity.data["actor"]),
500 ActivityPub.accept(%{
501 to: follow_activity.data["to"],
504 object: follow_activity.data["id"],
507 if not User.following?(follower, followed) do
508 {:ok, _follower} = User.follow(follower, followed)
518 %{"type" => "Reject", "object" => follow_object, "actor" => _actor, "id" => _id} = data
520 with actor <- get_actor(data),
521 %User{} = followed <- User.get_or_fetch_by_ap_id(actor),
522 {:ok, follow_activity} <- get_follow_activity(follow_object, followed),
523 {:ok, follow_activity} <- Utils.update_follow_state(follow_activity, "reject"),
524 %User{local: true} = follower <- User.get_cached_by_ap_id(follow_activity.data["actor"]),
526 ActivityPub.reject(%{
527 to: follow_activity.data["to"],
530 object: follow_activity.data["id"],
533 User.unfollow(follower, followed)
542 %{"type" => "Like", "object" => object_id, "actor" => _actor, "id" => id} = data
544 with actor <- get_actor(data),
545 %User{} = actor <- User.get_or_fetch_by_ap_id(actor),
546 {:ok, object} <- get_obj_helper(object_id) || fetch_obj_helper(object_id),
547 {:ok, activity, _object} <- ActivityPub.like(actor, object, id, false) do
555 %{"type" => "Announce", "object" => object_id, "actor" => _actor, "id" => id} = data
557 with actor <- get_actor(data),
558 %User{} = actor <- User.get_or_fetch_by_ap_id(actor),
559 {:ok, object} <- get_obj_helper(object_id) || fetch_obj_helper(object_id),
560 public <- Visibility.is_public?(data),
561 {:ok, activity, _object} <- ActivityPub.announce(actor, object, id, false, public) do
569 %{"type" => "Update", "object" => %{"type" => object_type} = object, "actor" => actor_id} =
572 when object_type in ["Person", "Application", "Service", "Organization"] do
573 with %User{ap_id: ^actor_id} = actor <- User.get_by_ap_id(object["id"]) do
574 {:ok, new_user_data} = ActivityPub.user_data_from_user_object(object)
576 banner = new_user_data[:info]["banner"]
577 locked = new_user_data[:info]["locked"] || false
581 |> Map.take([:name, :bio, :avatar])
582 |> Map.put(:info, %{"banner" => banner, "locked" => locked})
585 |> User.upgrade_changeset(update_data)
586 |> User.update_and_set_cache()
588 ActivityPub.update(%{
590 to: data["to"] || [],
591 cc: data["cc"] || [],
602 # TODO: We presently assume that any actor on the same origin domain as the object being
603 # deleted has the rights to delete that object. A better way to validate whether or not
604 # the object should be deleted is to refetch the object URI, which should return either
605 # an error or a tombstone. This would allow us to verify that a deletion actually took
608 %{"type" => "Delete", "object" => object_id, "actor" => _actor, "id" => _id} = data
610 object_id = Utils.get_ap_id(object_id)
612 with actor <- get_actor(data),
613 %User{} = actor <- User.get_or_fetch_by_ap_id(actor),
614 {:ok, object} <- get_obj_helper(object_id) || fetch_obj_helper(object_id),
615 :ok <- contain_origin(actor.ap_id, object.data),
616 {:ok, activity} <- ActivityPub.delete(object, false) do
626 "object" => %{"type" => "Announce", "object" => object_id},
631 with actor <- get_actor(data),
632 %User{} = actor <- User.get_or_fetch_by_ap_id(actor),
633 {:ok, object} <- get_obj_helper(object_id) || fetch_obj_helper(object_id),
634 {:ok, activity, _} <- ActivityPub.unannounce(actor, object, id, false) do
644 "object" => %{"type" => "Follow", "object" => followed},
649 with %User{local: true} = followed <- User.get_cached_by_ap_id(followed),
650 %User{} = follower <- User.get_or_fetch_by_ap_id(follower),
651 {:ok, activity} <- ActivityPub.unfollow(follower, followed, id, false) do
652 User.unfollow(follower, followed)
662 "object" => %{"type" => "Block", "object" => blocked},
667 with true <- Pleroma.Config.get([:activitypub, :accept_blocks]),
668 %User{local: true} = blocked <- User.get_cached_by_ap_id(blocked),
669 %User{} = blocker <- User.get_or_fetch_by_ap_id(blocker),
670 {:ok, activity} <- ActivityPub.unblock(blocker, blocked, id, false) do
671 User.unblock(blocker, blocked)
679 %{"type" => "Block", "object" => blocked, "actor" => blocker, "id" => id} = _data
681 with true <- Pleroma.Config.get([:activitypub, :accept_blocks]),
682 %User{local: true} = blocked = User.get_cached_by_ap_id(blocked),
683 %User{} = blocker = User.get_or_fetch_by_ap_id(blocker),
684 {:ok, activity} <- ActivityPub.block(blocker, blocked, id, false) do
685 User.unfollow(blocker, blocked)
686 User.block(blocker, blocked)
696 "object" => %{"type" => "Like", "object" => object_id},
701 with actor <- get_actor(data),
702 %User{} = actor <- User.get_or_fetch_by_ap_id(actor),
703 {:ok, object} <- get_obj_helper(object_id) || fetch_obj_helper(object_id),
704 {:ok, activity, _, _} <- ActivityPub.unlike(actor, object, id, false) do
711 def handle_incoming(_), do: :error
713 def fetch_obj_helper(id) when is_bitstring(id), do: ActivityPub.fetch_object_from_id(id)
714 def fetch_obj_helper(obj) when is_map(obj), do: ActivityPub.fetch_object_from_id(obj["id"])
716 def get_obj_helper(id) do
717 if object = Object.normalize(id), do: {:ok, object}, else: nil
720 def set_reply_to_uri(%{"inReplyTo" => in_reply_to} = object) when is_binary(in_reply_to) do
721 with false <- String.starts_with?(in_reply_to, "http"),
722 {:ok, %{data: replied_to_object}} <- get_obj_helper(in_reply_to) do
723 Map.put(object, "inReplyTo", replied_to_object["external_url"] || in_reply_to)
729 def set_reply_to_uri(obj), do: obj
731 # Prepares the object of an outgoing create activity.
732 def prepare_object(object) do
740 |> prepare_attachments
743 |> strip_internal_fields
744 |> strip_internal_tags
749 # internal -> Mastodon
752 def prepare_outgoing(%{"type" => "Create", "object" => object} = data) do
759 |> Map.put("object", object)
760 |> Map.merge(Utils.make_json_ld_header())
765 # Mastodon Accept/Reject requires a non-normalized object containing the actor URIs,
766 # because of course it does.
767 def prepare_outgoing(%{"type" => "Accept"} = data) do
768 with follow_activity <- Activity.normalize(data["object"]) do
770 "actor" => follow_activity.actor,
771 "object" => follow_activity.data["object"],
772 "id" => follow_activity.data["id"],
778 |> Map.put("object", object)
779 |> Map.merge(Utils.make_json_ld_header())
785 def prepare_outgoing(%{"type" => "Reject"} = data) do
786 with follow_activity <- Activity.normalize(data["object"]) do
788 "actor" => follow_activity.actor,
789 "object" => follow_activity.data["object"],
790 "id" => follow_activity.data["id"],
796 |> Map.put("object", object)
797 |> Map.merge(Utils.make_json_ld_header())
803 def prepare_outgoing(%{"type" => _type} = data) do
806 |> strip_internal_fields
807 |> maybe_fix_object_url
808 |> Map.merge(Utils.make_json_ld_header())
813 def maybe_fix_object_url(data) do
814 if is_binary(data["object"]) and not String.starts_with?(data["object"], "http") do
815 case fetch_obj_helper(data["object"]) do
816 {:ok, relative_object} ->
817 if relative_object.data["external_url"] do
820 |> Map.put("object", relative_object.data["external_url"])
826 Logger.error("Couldn't fetch #{data["object"]} #{inspect(e)}")
834 def add_hashtags(object) do
836 (object["tag"] || [])
838 # Expand internal representation tags into AS2 tags.
839 tag when is_binary(tag) ->
841 "href" => Pleroma.Web.Endpoint.url() <> "/tags/#{tag}",
846 # Do not process tags which are already AS2 tag objects.
847 tag when is_map(tag) ->
852 |> Map.put("tag", tags)
855 def add_mention_tags(object) do
858 |> Utils.get_notified_from_object()
859 |> Enum.map(fn user ->
860 %{"type" => "Mention", "href" => user.ap_id, "name" => "@#{user.nickname}"}
863 tags = object["tag"] || []
866 |> Map.put("tag", tags ++ mentions)
869 # TODO: we should probably send mtime instead of unix epoch time for updated
870 def add_emoji_tags(object) do
871 tags = object["tag"] || []
872 emoji = object["emoji"] || []
876 |> Enum.map(fn {name, url} ->
878 "icon" => %{"url" => url, "type" => "Image"},
879 "name" => ":" <> name <> ":",
881 "updated" => "1970-01-01T00:00:00Z",
887 |> Map.put("tag", tags ++ out)
890 def set_conversation(object) do
891 Map.put(object, "conversation", object["context"])
894 def set_sensitive(object) do
895 tags = object["tag"] || []
896 Map.put(object, "sensitive", "nsfw" in tags)
899 def add_attributed_to(object) do
900 attributed_to = object["attributedTo"] || object["actor"]
903 |> Map.put("attributedTo", attributed_to)
906 def add_likes(%{"id" => id, "like_count" => likes} = object) do
908 "id" => "#{id}/likes",
909 "first" => "#{id}/likes?page=1",
910 "type" => "OrderedCollection",
911 "totalItems" => likes
915 |> Map.put("likes", likes)
918 def add_likes(object) do
922 def prepare_attachments(object) do
924 (object["attachment"] || [])
925 |> Enum.map(fn data ->
926 [%{"mediaType" => media_type, "href" => href} | _] = data["url"]
927 %{"url" => href, "mediaType" => media_type, "name" => data["name"], "type" => "Document"}
931 |> Map.put("attachment", attachments)
934 defp strip_internal_fields(object) do
939 "announcement_count",
942 "deleted_activity_id"
946 defp strip_internal_tags(%{"tag" => tags} = object) do
949 |> Enum.filter(fn x -> is_map(x) end)
952 |> Map.put("tag", tags)
955 defp strip_internal_tags(object), do: object
957 defp user_upgrade_task(user) do
958 # we pass a fake user so that the followers collection is stripped away
959 old_follower_address = User.ap_followers(%User{nickname: user.nickname})
964 where: ^old_follower_address in u.following,
969 "array_replace(?,?,?)",
971 ^old_follower_address,
972 ^user.follower_address
978 Repo.update_all(q, [])
980 maybe_retire_websub(user.ap_id)
985 where: ^old_follower_address in a.recipients,
990 "array_replace(?,?,?)",
992 ^old_follower_address,
993 ^user.follower_address
999 Repo.update_all(q, [])
1002 def upgrade_user_from_ap_id(ap_id, async \\ true) do
1003 with %User{local: false} = user <- User.get_by_ap_id(ap_id),
1004 {:ok, data} <- ActivityPub.fetch_and_prepare_user_from_ap_id(ap_id) do
1005 already_ap = User.ap_enabled?(user)
1008 User.upgrade_changeset(user, data)
1012 # This could potentially take a long time, do it in the background
1015 user_upgrade_task(user)
1018 user_upgrade_task(user)
1028 def maybe_retire_websub(ap_id) do
1029 # some sanity checks
1030 if is_binary(ap_id) && String.length(ap_id) > 8 do
1033 ws in Pleroma.Web.Websub.WebsubClientSubscription,
1034 where: fragment("? like ?", ws.topic, ^"#{ap_id}%")
1041 def maybe_fix_user_url(data) do
1042 if is_map(data["url"]) do
1043 Map.put(data, "url", data["url"]["href"])
1049 def maybe_fix_user_object(data) do
1051 |> maybe_fix_user_url