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.
11 alias Pleroma.Activity
13 alias Pleroma.Web.ActivityPub.ActivityPub
14 alias Pleroma.Web.ActivityPub.Utils
20 def get_actor(%{"actor" => actor}) when is_binary(actor) do
24 def get_actor(%{"actor" => actor}) when is_list(actor) do
25 if is_binary(Enum.at(actor, 0)) do
28 Enum.find(actor, fn %{"type" => type} -> type in ["Person", "Service", "Application"] end)
33 def get_actor(%{"actor" => %{"id" => id}}) when is_bitstring(id) do
37 def get_actor(%{"actor" => nil, "attributedTo" => actor}) when not is_nil(actor) do
38 get_actor(%{"actor" => actor})
42 Checks that an imported AP object's actor matches the domain it came from.
44 def contain_origin(_id, %{"actor" => nil}), do: :error
46 def contain_origin(id, %{"actor" => _actor} = params) do
47 id_uri = URI.parse(id)
48 actor_uri = URI.parse(get_actor(params))
50 if id_uri.host == actor_uri.host do
57 def contain_origin_from_id(_id, %{"id" => nil}), do: :error
59 def contain_origin_from_id(id, %{"id" => other_id} = _params) do
60 id_uri = URI.parse(id)
61 other_uri = URI.parse(other_id)
63 if id_uri.host == other_uri.host do
71 Modifies an incoming AP object (mastodon format) to our internal format.
73 def fix_object(object) do
87 def fix_addressing_list(map, field) do
88 if is_binary(map[field]) do
90 |> Map.put(field, [map[field]])
96 def fix_explicit_addressing(%{"to" => to, "cc" => cc} = object, explicit_mentions) do
99 |> Enum.filter(fn x -> x in explicit_mentions end)
103 |> Enum.filter(fn x -> x not in explicit_mentions end)
110 |> Map.put("to", explicit_to)
111 |> Map.put("cc", final_cc)
114 def fix_explicit_addressing(object, _explicit_mentions), do: object
116 # if directMessage flag is set to true, leave the addressing alone
117 def fix_explicit_addressing(%{"directMessage" => true} = object), do: object
119 def fix_explicit_addressing(object) do
122 |> Utils.determine_explicit_mentions()
124 explicit_mentions = explicit_mentions ++ ["https://www.w3.org/ns/activitystreams#Public"]
127 |> fix_explicit_addressing(explicit_mentions)
130 def fix_addressing(object) do
132 |> fix_addressing_list("to")
133 |> fix_addressing_list("cc")
134 |> fix_addressing_list("bto")
135 |> fix_addressing_list("bcc")
136 |> fix_explicit_addressing
139 def fix_actor(%{"attributedTo" => actor} = object) do
141 |> Map.put("actor", get_actor(%{"actor" => actor}))
144 def fix_likes(%{"likes" => likes} = object)
145 when is_bitstring(likes) do
146 # Check for standardisation
147 # This is what Peertube does
148 # curl -H 'Accept: application/activity+json' $likes | jq .totalItems
150 |> Map.put("likes", [])
151 |> Map.put("like_count", 0)
154 def fix_likes(object) do
158 def fix_in_reply_to(%{"inReplyTo" => in_reply_to} = object)
159 when not is_nil(in_reply_to) do
162 is_bitstring(in_reply_to) ->
165 is_map(in_reply_to) && is_bitstring(in_reply_to["id"]) ->
168 is_list(in_reply_to) && is_bitstring(Enum.at(in_reply_to, 0)) ->
169 Enum.at(in_reply_to, 0)
171 # Maybe I should output an error too?
176 case fetch_obj_helper(in_reply_to_id) do
177 {:ok, replied_object} ->
178 with %Activity{} = activity <-
179 Activity.get_create_by_object_ap_id(replied_object.data["id"]) do
181 |> Map.put("inReplyTo", replied_object.data["id"])
182 |> Map.put("inReplyToAtomUri", object["inReplyToAtomUri"] || in_reply_to_id)
183 |> Map.put("inReplyToStatusId", activity.id)
184 |> Map.put("conversation", replied_object.data["context"] || object["conversation"])
185 |> Map.put("context", replied_object.data["context"] || object["conversation"])
188 Logger.error("Couldn't fetch \"#{inspect(in_reply_to_id)}\", error: #{inspect(e)}")
193 Logger.error("Couldn't fetch \"#{inspect(in_reply_to_id)}\", error: #{inspect(e)}")
198 def fix_in_reply_to(object), do: object
200 def fix_context(object) do
201 context = object["context"] || object["conversation"] || Utils.generate_context_id()
204 |> Map.put("context", context)
205 |> Map.put("conversation", context)
208 def fix_attachments(%{"attachment" => attachment} = object) when is_list(attachment) do
211 |> Enum.map(fn data ->
212 media_type = data["mediaType"] || data["mimeType"]
213 href = data["url"] || data["href"]
215 url = [%{"type" => "Link", "mediaType" => media_type, "href" => href}]
218 |> Map.put("mediaType", media_type)
219 |> Map.put("url", url)
223 |> Map.put("attachment", attachments)
226 def fix_attachments(%{"attachment" => attachment} = object) when is_map(attachment) do
227 Map.put(object, "attachment", [attachment])
231 def fix_attachments(object), do: object
233 def fix_url(%{"url" => url} = object) when is_map(url) do
235 |> Map.put("url", url["href"])
238 def fix_url(%{"type" => "Video", "url" => url} = object) when is_list(url) do
239 first_element = Enum.at(url, 0)
243 |> Enum.filter(fn x -> is_map(x) end)
244 |> Enum.filter(fn x -> x["mimeType"] == "text/html" end)
248 |> Map.put("attachment", [first_element])
249 |> Map.put("url", link_element["href"])
252 def fix_url(%{"type" => object_type, "url" => url} = object)
253 when object_type != "Video" and is_list(url) do
254 first_element = Enum.at(url, 0)
258 is_bitstring(first_element) -> first_element
259 is_map(first_element) -> first_element["href"] || ""
264 |> Map.put("url", url_string)
267 def fix_url(object), do: object
269 def fix_emoji(%{"tag" => tags} = object) when is_list(tags) do
270 emoji = tags |> Enum.filter(fn data -> data["type"] == "Emoji" and data["icon"] end)
274 |> Enum.reduce(%{}, fn data, mapping ->
275 name = String.trim(data["name"], ":")
277 mapping |> Map.put(name, data["icon"]["url"])
280 # we merge mastodon and pleroma emoji into a single mapping, to allow for both wire formats
281 emoji = Map.merge(object["emoji"] || %{}, emoji)
284 |> Map.put("emoji", emoji)
287 def fix_emoji(%{"tag" => %{"type" => "Emoji"} = tag} = object) do
288 name = String.trim(tag["name"], ":")
289 emoji = %{name => tag["icon"]["url"]}
292 |> Map.put("emoji", emoji)
295 def fix_emoji(object), do: object
297 def fix_tag(%{"tag" => tag} = object) when is_list(tag) do
300 |> Enum.filter(fn data -> data["type"] == "Hashtag" and data["name"] end)
301 |> Enum.map(fn data -> String.slice(data["name"], 1..-1) end)
303 combined = tag ++ tags
306 |> Map.put("tag", combined)
309 def fix_tag(%{"tag" => %{"type" => "Hashtag", "name" => hashtag} = tag} = object) do
310 combined = [tag, String.slice(hashtag, 1..-1)]
313 |> Map.put("tag", combined)
316 def fix_tag(object), do: object
318 # content map usually only has one language so this will do for now.
319 def fix_content_map(%{"contentMap" => content_map} = object) do
320 content_groups = Map.to_list(content_map)
321 {_, content} = Enum.at(content_groups, 0)
324 |> Map.put("content", content)
327 def fix_content_map(object), do: object
329 defp mastodon_follow_hack(%{"id" => id, "actor" => follower_id}, followed) do
330 with true <- id =~ "follows",
331 %User{local: true} = follower <- User.get_cached_by_ap_id(follower_id),
332 %Activity{} = activity <- Utils.fetch_latest_follow(follower, followed) do
339 defp mastodon_follow_hack(_, _), do: {:error, nil}
341 defp get_follow_activity(follow_object, followed) do
342 with object_id when not is_nil(object_id) <- Utils.get_ap_id(follow_object),
343 {_, %Activity{} = activity} <- {:activity, Activity.get_by_ap_id(object_id)} do
346 # Can't find the activity. This might a Mastodon 2.3 "Accept"
348 mastodon_follow_hack(follow_object, followed)
355 # disallow objects with bogus IDs
356 def handle_incoming(%{"id" => nil}), do: :error
357 def handle_incoming(%{"id" => ""}), do: :error
358 # length of https:// = 8, should validate better, but good enough for now.
359 def handle_incoming(%{"id" => id}) when not (is_binary(id) and length(id) > 8), do: :error
361 # TODO: validate those with a Ecto scheme
364 def handle_incoming(%{"type" => "Create", "object" => %{"type" => objtype} = object} = data)
365 when objtype in ["Article", "Note", "Video", "Page"] do
366 actor = get_actor(data)
369 Map.put(data, "actor", actor)
372 with nil <- Activity.get_create_by_object_ap_id(object["id"]),
373 %User{} = user <- User.get_or_fetch_by_ap_id(data["actor"]) do
374 object = fix_object(data["object"])
380 context: object["conversation"],
382 published: data["published"],
391 ActivityPub.create(params)
393 %Activity{} = activity -> {:ok, activity}
399 %{"type" => "Follow", "object" => followed, "actor" => follower, "id" => id} = data
401 with %User{local: true} = followed <- User.get_cached_by_ap_id(followed),
402 %User{} = follower <- User.get_or_fetch_by_ap_id(follower),
403 {:ok, activity} <- ActivityPub.follow(follower, followed, id, false) do
404 if not User.locked?(followed) do
405 ActivityPub.accept(%{
406 to: [follower.ap_id],
407 actor: followed.ap_id,
412 User.follow(follower, followed)
422 %{"type" => "Accept", "object" => follow_object, "actor" => _actor, "id" => _id} = data
424 with actor <- get_actor(data),
425 %User{} = followed <- User.get_or_fetch_by_ap_id(actor),
426 {:ok, follow_activity} <- get_follow_activity(follow_object, followed),
427 {:ok, follow_activity} <- Utils.update_follow_state(follow_activity, "accept"),
428 %User{local: true} = follower <- User.get_cached_by_ap_id(follow_activity.data["actor"]),
430 ActivityPub.accept(%{
431 to: follow_activity.data["to"],
433 actor: followed.ap_id,
434 object: follow_activity.data["id"],
437 if not User.following?(follower, followed) do
438 {:ok, _follower} = User.follow(follower, followed)
448 %{"type" => "Reject", "object" => follow_object, "actor" => _actor, "id" => _id} = data
450 with actor <- get_actor(data),
451 %User{} = followed <- User.get_or_fetch_by_ap_id(actor),
452 {:ok, follow_activity} <- get_follow_activity(follow_object, followed),
453 {:ok, follow_activity} <- Utils.update_follow_state(follow_activity, "reject"),
454 %User{local: true} = follower <- User.get_cached_by_ap_id(follow_activity.data["actor"]),
456 ActivityPub.accept(%{
457 to: follow_activity.data["to"],
459 actor: followed.ap_id,
460 object: follow_activity.data["id"],
463 User.unfollow(follower, followed)
472 %{"type" => "Like", "object" => object_id, "actor" => _actor, "id" => id} = data
474 with actor <- get_actor(data),
475 %User{} = actor <- User.get_or_fetch_by_ap_id(actor),
476 {:ok, object} <- get_obj_helper(object_id) || fetch_obj_helper(object_id),
477 {:ok, activity, _object} <- ActivityPub.like(actor, object, id, false) do
485 %{"type" => "Announce", "object" => object_id, "actor" => _actor, "id" => id} = data
487 with actor <- get_actor(data),
488 %User{} = actor <- User.get_or_fetch_by_ap_id(actor),
489 {:ok, object} <- get_obj_helper(object_id) || fetch_obj_helper(object_id),
490 public <- ActivityPub.is_public?(data),
491 {:ok, activity, _object} <- ActivityPub.announce(actor, object, id, false, public) do
499 %{"type" => "Update", "object" => %{"type" => object_type} = object, "actor" => actor_id} =
502 when object_type in ["Person", "Application", "Service", "Organization"] do
503 with %User{ap_id: ^actor_id} = actor <- User.get_by_ap_id(object["id"]) do
504 {:ok, new_user_data} = ActivityPub.user_data_from_user_object(object)
506 banner = new_user_data[:info]["banner"]
507 locked = new_user_data[:info]["locked"] || false
511 |> Map.take([:name, :bio, :avatar])
512 |> Map.put(:info, %{"banner" => banner, "locked" => locked})
515 |> User.upgrade_changeset(update_data)
516 |> User.update_and_set_cache()
518 ActivityPub.update(%{
520 to: data["to"] || [],
521 cc: data["cc"] || [],
532 # TODO: We presently assume that any actor on the same origin domain as the object being
533 # deleted has the rights to delete that object. A better way to validate whether or not
534 # the object should be deleted is to refetch the object URI, which should return either
535 # an error or a tombstone. This would allow us to verify that a deletion actually took
538 %{"type" => "Delete", "object" => object_id, "actor" => _actor, "id" => _id} = data
540 object_id = Utils.get_ap_id(object_id)
542 with actor <- get_actor(data),
543 %User{} = actor <- User.get_or_fetch_by_ap_id(actor),
544 {:ok, object} <- get_obj_helper(object_id) || fetch_obj_helper(object_id),
545 :ok <- contain_origin(actor.ap_id, object.data),
546 {:ok, activity} <- ActivityPub.delete(object, false) do
556 "object" => %{"type" => "Announce", "object" => object_id},
561 with actor <- get_actor(data),
562 %User{} = actor <- User.get_or_fetch_by_ap_id(actor),
563 {:ok, object} <- get_obj_helper(object_id) || fetch_obj_helper(object_id),
564 {:ok, activity, _} <- ActivityPub.unannounce(actor, object, id, false) do
574 "object" => %{"type" => "Follow", "object" => followed},
579 with %User{local: true} = followed <- User.get_cached_by_ap_id(followed),
580 %User{} = follower <- User.get_or_fetch_by_ap_id(follower),
581 {:ok, activity} <- ActivityPub.unfollow(follower, followed, id, false) do
582 User.unfollow(follower, followed)
592 "object" => %{"type" => "Block", "object" => blocked},
597 with true <- Pleroma.Config.get([:activitypub, :accept_blocks]),
598 %User{local: true} = blocked <- User.get_cached_by_ap_id(blocked),
599 %User{} = blocker <- User.get_or_fetch_by_ap_id(blocker),
600 {:ok, activity} <- ActivityPub.unblock(blocker, blocked, id, false) do
601 User.unblock(blocker, blocked)
609 %{"type" => "Block", "object" => blocked, "actor" => blocker, "id" => id} = _data
611 with true <- Pleroma.Config.get([:activitypub, :accept_blocks]),
612 %User{local: true} = blocked = User.get_cached_by_ap_id(blocked),
613 %User{} = blocker = User.get_or_fetch_by_ap_id(blocker),
614 {:ok, activity} <- ActivityPub.block(blocker, blocked, id, false) do
615 User.unfollow(blocker, blocked)
616 User.block(blocker, blocked)
626 "object" => %{"type" => "Like", "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.unlike(actor, object, id, false) do
641 def handle_incoming(_), do: :error
643 def fetch_obj_helper(id) when is_bitstring(id), do: ActivityPub.fetch_object_from_id(id)
644 def fetch_obj_helper(obj) when is_map(obj), do: ActivityPub.fetch_object_from_id(obj["id"])
646 def get_obj_helper(id) do
647 if object = Object.normalize(id), do: {:ok, object}, else: nil
650 def set_reply_to_uri(%{"inReplyTo" => inReplyTo} = object) do
651 with false <- String.starts_with?(inReplyTo, "http"),
652 {:ok, %{data: replied_to_object}} <- get_obj_helper(inReplyTo) do
653 Map.put(object, "inReplyTo", replied_to_object["external_url"] || inReplyTo)
659 def set_reply_to_uri(obj), do: obj
661 # Prepares the object of an outgoing create activity.
662 def prepare_object(object) do
670 |> prepare_attachments
673 |> strip_internal_fields
674 |> strip_internal_tags
679 # internal -> Mastodon
682 def prepare_outgoing(%{"type" => "Create", "object" => object} = data) do
689 |> Map.put("object", object)
690 |> Map.merge(Utils.make_json_ld_header())
695 # Mastodon Accept/Reject requires a non-normalized object containing the actor URIs,
696 # because of course it does.
697 def prepare_outgoing(%{"type" => "Accept"} = data) do
698 with follow_activity <- Activity.normalize(data["object"]) do
700 "actor" => follow_activity.actor,
701 "object" => follow_activity.data["object"],
702 "id" => follow_activity.data["id"],
708 |> Map.put("object", object)
709 |> Map.merge(Utils.make_json_ld_header())
715 def prepare_outgoing(%{"type" => "Reject"} = data) do
716 with follow_activity <- Activity.normalize(data["object"]) do
718 "actor" => follow_activity.actor,
719 "object" => follow_activity.data["object"],
720 "id" => follow_activity.data["id"],
726 |> Map.put("object", object)
727 |> Map.merge(Utils.make_json_ld_header())
733 def prepare_outgoing(%{"type" => _type} = data) do
736 |> maybe_fix_object_url
737 |> Map.merge(Utils.make_json_ld_header())
742 def maybe_fix_object_url(data) do
743 if is_binary(data["object"]) and not String.starts_with?(data["object"], "http") do
744 case fetch_obj_helper(data["object"]) do
745 {:ok, relative_object} ->
746 if relative_object.data["external_url"] do
749 |> Map.put("object", relative_object.data["external_url"])
755 Logger.error("Couldn't fetch #{data["object"]} #{inspect(e)}")
763 def add_hashtags(object) do
765 (object["tag"] || [])
766 |> Enum.map(fn tag ->
768 "href" => Pleroma.Web.Endpoint.url() <> "/tags/#{tag}",
775 |> Map.put("tag", tags)
778 def add_mention_tags(object) do
781 |> Utils.get_notified_from_object()
782 |> Enum.map(fn user ->
783 %{"type" => "Mention", "href" => user.ap_id, "name" => "@#{user.nickname}"}
786 tags = object["tag"] || []
789 |> Map.put("tag", tags ++ mentions)
792 # TODO: we should probably send mtime instead of unix epoch time for updated
793 def add_emoji_tags(object) do
794 tags = object["tag"] || []
795 emoji = object["emoji"] || []
799 |> Enum.map(fn {name, url} ->
801 "icon" => %{"url" => url, "type" => "Image"},
802 "name" => ":" <> name <> ":",
804 "updated" => "1970-01-01T00:00:00Z",
810 |> Map.put("tag", tags ++ out)
813 def set_conversation(object) do
814 Map.put(object, "conversation", object["context"])
817 def set_sensitive(object) do
818 tags = object["tag"] || []
819 Map.put(object, "sensitive", "nsfw" in tags)
822 def add_attributed_to(object) do
823 attributedTo = object["attributedTo"] || object["actor"]
826 |> Map.put("attributedTo", attributedTo)
829 def add_likes(%{"id" => id, "like_count" => likes} = object) do
831 "id" => "#{id}/likes",
832 "first" => "#{id}/likes?page=1",
833 "type" => "OrderedCollection",
834 "totalItems" => likes
838 |> Map.put("likes", likes)
841 def add_likes(object) do
845 def prepare_attachments(object) do
847 (object["attachment"] || [])
848 |> Enum.map(fn data ->
849 [%{"mediaType" => media_type, "href" => href} | _] = data["url"]
850 %{"url" => href, "mediaType" => media_type, "name" => data["name"], "type" => "Document"}
854 |> Map.put("attachment", attachments)
857 defp strip_internal_fields(object) do
862 "announcement_count",
868 defp strip_internal_tags(%{"tag" => tags} = object) do
871 |> Enum.filter(fn x -> is_map(x) end)
874 |> Map.put("tag", tags)
877 defp strip_internal_tags(object), do: object
879 defp user_upgrade_task(user) do
880 old_follower_address = User.ap_followers(user)
885 where: ^old_follower_address in u.following,
890 "array_replace(?,?,?)",
892 ^old_follower_address,
893 ^user.follower_address
899 Repo.update_all(q, [])
901 maybe_retire_websub(user.ap_id)
906 where: ^old_follower_address in a.recipients,
911 "array_replace(?,?,?)",
913 ^old_follower_address,
914 ^user.follower_address
920 Repo.update_all(q, [])
923 def upgrade_user_from_ap_id(ap_id, async \\ true) do
924 with %User{local: false} = user <- User.get_by_ap_id(ap_id),
925 {:ok, data} <- ActivityPub.fetch_and_prepare_user_from_ap_id(ap_id) do
926 already_ap = User.ap_enabled?(user)
929 User.upgrade_changeset(user, data)
933 # This could potentially take a long time, do it in the background
936 user_upgrade_task(user)
939 user_upgrade_task(user)
949 def maybe_retire_websub(ap_id) do
951 if is_binary(ap_id) && String.length(ap_id) > 8 do
954 ws in Pleroma.Web.Websub.WebsubClientSubscription,
955 where: fragment("? like ?", ws.topic, ^"#{ap_id}%")
962 def maybe_fix_user_url(data) do
963 if is_map(data["url"]) do
964 Map.put(data, "url", data["url"]["href"])
970 def maybe_fix_user_object(data) do
972 |> maybe_fix_user_url