1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2020 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.FollowingRelationship
12 alias Pleroma.Object.Containment
15 alias Pleroma.Web.ActivityPub.ActivityPub
16 alias Pleroma.Web.ActivityPub.ObjectValidator
17 alias Pleroma.Web.ActivityPub.ObjectValidators.LikeValidator
18 alias Pleroma.Web.ActivityPub.Pipeline
19 alias Pleroma.Web.ActivityPub.Utils
20 alias Pleroma.Web.ActivityPub.Visibility
21 alias Pleroma.Web.Federator
22 alias Pleroma.Workers.TransmogrifierWorker
27 require Pleroma.Constants
30 Modifies an incoming AP object (mastodon format) to our internal format.
32 def fix_object(object, options \\ []) do
34 |> strip_internal_fields
39 |> 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
61 is_binary(map[field]) ->
62 Map.put(map, field, [map[field]])
65 Map.put(map, field, [])
72 def fix_explicit_addressing(
73 %{"to" => to, "cc" => cc} = object,
77 explicit_to = Enum.filter(to, fn x -> x in explicit_mentions end)
79 explicit_cc = Enum.filter(to, fn x -> x not in explicit_mentions end)
83 |> Enum.reject(fn x -> String.ends_with?(x, "/followers") and x != follower_collection end)
87 |> Map.put("to", explicit_to)
88 |> Map.put("cc", final_cc)
91 def fix_explicit_addressing(object, _explicit_mentions, _followers_collection), do: object
93 # if directMessage flag is set to true, leave the addressing alone
94 def fix_explicit_addressing(%{"directMessage" => true} = object), do: object
96 def fix_explicit_addressing(object) do
97 explicit_mentions = Utils.determine_explicit_mentions(object)
99 %User{follower_address: follower_collection} =
101 |> Containment.get_actor()
102 |> User.get_cached_by_ap_id()
107 Pleroma.Constants.as_public(),
111 fix_explicit_addressing(object, explicit_mentions, follower_collection)
114 # if as:Public is addressed, then make sure the followers collection is also addressed
115 # so that the activities will be delivered to local users.
116 def fix_implicit_addressing(%{"to" => to, "cc" => cc} = object, followers_collection) do
117 recipients = to ++ cc
119 if followers_collection not in recipients do
121 Pleroma.Constants.as_public() in cc ->
122 to = to ++ [followers_collection]
123 Map.put(object, "to", to)
125 Pleroma.Constants.as_public() in to ->
126 cc = cc ++ [followers_collection]
127 Map.put(object, "cc", cc)
137 def fix_implicit_addressing(object, _), do: object
139 def fix_addressing(object) do
140 {:ok, %User{} = user} = User.get_or_fetch_by_ap_id(object["actor"])
141 followers_collection = User.ap_followers(user)
144 |> fix_addressing_list("to")
145 |> fix_addressing_list("cc")
146 |> fix_addressing_list("bto")
147 |> fix_addressing_list("bcc")
148 |> fix_explicit_addressing()
149 |> fix_implicit_addressing(followers_collection)
152 def fix_actor(%{"attributedTo" => actor} = object) do
153 Map.put(object, "actor", Containment.get_actor(%{"actor" => actor}))
156 def fix_in_reply_to(object, options \\ [])
158 def fix_in_reply_to(%{"inReplyTo" => in_reply_to} = object, options)
159 when not is_nil(in_reply_to) do
160 in_reply_to_id = prepare_in_reply_to(in_reply_to)
161 object = Map.put(object, "inReplyToAtomUri", in_reply_to_id)
162 depth = (options[:depth] || 0) + 1
164 if Federator.allowed_thread_distance?(depth) do
165 with {:ok, replied_object} <- get_obj_helper(in_reply_to_id, options),
166 %Activity{} <- Activity.get_create_by_object_ap_id(replied_object.data["id"]) do
168 |> Map.put("inReplyTo", replied_object.data["id"])
169 |> Map.put("inReplyToAtomUri", object["inReplyToAtomUri"] || in_reply_to_id)
170 |> Map.put("conversation", replied_object.data["context"] || object["conversation"])
171 |> Map.put("context", replied_object.data["context"] || object["conversation"])
174 Logger.error("Couldn't fetch #{inspect(in_reply_to_id)}, error: #{inspect(e)}")
182 def fix_in_reply_to(object, _options), do: object
184 defp prepare_in_reply_to(in_reply_to) do
186 is_bitstring(in_reply_to) ->
189 is_map(in_reply_to) && is_bitstring(in_reply_to["id"]) ->
192 is_list(in_reply_to) && is_bitstring(Enum.at(in_reply_to, 0)) ->
193 Enum.at(in_reply_to, 0)
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 defp add_if_present(map, _key, nil), do: map
210 defp add_if_present(map, key, value) do
211 Map.put(map, key, value)
214 def fix_attachments(%{"attachment" => attachment} = object) when is_list(attachment) do
216 Enum.map(attachment, fn data ->
219 is_list(data["url"]) -> List.first(data["url"])
220 is_map(data["url"]) -> data["url"]
226 is_map(url) && is_binary(url["mediaType"]) -> url["mediaType"]
227 is_binary(data["mediaType"]) -> data["mediaType"]
228 is_binary(data["mimeType"]) -> data["mimeType"]
234 is_map(url) && is_binary(url["href"]) -> url["href"]
235 is_binary(data["url"]) -> data["url"]
236 is_binary(data["href"]) -> data["href"]
241 |> add_if_present("mediaType", media_type)
242 |> add_if_present("type", Map.get(url || %{}, "type"))
244 %{"url" => [attachment_url]}
245 |> add_if_present("mediaType", media_type)
246 |> add_if_present("type", data["type"])
247 |> add_if_present("name", data["name"])
250 Map.put(object, "attachment", attachments)
253 def fix_attachments(%{"attachment" => attachment} = object) when is_map(attachment) do
255 |> Map.put("attachment", [attachment])
259 def fix_attachments(object), do: object
261 def fix_url(%{"url" => url} = object) when is_map(url) do
262 Map.put(object, "url", url["href"])
265 def fix_url(%{"type" => object_type, "url" => url} = object)
266 when object_type in ["Video", "Audio"] and is_list(url) do
267 first_element = Enum.at(url, 0)
269 link_element = Enum.find(url, fn x -> is_map(x) and x["mimeType"] == "text/html" end)
272 |> Map.put("attachment", [first_element])
273 |> Map.put("url", link_element["href"])
276 def fix_url(%{"type" => object_type, "url" => url} = object)
277 when object_type != "Video" and is_list(url) do
278 first_element = Enum.at(url, 0)
282 is_bitstring(first_element) -> first_element
283 is_map(first_element) -> first_element["href"] || ""
287 Map.put(object, "url", url_string)
290 def fix_url(object), do: object
292 def fix_emoji(%{"tag" => tags} = object) when is_list(tags) do
295 |> Enum.filter(fn data -> data["type"] == "Emoji" and data["icon"] end)
296 |> Enum.reduce(%{}, fn data, mapping ->
297 name = String.trim(data["name"], ":")
299 Map.put(mapping, name, data["icon"]["url"])
302 # we merge mastodon and pleroma emoji into a single mapping, to allow for both wire formats
303 emoji = Map.merge(object["emoji"] || %{}, emoji)
305 Map.put(object, "emoji", emoji)
308 def fix_emoji(%{"tag" => %{"type" => "Emoji"} = tag} = object) do
309 name = String.trim(tag["name"], ":")
310 emoji = %{name => tag["icon"]["url"]}
312 Map.put(object, "emoji", emoji)
315 def fix_emoji(object), do: object
317 def fix_tag(%{"tag" => tag} = object) when is_list(tag) do
320 |> Enum.filter(fn data -> data["type"] == "Hashtag" and data["name"] end)
321 |> Enum.map(fn data -> String.slice(data["name"], 1..-1) end)
323 Map.put(object, "tag", tag ++ tags)
326 def fix_tag(%{"tag" => %{"type" => "Hashtag", "name" => hashtag} = tag} = object) do
327 combined = [tag, String.slice(hashtag, 1..-1)]
329 Map.put(object, "tag", combined)
332 def fix_tag(%{"tag" => %{} = tag} = object), do: Map.put(object, "tag", [tag])
334 def fix_tag(object), do: object
336 # content map usually only has one language so this will do for now.
337 def fix_content_map(%{"contentMap" => content_map} = object) do
338 content_groups = Map.to_list(content_map)
339 {_, content} = Enum.at(content_groups, 0)
341 Map.put(object, "content", content)
344 def fix_content_map(object), do: object
346 def fix_type(object, options \\ [])
348 def fix_type(%{"inReplyTo" => reply_id, "name" => _} = object, options)
349 when is_binary(reply_id) do
350 with true <- Federator.allowed_thread_distance?(options[:depth]),
351 {:ok, %{data: %{"type" => "Question"} = _} = _} <- get_obj_helper(reply_id, options) do
352 Map.put(object, "type", "Answer")
358 def fix_type(object, _), do: object
360 defp mastodon_follow_hack(%{"id" => id, "actor" => follower_id}, followed) do
361 with true <- id =~ "follows",
362 %User{local: true} = follower <- User.get_cached_by_ap_id(follower_id),
363 %Activity{} = activity <- Utils.fetch_latest_follow(follower, followed) do
370 defp mastodon_follow_hack(_, _), do: {:error, nil}
372 defp get_follow_activity(follow_object, followed) do
373 with object_id when not is_nil(object_id) <- Utils.get_ap_id(follow_object),
374 {_, %Activity{} = activity} <- {:activity, Activity.get_by_ap_id(object_id)} do
377 # Can't find the activity. This might a Mastodon 2.3 "Accept"
379 mastodon_follow_hack(follow_object, followed)
386 # Reduce the object list to find the reported user.
387 defp get_reported(objects) do
388 Enum.reduce_while(objects, nil, fn ap_id, _ ->
389 with %User{} = user <- User.get_cached_by_ap_id(ap_id) do
397 def handle_incoming(data, options \\ [])
399 # Flag objects are placed ahead of the ID check because Mastodon 2.8 and earlier send them
401 def handle_incoming(%{"type" => "Flag", "object" => objects, "actor" => actor} = data, _options) do
402 with context <- data["context"] || Utils.generate_context_id(),
403 content <- data["content"] || "",
404 %User{} = actor <- User.get_cached_by_ap_id(actor),
405 # Reduce the object list to find the reported user.
406 %User{} = account <- get_reported(objects),
407 # Remove the reported user from the object list.
408 statuses <- Enum.filter(objects, fn ap_id -> ap_id != account.ap_id end) do
415 additional: %{"cc" => [account.ap_id]}
417 |> ActivityPub.flag()
421 # disallow objects with bogus IDs
422 def handle_incoming(%{"id" => nil}, _options), do: :error
423 def handle_incoming(%{"id" => ""}, _options), do: :error
424 # length of https:// = 8, should validate better, but good enough for now.
425 def handle_incoming(%{"id" => id}, _options) when is_binary(id) and byte_size(id) < 8,
428 # TODO: validate those with a Ecto scheme
432 %{"type" => "Create", "object" => %{"type" => objtype} = object} = data,
435 when objtype in ["Article", "Event", "Note", "Video", "Page", "Question", "Answer", "Audio"] do
436 actor = Containment.get_actor(data)
439 Map.put(data, "actor", actor)
442 with nil <- Activity.get_create_by_object_ap_id(object["id"]),
443 {:ok, %User{} = user} <- User.get_or_fetch_by_ap_id(data["actor"]) do
444 object = fix_object(object, options)
450 context: object["conversation"],
452 published: data["published"],
461 with {:ok, created_activity} <- ActivityPub.create(params) do
462 reply_depth = (options[:depth] || 0) + 1
464 if Federator.allowed_thread_distance?(reply_depth) do
465 for reply_id <- replies(object) do
466 Pleroma.Workers.RemoteFetcherWorker.enqueue("fetch_remote", %{
468 "depth" => reply_depth
473 {:ok, created_activity}
476 %Activity{} = activity -> {:ok, activity}
482 %{"type" => "Listen", "object" => %{"type" => "Audio"} = object} = data,
485 actor = Containment.get_actor(data)
488 Map.put(data, "actor", actor)
491 with {:ok, %User{} = user} <- User.get_or_fetch_by_ap_id(data["actor"]) do
492 reply_depth = (options[:depth] || 0) + 1
493 options = Keyword.put(options, :depth, reply_depth)
494 object = fix_object(object, options)
502 published: data["published"],
503 additional: Map.take(data, ["cc", "id"])
506 ActivityPub.listen(params)
513 %{"type" => "Follow", "object" => followed, "actor" => follower, "id" => id} = data,
516 with %User{local: true} = followed <-
517 User.get_cached_by_ap_id(Containment.get_actor(%{"actor" => followed})),
518 {:ok, %User{} = follower} <-
519 User.get_or_fetch_by_ap_id(Containment.get_actor(%{"actor" => follower})),
520 {:ok, activity} <- ActivityPub.follow(follower, followed, id, false) do
521 with deny_follow_blocked <- Pleroma.Config.get([:user, :deny_follow_blocked]),
522 {_, false} <- {:user_blocked, User.blocks?(followed, follower) && deny_follow_blocked},
523 {_, false} <- {:user_locked, User.locked?(followed)},
524 {_, {:ok, follower}} <- {:follow, User.follow(follower, followed)},
526 {:follow_state_update, Utils.update_follow_state_for_all(activity, "accept")},
527 {:ok, _relationship} <-
528 FollowingRelationship.update(follower, followed, :follow_accept) do
529 ActivityPub.accept(%{
530 to: [follower.ap_id],
536 {:user_blocked, true} ->
537 {:ok, _} = Utils.update_follow_state_for_all(activity, "reject")
538 {:ok, _relationship} = FollowingRelationship.update(follower, followed, :follow_reject)
540 ActivityPub.reject(%{
541 to: [follower.ap_id],
547 {:follow, {:error, _}} ->
548 {:ok, _} = Utils.update_follow_state_for_all(activity, "reject")
549 {:ok, _relationship} = FollowingRelationship.update(follower, followed, :follow_reject)
551 ActivityPub.reject(%{
552 to: [follower.ap_id],
558 {:user_locked, true} ->
559 {:ok, _relationship} = FollowingRelationship.update(follower, followed, :follow_pending)
571 %{"type" => "Accept", "object" => follow_object, "actor" => _actor, "id" => id} = data,
574 with actor <- Containment.get_actor(data),
575 {:ok, %User{} = followed} <- User.get_or_fetch_by_ap_id(actor),
576 {:ok, follow_activity} <- get_follow_activity(follow_object, followed),
577 {:ok, follow_activity} <- Utils.update_follow_state_for_all(follow_activity, "accept"),
578 %User{local: true} = follower <- User.get_cached_by_ap_id(follow_activity.data["actor"]),
579 {:ok, _relationship} <- FollowingRelationship.update(follower, followed, :follow_accept) do
580 ActivityPub.accept(%{
581 to: follow_activity.data["to"],
584 object: follow_activity.data["id"],
594 %{"type" => "Reject", "object" => follow_object, "actor" => _actor, "id" => id} = data,
597 with actor <- Containment.get_actor(data),
598 {:ok, %User{} = followed} <- User.get_or_fetch_by_ap_id(actor),
599 {:ok, follow_activity} <- get_follow_activity(follow_object, followed),
600 {:ok, follow_activity} <- Utils.update_follow_state_for_all(follow_activity, "reject"),
601 %User{local: true} = follower <- User.get_cached_by_ap_id(follow_activity.data["actor"]),
602 {:ok, _relationship} <- FollowingRelationship.update(follower, followed, :follow_reject),
604 ActivityPub.reject(%{
605 to: follow_activity.data["to"],
608 object: follow_activity.data["id"],
618 @misskey_reactions %{
632 @doc "Rewrite misskey likes into EmojiReacts"
636 "_misskey_reaction" => reaction
641 |> Map.put("type", "EmojiReact")
642 |> Map.put("content", @misskey_reactions[reaction] || reaction)
643 |> handle_incoming(options)
647 %{"type" => "Create", "object" => %{"type" => "ChatMessage"}} = data,
650 case Pipeline.common_pipeline(data, local: false) do
651 {:ok, activity, _} ->
659 def handle_incoming(%{"type" => "Like"} = data, _options) do
660 with {_, {:ok, cast_data_sym}} <-
662 data |> LikeValidator.cast_data() |> Ecto.Changeset.apply_action(:insert)},
663 cast_data = ObjectValidator.stringify_keys(Map.from_struct(cast_data_sym)),
664 :ok <- ObjectValidator.fetch_actor_and_object(cast_data),
665 {_, {:ok, cast_data}} <- {:ensure_context_presence, ensure_context_presence(cast_data)},
666 {_, {:ok, cast_data}} <-
667 {:ensure_recipients_presence, ensure_recipients_presence(cast_data)},
668 {_, {:ok, activity, _meta}} <-
669 {:common_pipeline, Pipeline.common_pipeline(cast_data, local: false)} do
678 "type" => "EmojiReact",
679 "object" => object_id,
686 with actor <- Containment.get_actor(data),
687 {:ok, %User{} = actor} <- User.get_or_fetch_by_ap_id(actor),
688 {:ok, object} <- get_obj_helper(object_id),
689 {:ok, activity, _object} <-
690 ActivityPub.react_with_emoji(actor, object, emoji, activity_id: id, local: false) do
698 %{"type" => "Announce", "object" => object_id, "actor" => _actor, "id" => id} = data,
701 with actor <- Containment.get_actor(data),
702 {:ok, %User{} = actor} <- User.get_or_fetch_by_ap_id(actor),
703 {:ok, object} <- get_embedded_obj_helper(object_id, actor),
704 public <- Visibility.is_public?(data),
705 {:ok, activity, _object} <- ActivityPub.announce(actor, object, id, false, public) do
713 %{"type" => "Update", "object" => %{"type" => object_type} = object, "actor" => actor_id} =
717 when object_type in [
723 with %User{ap_id: ^actor_id} = actor <- User.get_cached_by_ap_id(object["id"]) do
724 {:ok, new_user_data} = ActivityPub.user_data_from_user_object(object)
727 |> User.remote_user_changeset(new_user_data)
728 |> User.update_and_set_cache()
730 ActivityPub.update(%{
732 to: data["to"] || [],
733 cc: data["cc"] || [],
736 activity_id: data["id"]
745 # TODO: We presently assume that any actor on the same origin domain as the object being
746 # deleted has the rights to delete that object. A better way to validate whether or not
747 # the object should be deleted is to refetch the object URI, which should return either
748 # an error or a tombstone. This would allow us to verify that a deletion actually took
751 %{"type" => "Delete", "object" => object_id, "actor" => actor, "id" => id} = data,
754 object_id = Utils.get_ap_id(object_id)
756 with actor <- Containment.get_actor(data),
757 {:ok, %User{} = actor} <- User.get_or_fetch_by_ap_id(actor),
758 {:ok, object} <- get_obj_helper(object_id),
759 :ok <- Containment.contain_origin(actor.ap_id, object.data),
761 ActivityPub.delete(object, local: false, activity_id: id, actor: actor.ap_id) do
765 case User.get_cached_by_ap_id(object_id) do
766 %User{ap_id: ^actor} = user ->
781 "object" => %{"type" => "Announce", "object" => object_id},
787 with actor <- Containment.get_actor(data),
788 {:ok, %User{} = actor} <- User.get_or_fetch_by_ap_id(actor),
789 {:ok, object} <- get_obj_helper(object_id),
790 {:ok, activity, _} <- ActivityPub.unannounce(actor, object, id, false) do
800 "object" => %{"type" => "Follow", "object" => followed},
806 with %User{local: true} = followed <- User.get_cached_by_ap_id(followed),
807 {:ok, %User{} = follower} <- User.get_or_fetch_by_ap_id(follower),
808 {:ok, activity} <- ActivityPub.unfollow(follower, followed, id, false) do
809 User.unfollow(follower, followed)
819 "object" => %{"type" => "EmojiReact", "id" => reaction_activity_id},
825 with actor <- Containment.get_actor(data),
826 {:ok, %User{} = actor} <- User.get_or_fetch_by_ap_id(actor),
827 {:ok, activity, _} <-
828 ActivityPub.unreact_with_emoji(actor, reaction_activity_id,
841 "object" => %{"type" => "Block", "object" => blocked},
847 with %User{local: true} = blocked <- User.get_cached_by_ap_id(blocked),
848 {:ok, %User{} = blocker} <- User.get_or_fetch_by_ap_id(blocker),
849 {:ok, activity} <- ActivityPub.unblock(blocker, blocked, id, false) do
850 User.unblock(blocker, blocked)
858 %{"type" => "Block", "object" => blocked, "actor" => blocker, "id" => id} = _data,
861 with %User{local: true} = blocked = User.get_cached_by_ap_id(blocked),
862 {:ok, %User{} = blocker} = User.get_or_fetch_by_ap_id(blocker),
863 {:ok, activity} <- ActivityPub.block(blocker, blocked, id, false) do
864 User.unfollow(blocker, blocked)
865 User.block(blocker, blocked)
875 "object" => %{"type" => "Like", "object" => object_id},
881 with actor <- Containment.get_actor(data),
882 {:ok, %User{} = actor} <- User.get_or_fetch_by_ap_id(actor),
883 {:ok, object} <- get_obj_helper(object_id),
884 {:ok, activity, _, _} <- ActivityPub.unlike(actor, object, id, false) do
891 # For Undos that don't have the complete object attached, try to find it in our database.
899 when is_binary(object) do
900 with %Activity{data: data} <- Activity.get_by_ap_id(object) do
902 |> Map.put("object", data)
903 |> handle_incoming(options)
912 "actor" => origin_actor,
913 "object" => origin_actor,
914 "target" => target_actor
918 with %User{} = origin_user <- User.get_cached_by_ap_id(origin_actor),
919 {:ok, %User{} = target_user} <- User.get_or_fetch_by_ap_id(target_actor),
920 true <- origin_actor in target_user.also_known_as do
921 ActivityPub.move(origin_user, target_user, false)
927 def handle_incoming(_, _), do: :error
929 @spec get_obj_helper(String.t(), Keyword.t()) :: {:ok, Object.t()} | nil
930 def get_obj_helper(id, options \\ []) do
931 case Object.normalize(id, true, options) do
932 %Object{} = object -> {:ok, object}
937 @spec get_embedded_obj_helper(String.t() | Object.t(), User.t()) :: {:ok, Object.t()} | nil
938 def get_embedded_obj_helper(%{"attributedTo" => attributed_to, "id" => object_id} = data, %User{
941 when attributed_to == ap_id do
942 with {:ok, activity} <-
947 "actor" => attributed_to,
950 {:ok, Object.normalize(activity)}
952 _ -> get_obj_helper(object_id)
956 def get_embedded_obj_helper(object_id, _) do
957 get_obj_helper(object_id)
960 def set_reply_to_uri(%{"inReplyTo" => in_reply_to} = object) when is_binary(in_reply_to) do
961 with false <- String.starts_with?(in_reply_to, "http"),
962 {:ok, %{data: replied_to_object}} <- get_obj_helper(in_reply_to) do
963 Map.put(object, "inReplyTo", replied_to_object["external_url"] || in_reply_to)
969 def set_reply_to_uri(obj), do: obj
972 Serialized Mastodon-compatible `replies` collection containing _self-replies_.
973 Based on Mastodon's ActivityPub::NoteSerializer#replies.
975 def set_replies(obj_data) do
977 with limit when limit > 0 <-
978 Pleroma.Config.get([:activitypub, :note_replies_output_limit], 0),
979 %Object{} = object <- Object.get_cached_by_ap_id(obj_data["id"]) do
981 |> Object.self_replies()
982 |> select([o], fragment("?->>'id'", o.data))
989 set_replies(obj_data, replies_uris)
992 defp set_replies(obj, []) do
996 defp set_replies(obj, replies_uris) do
997 replies_collection = %{
998 "type" => "Collection",
999 "items" => replies_uris
1002 Map.merge(obj, %{"replies" => replies_collection})
1005 def replies(%{"replies" => %{"first" => %{"items" => items}}}) when not is_nil(items) do
1009 def replies(%{"replies" => %{"items" => items}}) when not is_nil(items) do
1013 def replies(_), do: []
1015 # Prepares the object of an outgoing create activity.
1016 def prepare_object(object) do
1022 |> add_attributed_to
1023 |> prepare_attachments
1027 |> strip_internal_fields
1028 |> strip_internal_tags
1034 # internal -> Mastodon
1037 def prepare_outgoing(%{"type" => activity_type, "object" => object_id} = data)
1038 when activity_type in ["Create", "Listen"] do
1041 |> Object.normalize()
1047 |> Map.put("object", object)
1048 |> Map.merge(Utils.make_json_ld_header())
1049 |> Map.delete("bcc")
1054 def prepare_outgoing(%{"type" => "Announce", "actor" => ap_id, "object" => object_id} = data) do
1057 |> Object.normalize()
1060 if Visibility.is_private?(object) && object.data["actor"] == ap_id do
1061 data |> Map.put("object", object |> Map.get(:data) |> prepare_object)
1063 data |> maybe_fix_object_url
1068 |> strip_internal_fields
1069 |> Map.merge(Utils.make_json_ld_header())
1070 |> Map.delete("bcc")
1075 # Mastodon Accept/Reject requires a non-normalized object containing the actor URIs,
1076 # because of course it does.
1077 def prepare_outgoing(%{"type" => "Accept"} = data) do
1078 with follow_activity <- Activity.normalize(data["object"]) do
1080 "actor" => follow_activity.actor,
1081 "object" => follow_activity.data["object"],
1082 "id" => follow_activity.data["id"],
1088 |> Map.put("object", object)
1089 |> Map.merge(Utils.make_json_ld_header())
1095 def prepare_outgoing(%{"type" => "Reject"} = data) do
1096 with follow_activity <- Activity.normalize(data["object"]) do
1098 "actor" => follow_activity.actor,
1099 "object" => follow_activity.data["object"],
1100 "id" => follow_activity.data["id"],
1106 |> Map.put("object", object)
1107 |> Map.merge(Utils.make_json_ld_header())
1113 def prepare_outgoing(%{"type" => _type} = data) do
1116 |> strip_internal_fields
1117 |> maybe_fix_object_url
1118 |> Map.merge(Utils.make_json_ld_header())
1123 def maybe_fix_object_url(%{"object" => object} = data) when is_binary(object) do
1124 with false <- String.starts_with?(object, "http"),
1125 {:fetch, {:ok, relative_object}} <- {:fetch, get_obj_helper(object)},
1126 %{data: %{"external_url" => external_url}} when not is_nil(external_url) <-
1128 Map.put(data, "object", external_url)
1131 Logger.error("Couldn't fetch #{object} #{inspect(e)}")
1139 def maybe_fix_object_url(data), do: data
1141 def add_hashtags(object) do
1143 (object["tag"] || [])
1145 # Expand internal representation tags into AS2 tags.
1146 tag when is_binary(tag) ->
1148 "href" => Pleroma.Web.Endpoint.url() <> "/tags/#{tag}",
1149 "name" => "##{tag}",
1153 # Do not process tags which are already AS2 tag objects.
1154 tag when is_map(tag) ->
1158 Map.put(object, "tag", tags)
1161 def add_mention_tags(object) do
1162 {enabled_receivers, disabled_receivers} = Utils.get_notified_from_object(object)
1163 potential_receivers = enabled_receivers ++ disabled_receivers
1164 mentions = Enum.map(potential_receivers, &build_mention_tag/1)
1166 tags = object["tag"] || []
1167 Map.put(object, "tag", tags ++ mentions)
1170 defp build_mention_tag(%{ap_id: ap_id, nickname: nickname} = _) do
1171 %{"type" => "Mention", "href" => ap_id, "name" => "@#{nickname}"}
1174 def take_emoji_tags(%User{emoji: emoji}) do
1177 |> Enum.map(&build_emoji_tag/1)
1180 # TODO: we should probably send mtime instead of unix epoch time for updated
1181 def add_emoji_tags(%{"emoji" => emoji} = object) do
1182 tags = object["tag"] || []
1184 out = Enum.map(emoji, &build_emoji_tag/1)
1186 Map.put(object, "tag", tags ++ out)
1189 def add_emoji_tags(object), do: object
1191 defp build_emoji_tag({name, url}) do
1193 "icon" => %{"url" => url, "type" => "Image"},
1194 "name" => ":" <> name <> ":",
1196 "updated" => "1970-01-01T00:00:00Z",
1201 def set_conversation(object) do
1202 Map.put(object, "conversation", object["context"])
1205 def set_sensitive(object) do
1206 tags = object["tag"] || []
1207 Map.put(object, "sensitive", "nsfw" in tags)
1210 def set_type(%{"type" => "Answer"} = object) do
1211 Map.put(object, "type", "Note")
1214 def set_type(object), do: object
1216 def add_attributed_to(object) do
1217 attributed_to = object["attributedTo"] || object["actor"]
1218 Map.put(object, "attributedTo", attributed_to)
1221 def prepare_attachments(object) do
1223 (object["attachment"] || [])
1224 |> Enum.map(fn data ->
1225 [%{"mediaType" => media_type, "href" => href} | _] = data["url"]
1226 %{"url" => href, "mediaType" => media_type, "name" => data["name"], "type" => "Document"}
1229 Map.put(object, "attachment", attachments)
1232 def strip_internal_fields(object) do
1234 |> Map.drop(Pleroma.Constants.object_internal_fields())
1237 defp strip_internal_tags(%{"tag" => tags} = object) do
1238 tags = Enum.filter(tags, fn x -> is_map(x) end)
1240 Map.put(object, "tag", tags)
1243 defp strip_internal_tags(object), do: object
1245 def perform(:user_upgrade, user) do
1246 # we pass a fake user so that the followers collection is stripped away
1247 old_follower_address = User.ap_followers(%User{nickname: user.nickname})
1251 where: ^old_follower_address in a.recipients,
1256 "array_replace(?,?,?)",
1258 ^old_follower_address,
1259 ^user.follower_address
1264 |> Repo.update_all([])
1267 def upgrade_user_from_ap_id(ap_id) do
1268 with %User{local: false} = user <- User.get_cached_by_ap_id(ap_id),
1269 {:ok, data} <- ActivityPub.fetch_and_prepare_user_from_ap_id(ap_id),
1270 {:ok, user} <- update_user(user, data) do
1271 TransmogrifierWorker.enqueue("user_upgrade", %{"user_id" => user.id})
1274 %User{} = user -> {:ok, user}
1279 defp update_user(user, data) do
1281 |> User.remote_user_changeset(data)
1282 |> User.update_and_set_cache()
1285 def maybe_fix_user_url(%{"url" => url} = data) when is_map(url) do
1286 Map.put(data, "url", url["href"])
1289 def maybe_fix_user_url(data), do: data
1291 def maybe_fix_user_object(data), do: maybe_fix_user_url(data)
1293 defp ensure_context_presence(%{"context" => context} = data) when is_binary(context),
1296 defp ensure_context_presence(%{"object" => object} = data) when is_binary(object) do
1297 with %{data: %{"context" => context}} when is_binary(context) <- Object.normalize(object) do
1298 {:ok, Map.put(data, "context", context)}
1301 {:error, :no_context}
1305 defp ensure_context_presence(_) do
1306 {:error, :no_context}
1309 defp ensure_recipients_presence(%{"to" => [_ | _], "cc" => [_ | _]} = data),
1312 defp ensure_recipients_presence(%{"object" => object} = data) do
1313 case Object.normalize(object) do
1314 %{data: %{"actor" => actor}} ->
1317 |> Map.put("to", [actor])
1318 |> Map.put("cc", data["cc"] || [])
1323 {:error, :no_object}
1330 defp ensure_recipients_presence(_) do
1331 {:error, :no_object}