1 defmodule Pleroma.Web.ActivityPub.Transmogrifier do
3 A module to handle coding from internal to wire ActivityPub and back.
9 alias Pleroma.Web.ActivityPub.ActivityPub
10 alias Pleroma.Web.ActivityPub.Utils
16 def get_actor(%{"actor" => actor}) when is_binary(actor) do
20 def get_actor(%{"actor" => actor}) when is_list(actor) do
24 def get_actor(%{"actor" => actor_list}) do
25 Enum.find(actor_list, fn %{"type" => type} -> type == "Person" end)
30 Modifies an incoming AP object (mastodon format) to our internal format.
32 def fix_object(object) do
43 def fix_actor(%{"attributedTo" => actor} = object) do
45 |> Map.put("actor", get_actor(%{"actor" => actor}))
48 def fix_in_reply_to(%{"inReplyTo" => in_reply_to_id} = object)
49 when not is_nil(in_reply_to_id) do
50 case ActivityPub.fetch_object_from_id(in_reply_to_id) do
51 {:ok, replied_object} ->
52 with %Activity{} = activity <-
53 Activity.get_create_activity_by_object_ap_id(replied_object.data["id"]) do
55 |> Map.put("inReplyTo", replied_object.data["id"])
56 |> Map.put("inReplyToAtomUri", object["inReplyToAtomUri"] || in_reply_to_id)
57 |> Map.put("inReplyToStatusId", activity.id)
58 |> Map.put("conversation", replied_object.data["context"] || object["conversation"])
59 |> Map.put("context", replied_object.data["context"] || object["conversation"])
62 Logger.error("Couldn't fetch #{object["inReplyTo"]} #{inspect(e)}")
67 Logger.error("Couldn't fetch #{object["inReplyTo"]} #{inspect(e)}")
72 def fix_in_reply_to(object), do: object
74 def fix_context(object) do
76 |> Map.put("context", object["conversation"])
79 def fix_attachments(object) do
81 (object["attachment"] || [])
82 |> Enum.map(fn data ->
83 url = [%{"type" => "Link", "mediaType" => data["mediaType"], "href" => data["url"]}]
84 Map.put(data, "url", url)
88 |> Map.put("attachment", attachments)
91 def fix_emoji(object) do
92 tags = object["tag"] || []
93 emoji = tags |> Enum.filter(fn data -> data["type"] == "Emoji" and data["icon"] end)
97 |> Enum.reduce(%{}, fn data, mapping ->
101 if String.starts_with?(name, ":") do
102 name |> String.slice(1..-2)
107 mapping |> Map.put(name, data["icon"]["url"])
110 # we merge mastodon and pleroma emoji into a single mapping, to allow for both wire formats
111 emoji = Map.merge(object["emoji"] || %{}, emoji)
114 |> Map.put("emoji", emoji)
117 def fix_tag(object) do
119 (object["tag"] || [])
120 |> Enum.filter(fn data -> data["type"] == "Hashtag" and data["name"] end)
121 |> Enum.map(fn data -> String.slice(data["name"], 1..-1) end)
123 combined = (object["tag"] || []) ++ tags
126 |> Map.put("tag", combined)
129 # content map usually only has one language so this will do for now.
130 def fix_content_map(%{"contentMap" => content_map} = object) do
131 content_groups = Map.to_list(content_map)
132 {_, content} = Enum.at(content_groups, 0)
135 |> Map.put("content", content)
138 def fix_content_map(object), do: object
140 # TODO: validate those with a Ecto scheme
143 def handle_incoming(%{"type" => "Create", "object" => %{"type" => objtype} = object} = data)
144 when objtype in ["Article", "Note"] do
145 actor = get_actor(data)
146 data = Map.put(data, "actor", actor)
148 with nil <- Activity.get_create_activity_by_object_ap_id(object["id"]),
149 %User{} = user <- User.get_or_fetch_by_ap_id(data["actor"]) do
150 object = fix_object(data["object"])
156 context: object["conversation"],
158 published: data["published"],
166 ActivityPub.create(params)
168 %Activity{} = activity -> {:ok, activity}
174 %{"type" => "Follow", "object" => followed, "actor" => follower, "id" => id} = data
176 with %User{local: true} = followed <- User.get_cached_by_ap_id(followed),
177 %User{} = follower <- User.get_or_fetch_by_ap_id(follower),
178 {:ok, activity} <- ActivityPub.follow(follower, followed, id, false) do
179 if not User.locked?(followed) do
180 ActivityPub.accept(%{
181 to: [follower.ap_id],
182 actor: followed.ap_id,
187 User.follow(follower, followed)
196 defp mastodon_follow_hack(%{"id" => id, "actor" => follower_id}, followed) do
197 with true <- id =~ "follows",
198 %User{local: true} = follower <- User.get_cached_by_ap_id(follower_id),
199 %Activity{} = activity <- Utils.fetch_latest_follow(follower, followed) do
206 defp mastodon_follow_hack(_), do: {:error, nil}
208 defp get_follow_activity(follow_object, followed) do
209 with object_id when not is_nil(object_id) <- Utils.get_ap_id(follow_object),
210 {_, %Activity{} = activity} <- {:activity, Activity.get_by_ap_id(object_id)} do
213 # Can't find the activity. This might a Mastodon 2.3 "Accept"
215 mastodon_follow_hack(follow_object, followed)
223 %{"type" => "Accept", "object" => follow_object, "actor" => actor, "id" => id} = data
225 with %User{} = followed <- User.get_or_fetch_by_ap_id(actor),
226 {:ok, follow_activity} <- get_follow_activity(follow_object, followed),
227 %User{local: true} = follower <- User.get_cached_by_ap_id(follow_activity.data["actor"]),
229 ActivityPub.accept(%{
230 to: follow_activity.data["to"],
232 actor: followed.ap_id,
233 object: follow_activity.data["id"],
236 if not User.following?(follower, followed) do
237 {:ok, follower} = User.follow(follower, followed)
247 %{"type" => "Reject", "object" => follow_object, "actor" => actor, "id" => id} = data
249 with %User{} = followed <- User.get_or_fetch_by_ap_id(actor),
250 {:ok, follow_activity} <- get_follow_activity(follow_object, followed),
251 %User{local: true} = follower <- User.get_cached_by_ap_id(follow_activity.data["actor"]),
253 ActivityPub.accept(%{
254 to: follow_activity.data["to"],
256 actor: followed.ap_id,
257 object: follow_activity.data["id"],
260 User.unfollow(follower, followed)
269 %{"type" => "Like", "object" => object_id, "actor" => actor, "id" => id} = _data
271 with %User{} = actor <- User.get_or_fetch_by_ap_id(actor),
273 get_obj_helper(object_id) || ActivityPub.fetch_object_from_id(object_id),
274 {:ok, activity, _object} <- ActivityPub.like(actor, object, id, false) do
282 %{"type" => "Announce", "object" => object_id, "actor" => actor, "id" => id} = _data
284 with %User{} = actor <- User.get_or_fetch_by_ap_id(actor),
286 get_obj_helper(object_id) || ActivityPub.fetch_object_from_id(object_id),
287 {:ok, activity, _object} <- ActivityPub.announce(actor, object, id, false) do
295 %{"type" => "Update", "object" => %{"type" => "Person"} = object, "actor" => actor_id} =
298 with %User{ap_id: ^actor_id} = actor <- User.get_by_ap_id(object["id"]) do
299 {:ok, new_user_data} = ActivityPub.user_data_from_user_object(object)
301 banner = new_user_data[:info]["banner"]
302 locked = new_user_data[:info]["locked"] || false
306 |> Map.take([:name, :bio, :avatar])
307 |> Map.put(:info, Map.merge(actor.info, %{"banner" => banner, "locked" => locked}))
310 |> User.upgrade_changeset(update_data)
311 |> User.update_and_set_cache()
313 ActivityPub.update(%{
315 to: data["to"] || [],
316 cc: data["cc"] || [],
329 %{"type" => "Delete", "object" => object_id, "actor" => actor, "id" => _id} = _data
331 object_id = Utils.get_ap_id(object_id)
333 with %User{} = _actor <- User.get_or_fetch_by_ap_id(actor),
335 get_obj_helper(object_id) || ActivityPub.fetch_object_from_id(object_id),
336 {:ok, activity} <- ActivityPub.delete(object, false) do
346 "object" => %{"type" => "Announce", "object" => object_id},
351 with %User{} = actor <- User.get_or_fetch_by_ap_id(actor),
353 get_obj_helper(object_id) || ActivityPub.fetch_object_from_id(object_id),
354 {:ok, activity, _} <- ActivityPub.unannounce(actor, object, id, false) do
364 "object" => %{"type" => "Follow", "object" => followed},
369 with %User{local: true} = followed <- User.get_cached_by_ap_id(followed),
370 %User{} = follower <- User.get_or_fetch_by_ap_id(follower),
371 {:ok, activity} <- ActivityPub.unfollow(follower, followed, id, false) do
372 User.unfollow(follower, followed)
379 @ap_config Application.get_env(:pleroma, :activitypub)
380 @accept_blocks Keyword.get(@ap_config, :accept_blocks)
385 "object" => %{"type" => "Block", "object" => blocked},
390 with true <- @accept_blocks,
391 %User{local: true} = blocked <- User.get_cached_by_ap_id(blocked),
392 %User{} = blocker <- User.get_or_fetch_by_ap_id(blocker),
393 {:ok, activity} <- ActivityPub.unblock(blocker, blocked, id, false) do
394 User.unblock(blocker, blocked)
402 %{"type" => "Block", "object" => blocked, "actor" => blocker, "id" => id} = data
404 with true <- @accept_blocks,
405 %User{local: true} = blocked = User.get_cached_by_ap_id(blocked),
406 %User{} = blocker = User.get_or_fetch_by_ap_id(blocker),
407 {:ok, activity} <- ActivityPub.block(blocker, blocked, id, false) do
408 User.unfollow(blocker, blocked)
409 User.block(blocker, blocked)
419 "object" => %{"type" => "Like", "object" => object_id},
424 with %User{} = actor <- User.get_or_fetch_by_ap_id(actor),
426 get_obj_helper(object_id) || ActivityPub.fetch_object_from_id(object_id),
427 {:ok, activity, _, _} <- ActivityPub.unlike(actor, object, id, false) do
434 def handle_incoming(_), do: :error
436 def get_obj_helper(id) do
437 if object = Object.normalize(id), do: {:ok, object}, else: nil
440 def set_reply_to_uri(%{"inReplyTo" => inReplyTo} = object) do
441 with false <- String.starts_with?(inReplyTo, "http"),
442 {:ok, %{data: replied_to_object}} <- get_obj_helper(inReplyTo) do
443 Map.put(object, "inReplyTo", replied_to_object["external_url"] || inReplyTo)
449 def set_reply_to_uri(obj), do: obj
451 # Prepares the object of an outgoing create activity.
452 def prepare_object(object) do
459 |> prepare_attachments
466 # internal -> Mastodon
469 def prepare_outgoing(%{"type" => "Create", "object" => %{"type" => "Note"} = object} = data) do
476 |> Map.put("object", object)
477 |> Map.put("@context", "https://www.w3.org/ns/activitystreams")
482 # Mastodon Accept/Reject requires a non-normalized object containing the actor URIs,
483 # because of course it does.
484 def prepare_outgoing(%{"type" => "Accept"} = data) do
485 with follow_activity <- Activity.normalize(data["object"]) do
487 "actor" => follow_activity.actor,
488 "object" => follow_activity.data["object"],
489 "id" => follow_activity.data["id"],
495 |> Map.put("object", object)
496 |> Map.put("@context", "https://www.w3.org/ns/activitystreams")
502 def prepare_outgoing(%{"type" => "Reject"} = data) do
503 with follow_activity <- Activity.normalize(data["object"]) do
505 "actor" => follow_activity.actor,
506 "object" => follow_activity.data["object"],
507 "id" => follow_activity.data["id"],
513 |> Map.put("object", object)
514 |> Map.put("@context", "https://www.w3.org/ns/activitystreams")
520 def prepare_outgoing(%{"type" => _type} = data) do
523 |> maybe_fix_object_url
524 |> Map.put("@context", "https://www.w3.org/ns/activitystreams")
529 def maybe_fix_object_url(data) do
530 if is_binary(data["object"]) and not String.starts_with?(data["object"], "http") do
531 case ActivityPub.fetch_object_from_id(data["object"]) do
532 {:ok, relative_object} ->
533 if relative_object.data["external_url"] do
536 |> Map.put("object", relative_object.data["external_url"])
542 Logger.error("Couldn't fetch #{data["object"]} #{inspect(e)}")
550 def add_hashtags(object) do
552 (object["tag"] || [])
553 |> Enum.map(fn tag ->
555 "href" => Pleroma.Web.Endpoint.url() <> "/tags/#{tag}",
562 |> Map.put("tag", tags)
565 def add_mention_tags(object) do
566 recipients = object["to"] ++ (object["cc"] || [])
570 |> Enum.map(fn ap_id -> User.get_cached_by_ap_id(ap_id) end)
572 |> Enum.map(fn user ->
573 %{"type" => "Mention", "href" => user.ap_id, "name" => "@#{user.nickname}"}
576 tags = object["tag"] || []
579 |> Map.put("tag", tags ++ mentions)
582 # TODO: we should probably send mtime instead of unix epoch time for updated
583 def add_emoji_tags(object) do
584 tags = object["tag"] || []
585 emoji = object["emoji"] || []
589 |> Enum.map(fn {name, url} ->
591 "icon" => %{"url" => url, "type" => "Image"},
592 "name" => ":" <> name <> ":",
594 "updated" => "1970-01-01T00:00:00Z",
600 |> Map.put("tag", tags ++ out)
603 def set_conversation(object) do
604 Map.put(object, "conversation", object["context"])
607 def set_sensitive(object) do
608 tags = object["tag"] || []
609 Map.put(object, "sensitive", "nsfw" in tags)
612 def add_attributed_to(object) do
613 attributedTo = object["attributedTo"] || object["actor"]
616 |> Map.put("attributedTo", attributedTo)
619 def prepare_attachments(object) do
621 (object["attachment"] || [])
622 |> Enum.map(fn data ->
623 [%{"mediaType" => media_type, "href" => href} | _] = data["url"]
624 %{"url" => href, "mediaType" => media_type, "name" => data["name"], "type" => "Document"}
628 |> Map.put("attachment", attachments)
631 defp user_upgrade_task(user) do
632 old_follower_address = User.ap_followers(user)
637 where: ^old_follower_address in u.following,
642 "array_replace(?,?,?)",
644 ^old_follower_address,
645 ^user.follower_address
651 Repo.update_all(q, [])
653 maybe_retire_websub(user.ap_id)
655 # Only do this for recent activties, don't go through the whole db.
656 # Only look at the last 1000 activities.
657 since = (Repo.aggregate(Activity, :max, :id) || 0) - 1_000
662 where: ^old_follower_address in a.recipients,
663 where: a.id > ^since,
668 "array_replace(?,?,?)",
670 ^old_follower_address,
671 ^user.follower_address
677 Repo.update_all(q, [])
680 def upgrade_user_from_ap_id(ap_id, async \\ true) do
681 with %User{local: false} = user <- User.get_by_ap_id(ap_id),
682 {:ok, data} <- ActivityPub.fetch_and_prepare_user_from_ap_id(ap_id) do
685 |> Map.put(:info, Map.merge(user.info, data[:info]))
687 already_ap = User.ap_enabled?(user)
690 User.upgrade_changeset(user, data)
694 # This could potentially take a long time, do it in the background
697 user_upgrade_task(user)
700 user_upgrade_task(user)
710 def maybe_retire_websub(ap_id) do
712 if is_binary(ap_id) && String.length(ap_id) > 8 do
715 ws in Pleroma.Web.Websub.WebsubClientSubscription,
716 where: fragment("? like ?", ws.topic, ^"#{ap_id}%")
723 def maybe_fix_user_url(data) do
724 if is_map(data["url"]) do
725 Map.put(data, "url", data["url"]["href"])
731 def maybe_fix_user_object(data) do
733 |> maybe_fix_user_url