1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2022 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
5 defmodule Pleroma.Web.ActivityPub.Utils do
11 alias Pleroma.Notification
15 alias Pleroma.Web.ActivityPub.ActivityPub
16 alias Pleroma.Web.ActivityPub.Visibility
17 alias Pleroma.Web.AdminAPI.AccountView
18 alias Pleroma.Web.Endpoint
19 alias Pleroma.Web.Router.Helpers
24 require Pleroma.Constants
26 @supported_object_types [
36 @strip_status_report_states ~w(closed resolved)
37 @supported_report_states ~w(open closed resolved)
38 @valid_visibilities ~w(public unlisted private direct)
40 def as_local_public, do: Endpoint.url() <> "/#Public"
42 # Some implementations send the actor URI as the actor field, others send the entire actor object,
43 # so figure out what the actor's URI is based on what we have.
44 def get_ap_id(%{"id" => id} = _), do: id
45 def get_ap_id(id), do: id
47 def normalize_params(params) do
48 Map.put(params, "actor", get_ap_id(params["actor"]))
51 @spec determine_explicit_mentions(map()) :: [any]
52 def determine_explicit_mentions(%{"tag" => tag}) when is_list(tag) do
54 %{"type" => "Mention", "href" => href} -> [href]
59 def determine_explicit_mentions(%{"tag" => tag} = object) when is_map(tag) do
61 |> Map.put("tag", [tag])
62 |> determine_explicit_mentions()
65 def determine_explicit_mentions(_), do: []
67 @spec label_in_collection?(any(), any()) :: boolean()
68 defp label_in_collection?(ap_id, coll) when is_binary(coll), do: ap_id == coll
69 defp label_in_collection?(ap_id, coll) when is_list(coll), do: ap_id in coll
70 defp label_in_collection?(_, _), do: false
72 @spec label_in_message?(String.t(), map()) :: boolean()
73 def label_in_message?(label, params),
75 [params["to"], params["cc"], params["bto"], params["bcc"]]
76 |> Enum.any?(&label_in_collection?(label, &1))
78 @spec unaddressed_message?(map()) :: boolean()
79 def unaddressed_message?(params),
81 [params["to"], params["cc"], params["bto"], params["bcc"]]
82 |> Enum.all?(&is_nil(&1))
84 @spec recipient_in_message(User.t(), User.t(), map()) :: boolean()
85 def recipient_in_message(%User{ap_id: ap_id} = recipient, %User{} = actor, params),
87 label_in_message?(ap_id, params) || unaddressed_message?(params) ||
88 User.following?(recipient, actor)
90 defp extract_list(target) when is_binary(target), do: [target]
91 defp extract_list(lst) when is_list(lst), do: lst
92 defp extract_list(_), do: []
94 def maybe_splice_recipient(ap_id, params) do
96 !label_in_collection?(ap_id, params["to"]) &&
97 !label_in_collection?(ap_id, params["cc"])
100 cc = [ap_id | extract_list(params["cc"])]
104 |> Maps.safe_put_in(["object", "cc"], cc)
110 def make_json_ld_header do
113 "https://www.w3.org/ns/activitystreams",
114 "#{Endpoint.url()}/schemas/litepub-0.1.jsonld",
123 DateTime.utc_now() |> DateTime.to_iso8601()
126 def generate_activity_id do
127 generate_id("activities")
130 def generate_context_id do
131 generate_id("contexts")
134 def generate_object_id do
135 Helpers.o_status_url(Endpoint, :object, UUID.generate())
138 def generate_id(type) do
139 "#{Endpoint.url()}/#{type}/#{UUID.generate()}"
142 def get_notified_from_object(%{"type" => type} = object) when type in @supported_object_types do
143 fake_create_activity = %{
144 "to" => object["to"],
145 "cc" => object["cc"],
150 get_notified_from_object(fake_create_activity)
153 def get_notified_from_object(object) do
154 Notification.get_notified_from_activity(%Activity{data: object}, false)
157 def maybe_create_context(context), do: context || generate_id("contexts")
160 Enqueues an activity for federation if it's local
162 @spec maybe_federate(any()) :: :ok
163 def maybe_federate(%Activity{local: true, data: %{"type" => type}} = activity) do
164 outgoing_blocks = Config.get([:activitypub, :outgoing_blocks])
166 with true <- Config.get!([:instance, :federating]),
167 true <- type != "Block" || outgoing_blocks,
168 false <- Visibility.is_local_public?(activity) do
169 Pleroma.Web.Federator.publish(activity)
175 def maybe_federate(_), do: :ok
178 Adds an id and a published data if they aren't there,
179 also adds it to an included object
181 @spec lazy_put_activity_defaults(map(), boolean) :: map()
182 def lazy_put_activity_defaults(map, fake? \\ false)
184 def lazy_put_activity_defaults(map, true) do
186 |> Map.put_new("id", "pleroma:fakeid")
187 |> Map.put_new_lazy("published", &make_date/0)
188 |> Map.put_new("context", "pleroma:fakecontext")
189 |> lazy_put_object_defaults(true)
192 def lazy_put_activity_defaults(map, _fake?) do
193 context = maybe_create_context(map["context"])
196 |> Map.put_new_lazy("id", &generate_activity_id/0)
197 |> Map.put_new_lazy("published", &make_date/0)
198 |> Map.put_new("context", context)
199 |> lazy_put_object_defaults(false)
202 # Adds an id and published date if they aren't there.
204 @spec lazy_put_object_defaults(map(), boolean()) :: map()
205 defp lazy_put_object_defaults(%{"object" => map} = activity, true)
209 |> Map.put_new("id", "pleroma:fake_object_id")
210 |> Map.put_new_lazy("published", &make_date/0)
211 |> Map.put_new("context", activity["context"])
212 |> Map.put_new("fake", true)
214 %{activity | "object" => object}
217 defp lazy_put_object_defaults(%{"object" => map} = activity, _)
221 |> Map.put_new_lazy("id", &generate_object_id/0)
222 |> Map.put_new_lazy("published", &make_date/0)
223 |> Map.put_new("context", activity["context"])
225 %{activity | "object" => object}
228 defp lazy_put_object_defaults(activity, _), do: activity
231 Inserts a full object if it is contained in an activity.
233 def insert_full_object(%{"object" => %{"type" => type} = object_data} = map)
234 when type in @supported_object_types do
235 with {:ok, object} <- Object.create(object_data) do
236 map = Map.put(map, "object", object.data["id"])
242 def insert_full_object(map), do: {:ok, map, nil}
244 #### Like-related helpers
247 Returns an existing like if a user already liked an object
249 @spec get_existing_like(String.t(), map()) :: Activity.t() | nil
250 def get_existing_like(actor, %{data: %{"id" => id}}) do
252 |> Activity.Queries.by_actor()
253 |> Activity.Queries.by_object_id(id)
254 |> Activity.Queries.by_type("Like")
260 Returns like activities targeting an object
262 def get_object_likes(%{data: %{"id" => id}}) do
264 |> Activity.Queries.by_object_id()
265 |> Activity.Queries.by_type("Like")
269 @spec make_like_data(User.t(), map(), String.t()) :: map()
271 %User{ap_id: ap_id} = actor,
272 %{data: %{"actor" => object_actor_id, "id" => id}} = object,
275 object_actor = User.get_cached_by_ap_id(object_actor_id)
278 if Visibility.is_public?(object) do
279 [actor.follower_address, object.data["actor"]]
281 [object.data["actor"]]
285 (object.data["to"] ++ (object.data["cc"] || []))
286 |> List.delete(actor.ap_id)
287 |> List.delete(object_actor.follower_address)
295 "context" => object.data["context"]
297 |> Maps.put_if_present("id", activity_id)
300 def make_emoji_reaction_data(user, object, emoji, activity_id) do
301 make_like_data(user, object, activity_id)
302 |> Map.put("type", "EmojiReact")
303 |> Map.put("content", emoji)
306 @spec update_element_in_object(String.t(), list(any), Object.t(), integer() | nil) ::
307 {:ok, Object.t()} | {:error, Ecto.Changeset.t()}
308 def update_element_in_object(property, element, object, count \\ nil) do
316 %{"#{property}_count" => length, "#{property}s" => element}
320 |> Changeset.change(data: data)
321 |> Object.update_and_set_cache()
324 @spec add_emoji_reaction_to_object(Activity.t(), Object.t()) ::
325 {:ok, Object.t()} | {:error, Ecto.Changeset.t()}
327 def add_emoji_reaction_to_object(
328 %Activity{data: %{"content" => emoji, "actor" => actor}},
331 reactions = get_cached_emoji_reactions(object)
334 case Enum.find_index(reactions, fn [candidate, _] -> emoji == candidate end) do
336 reactions ++ [[emoji, [actor]]]
342 fn [emoji, users] -> [emoji, Enum.uniq([actor | users])] end
346 count = emoji_count(new_reactions)
348 update_element_in_object("reaction", new_reactions, object, count)
351 def emoji_count(reactions_list) do
352 Enum.reduce(reactions_list, 0, fn [_, users], acc -> acc + length(users) end)
355 def remove_emoji_reaction_from_object(
356 %Activity{data: %{"content" => emoji, "actor" => actor}},
359 reactions = get_cached_emoji_reactions(object)
362 case Enum.find_index(reactions, fn [candidate, _] -> emoji == candidate end) do
370 fn [emoji, users] -> [emoji, List.delete(users, actor)] end
372 |> Enum.reject(fn [_, users] -> Enum.empty?(users) end)
375 count = emoji_count(new_reactions)
376 update_element_in_object("reaction", new_reactions, object, count)
379 def get_cached_emoji_reactions(object) do
380 if is_list(object.data["reactions"]) do
381 object.data["reactions"]
387 @spec add_like_to_object(Activity.t(), Object.t()) ::
388 {:ok, Object.t()} | {:error, Ecto.Changeset.t()}
389 def add_like_to_object(%Activity{data: %{"actor" => actor}}, object) do
390 [actor | fetch_likes(object)]
392 |> update_likes_in_object(object)
395 @spec remove_like_from_object(Activity.t(), Object.t()) ::
396 {:ok, Object.t()} | {:error, Ecto.Changeset.t()}
397 def remove_like_from_object(%Activity{data: %{"actor" => actor}}, object) do
400 |> List.delete(actor)
401 |> update_likes_in_object(object)
404 defp update_likes_in_object(likes, object) do
405 update_element_in_object("like", likes, object)
408 defp fetch_likes(object) do
409 if is_list(object.data["likes"]) do
416 #### Follow-related helpers
419 Updates a follow activity's state (for locked accounts).
421 @spec update_follow_state_for_all(Activity.t(), String.t()) :: {:ok, Activity | nil}
422 def update_follow_state_for_all(
423 %Activity{data: %{"actor" => actor, "object" => object}} = activity,
427 |> Activity.Queries.by_type()
428 |> Activity.Queries.by_actor(actor)
429 |> Activity.Queries.by_object_id(object)
430 |> where(fragment("data->>'state' = 'pending'") or fragment("data->>'state' = 'accept'"))
431 |> update(set: [data: fragment("jsonb_set(data, '{state}', ?)", ^state)])
432 |> Repo.update_all([])
434 activity = Activity.get_by_id(activity.id)
439 def update_follow_state(
440 %Activity{} = activity,
443 new_data = Map.put(activity.data, "state", state)
444 changeset = Changeset.change(activity, data: new_data)
446 with {:ok, activity} <- Repo.update(changeset) do
452 Makes a follow activity data for the given follower and followed
454 def make_follow_data(
455 %User{ap_id: follower_id},
456 %User{ap_id: followed_id} = _followed,
461 "actor" => follower_id,
462 "to" => [followed_id],
463 "cc" => [Pleroma.Constants.as_public()],
464 "object" => followed_id,
467 |> Maps.put_if_present("id", activity_id)
470 def fetch_latest_follow(%User{ap_id: follower_id}, %User{ap_id: followed_id}) do
472 |> Activity.Queries.by_type()
473 |> where(actor: ^follower_id)
474 # this is to use the index
475 |> Activity.Queries.by_object_id(followed_id)
476 |> order_by([activity], fragment("? desc nulls last", activity.id))
481 def fetch_latest_undo(%User{ap_id: ap_id}) do
483 |> Activity.Queries.by_type()
484 |> where(actor: ^ap_id)
485 |> order_by([activity], fragment("? desc nulls last", activity.id))
490 def get_latest_reaction(internal_activity_id, %{ap_id: ap_id}, emoji) do
491 %{data: %{"object" => object_ap_id}} = Activity.get_by_id(internal_activity_id)
494 |> Activity.Queries.by_type()
495 |> where(actor: ^ap_id)
496 |> where([activity], fragment("?->>'content' = ?", activity.data, ^emoji))
497 |> Activity.Queries.by_object_id(object_ap_id)
498 |> order_by([activity], fragment("? desc nulls last", activity.id))
503 #### Announce-related helpers
506 Returns an existing announce activity if the notice has already been announced
508 @spec get_existing_announce(String.t(), map()) :: Activity.t() | nil
509 def get_existing_announce(actor, %{data: %{"id" => ap_id}}) do
511 |> Activity.Queries.by_type()
512 |> where(actor: ^actor)
513 # this is to use the index
514 |> Activity.Queries.by_object_id(ap_id)
519 Make announce activity data for the given actor and object
521 # for relayed messages, we only want to send to subscribers
522 def make_announce_data(
523 %User{ap_id: ap_id} = user,
524 %Object{data: %{"id" => id}} = object,
529 "type" => "Announce",
532 "to" => [user.follower_address],
534 "context" => object.data["context"]
536 |> Maps.put_if_present("id", activity_id)
539 def make_announce_data(
540 %User{ap_id: ap_id} = user,
541 %Object{data: %{"id" => id}} = object,
546 "type" => "Announce",
549 "to" => [user.follower_address, object.data["actor"]],
550 "cc" => [Pleroma.Constants.as_public()],
551 "context" => object.data["context"]
553 |> Maps.put_if_present("id", activity_id)
557 %User{ap_id: actor, follower_address: follower_address},
559 data: %{"id" => undone_activity_id, "context" => context},
560 actor: undone_activity_actor
567 "object" => undone_activity_id,
568 "to" => [follower_address, undone_activity_actor],
569 "cc" => [Pleroma.Constants.as_public()],
572 |> Maps.put_if_present("id", activity_id)
575 @spec add_announce_to_object(Activity.t(), Object.t()) ::
576 {:ok, Object.t()} | {:error, Ecto.Changeset.t()}
577 def add_announce_to_object(
578 %Activity{data: %{"actor" => actor}},
581 unless actor |> User.get_cached_by_ap_id() |> User.invisible?() do
582 announcements = take_announcements(object)
584 with announcements <- Enum.uniq([actor | announcements]) do
585 update_element_in_object("announcement", announcements, object)
592 def add_announce_to_object(_, object), do: {:ok, object}
594 @spec remove_announce_from_object(Activity.t(), Object.t()) ::
595 {:ok, Object.t()} | {:error, Ecto.Changeset.t()}
596 def remove_announce_from_object(%Activity{data: %{"actor" => actor}}, object) do
597 with announcements <- List.delete(take_announcements(object), actor) do
598 update_element_in_object("announcement", announcements, object)
602 defp take_announcements(%{data: %{"announcements" => announcements}} = _)
603 when is_list(announcements),
606 defp take_announcements(_), do: []
608 #### Unfollow-related helpers
610 def make_unfollow_data(follower, followed, follow_activity, activity_id) do
613 "actor" => follower.ap_id,
614 "to" => [followed.ap_id],
615 "object" => follow_activity.data
617 |> Maps.put_if_present("id", activity_id)
620 #### Block-related helpers
621 @spec fetch_latest_block(User.t(), User.t()) :: Activity.t() | nil
622 def fetch_latest_block(%User{ap_id: blocker_id}, %User{ap_id: blocked_id}) do
624 |> Activity.Queries.by_type()
625 |> where(actor: ^blocker_id)
626 # this is to use the index
627 |> Activity.Queries.by_object_id(blocked_id)
628 |> order_by([activity], fragment("? desc nulls last", activity.id))
633 def make_block_data(blocker, blocked, activity_id) do
636 "actor" => blocker.ap_id,
637 "to" => [blocked.ap_id],
638 "object" => blocked.ap_id
640 |> Maps.put_if_present("id", activity_id)
643 #### Create-related helpers
645 def make_create_data(params, additional) do
646 published = params.published || make_date()
650 "to" => params.to |> Enum.uniq(),
651 "actor" => params.actor.ap_id,
652 "object" => params.object,
653 "published" => published,
654 "context" => params.context
656 |> Map.merge(additional)
659 #### Listen-related helpers
660 def make_listen_data(params, additional) do
661 published = params.published || make_date()
665 "to" => params.to |> Enum.uniq(),
666 "actor" => params.actor.ap_id,
667 "object" => params.object,
668 "published" => published,
669 "context" => params.context
671 |> Map.merge(additional)
674 #### Flag-related helpers
675 @spec make_flag_data(map(), map()) :: map()
676 def make_flag_data(%{actor: actor, context: context, content: content} = params, additional) do
679 "actor" => actor.ap_id,
680 "content" => content,
681 "object" => build_flag_object(params),
682 "context" => context,
685 |> Map.merge(additional)
688 def make_flag_data(_, _), do: %{}
690 defp build_flag_object(%{account: account, statuses: statuses}) do
691 [account.ap_id | build_flag_object(%{statuses: statuses})]
694 defp build_flag_object(%{statuses: statuses}) do
695 Enum.map(statuses || [], &build_flag_object/1)
698 defp build_flag_object(%Activity{} = activity) do
699 object = Object.normalize(activity, fetch: false)
701 # Do not allow people to report Creates. Instead, report the Object that is Created.
702 if activity.data["type"] != "Create" do
703 build_flag_object_with_actor_and_id(
705 User.get_by_ap_id(activity.data["actor"]),
709 build_flag_object(object)
713 defp build_flag_object(%Object{} = object) do
714 actor = User.get_by_ap_id(object.data["actor"])
715 build_flag_object_with_actor_and_id(object, actor, object.data["id"])
718 defp build_flag_object(act) when is_map(act) or is_binary(act) do
721 %Activity{} = act -> act.data["id"]
722 act when is_map(act) -> act["id"]
723 act when is_binary(act) -> act
726 case Activity.get_by_ap_id_with_object(id) do
727 %Activity{object: object} = _ ->
728 build_flag_object(object)
731 if %Object{} = object = Object.get_by_ap_id(id) do
732 build_flag_object(object)
734 %{"id" => id, "deleted" => true}
739 defp build_flag_object(_), do: []
741 defp build_flag_object_with_actor_and_id(%Object{data: data}, actor, id) do
745 "content" => data["content"],
746 "published" => data["published"],
750 %{user: actor, skip_visibility_check: true}
755 #### Report-related helpers
756 def get_reports(params, page, page_size) do
759 |> Map.put(:type, "Flag")
760 |> Map.put(:skip_preload, true)
761 |> Map.put(:preload_report_notes, true)
762 |> Map.put(:total, true)
763 |> Map.put(:limit, page_size)
764 |> Map.put(:offset, (page - 1) * page_size)
766 ActivityPub.fetch_activities([], params, :offset)
769 defp maybe_strip_report_status(data, state) do
770 with true <- Config.get([:instance, :report_strip_status]),
771 true <- state in @strip_status_report_states,
772 {:ok, stripped_activity} = strip_report_status_data(%Activity{data: data}) do
773 data |> Map.put("object", stripped_activity.data["object"])
779 def update_report_state(%Activity{} = activity, state) when state in @supported_report_states do
782 |> Map.put("state", state)
783 |> maybe_strip_report_status(state)
786 |> Changeset.change(data: new_data)
790 def update_report_state(activity_ids, state) when state in @supported_report_states do
791 activities_num = length(activity_ids)
793 from(a in Activity, where: a.id in ^activity_ids)
794 |> update(set: [data: fragment("jsonb_set(data, '{state}', ?)", ^state)])
795 |> Repo.update_all([])
797 {^activities_num, _} -> :ok
798 _ -> {:error, activity_ids}
802 def update_report_state(_, _), do: {:error, "Unsupported state"}
804 def strip_report_status_data(activity) do
805 [actor | reported_activities] = activity.data["object"]
807 stripped_activities =
808 Enum.map(reported_activities, fn
809 act when is_map(act) -> act["id"]
810 act when is_binary(act) -> act
813 new_data = put_in(activity.data, ["object"], [actor | stripped_activities])
815 {:ok, %{activity | data: new_data}}
818 def update_activity_visibility(activity, visibility) when visibility in @valid_visibilities do
819 [to, cc, recipients] =
821 |> get_updated_targets(visibility)
822 |> Enum.map(&Enum.uniq/1)
831 |> Object.change(%{data: object_data})
832 |> Object.update_and_set_cache()
840 |> Map.put(:object, object)
841 |> Activity.change(%{data: activity_data, recipients: recipients})
845 def update_activity_visibility(_, _), do: {:error, "Unsupported visibility"}
847 defp get_updated_targets(
848 %Activity{data: %{"to" => to} = data, recipients: recipients},
851 cc = Map.get(data, "cc", [])
852 follower_address = User.get_cached_by_ap_id(data["actor"]).follower_address
853 public = Pleroma.Constants.as_public()
857 to = [public | List.delete(to, follower_address)]
858 cc = [follower_address | List.delete(cc, public)]
859 recipients = [public | recipients]
863 to = [follower_address | List.delete(to, public)]
864 cc = List.delete(cc, public)
865 recipients = List.delete(recipients, public)
869 to = [follower_address | List.delete(to, public)]
870 cc = [public | List.delete(cc, follower_address)]
871 recipients = recipients ++ [follower_address, public]
879 def get_existing_votes(actor, %{data: %{"id" => id}}) do
881 |> Activity.Queries.by_actor()
882 |> Activity.Queries.by_type("Create")
883 |> Activity.with_preloaded_object()
884 |> where([a, object: o], fragment("(?)->>'inReplyTo' = ?", o.data, ^to_string(id)))
885 |> where([a, object: o], fragment("(?)->>'type' = 'Answer'", o.data))