1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2021 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}} = activity,
331 reactions = get_cached_emoji_reactions(object)
332 emoji = Pleroma.Emoji.stripped_name(emoji)
333 url = emoji_url(emoji, activity)
336 case Enum.find_index(reactions, fn [candidate, _, candidate_url] ->
337 if is_nil(candidate_url) do
344 reactions ++ [[emoji, [actor], url]]
350 fn [emoji, users, url] -> [emoji, Enum.uniq([actor | users]), url] end
354 count = emoji_count(new_reactions)
356 update_element_in_object("reaction", new_reactions, object, count)
364 %{"type" => "Emoji", "name" => name, "icon" => %{"url" => url}}
371 defp emoji_url(_, _), do: nil
373 def emoji_count(reactions_list) do
374 Enum.reduce(reactions_list, 0, fn [_, users, _], acc -> acc + length(users) end)
377 def remove_emoji_reaction_from_object(
378 %Activity{data: %{"content" => emoji, "actor" => actor}} = activity,
381 emoji = Pleroma.Emoji.stripped_name(emoji)
382 reactions = get_cached_emoji_reactions(object)
383 url = emoji_url(emoji, activity)
386 case Enum.find_index(reactions, fn [candidate, _, candidate_url] ->
387 if is_nil(candidate_url) do
400 fn [emoji, users, url] -> [emoji, List.delete(users, actor), url] end
402 |> Enum.reject(fn [_, users, _] -> Enum.empty?(users) end)
405 count = emoji_count(new_reactions)
406 update_element_in_object("reaction", new_reactions, object, count)
409 def get_cached_emoji_reactions(object) do
410 if is_list(object.data["reactions"]) do
411 object.data["reactions"]
417 @spec add_like_to_object(Activity.t(), Object.t()) ::
418 {:ok, Object.t()} | {:error, Ecto.Changeset.t()}
419 def add_like_to_object(%Activity{data: %{"actor" => actor}}, object) do
420 [actor | fetch_likes(object)]
422 |> update_likes_in_object(object)
425 @spec remove_like_from_object(Activity.t(), Object.t()) ::
426 {:ok, Object.t()} | {:error, Ecto.Changeset.t()}
427 def remove_like_from_object(%Activity{data: %{"actor" => actor}}, object) do
430 |> List.delete(actor)
431 |> update_likes_in_object(object)
434 defp update_likes_in_object(likes, object) do
435 update_element_in_object("like", likes, object)
438 defp fetch_likes(object) do
439 if is_list(object.data["likes"]) do
446 #### Follow-related helpers
449 Updates a follow activity's state (for locked accounts).
451 @spec update_follow_state_for_all(Activity.t(), String.t()) :: {:ok, Activity | nil}
452 def update_follow_state_for_all(
453 %Activity{data: %{"actor" => actor, "object" => object}} = activity,
457 |> Activity.Queries.by_type()
458 |> Activity.Queries.by_actor(actor)
459 |> Activity.Queries.by_object_id(object)
460 |> where(fragment("data->>'state' = 'pending'") or fragment("data->>'state' = 'accept'"))
461 |> update(set: [data: fragment("jsonb_set(data, '{state}', ?)", ^state)])
462 |> Repo.update_all([])
464 activity = Activity.get_by_id(activity.id)
470 Makes a follow activity data for the given follower and followed
472 def make_follow_data(
473 %User{ap_id: follower_id},
474 %User{ap_id: followed_id} = _followed,
479 "actor" => follower_id,
480 "to" => [followed_id],
481 "cc" => [Pleroma.Constants.as_public()],
482 "object" => followed_id,
485 |> Maps.put_if_present("id", activity_id)
488 def fetch_latest_follow(%User{ap_id: follower_id}, %User{ap_id: followed_id}) do
490 |> Activity.Queries.by_type()
491 |> where(actor: ^follower_id)
492 # this is to use the index
493 |> Activity.Queries.by_object_id(followed_id)
494 |> order_by([activity], fragment("? desc nulls last", activity.id))
499 def fetch_latest_undo(%User{ap_id: ap_id}) do
501 |> Activity.Queries.by_type()
502 |> where(actor: ^ap_id)
503 |> order_by([activity], fragment("? desc nulls last", activity.id))
508 def get_latest_reaction(internal_activity_id, %{ap_id: ap_id}, emoji) do
509 %{data: %{"object" => object_ap_id}} = Activity.get_by_id(internal_activity_id)
510 emoji = Pleroma.Emoji.maybe_quote(emoji)
513 |> Activity.Queries.by_type()
514 |> where(actor: ^ap_id)
515 |> custom_emoji_discriminator(emoji)
516 |> Activity.Queries.by_object_id(object_ap_id)
517 |> order_by([activity], fragment("? desc nulls last", activity.id))
522 defp custom_emoji_discriminator(query, emoji) do
523 if String.contains?(emoji, "@") do
524 stripped = Pleroma.Emoji.stripped_name(emoji)
525 [name, domain] = String.split(stripped, "@")
526 domain_pattern = "%" <> domain <> "%"
527 emoji_pattern = Pleroma.Emoji.maybe_quote(name)
530 |> where([activity], fragment("?->>'content' = ?
532 SELECT FROM jsonb_array_elements(?->'tag') elem
533 WHERE elem->>'id' ILIKE ?
534 )", activity.data, ^emoji_pattern, activity.data, ^domain_pattern))
537 |> where([activity], fragment("?->>'content' = ?", activity.data, ^emoji))
541 #### Announce-related helpers
544 Returns an existing announce activity if the notice has already been announced
546 @spec get_existing_announce(String.t(), map()) :: Activity.t() | nil
547 def get_existing_announce(actor, %{data: %{"id" => ap_id}}) do
549 |> Activity.Queries.by_type()
550 |> where(actor: ^actor)
551 # this is to use the index
552 |> Activity.Queries.by_object_id(ap_id)
557 Make announce activity data for the given actor and object
559 # for relayed messages, we only want to send to subscribers
560 def make_announce_data(
561 %User{ap_id: ap_id} = user,
562 %Object{data: %{"id" => id}} = object,
567 "type" => "Announce",
570 "to" => [user.follower_address],
572 "context" => object.data["context"]
574 |> Maps.put_if_present("id", activity_id)
577 def make_announce_data(
578 %User{ap_id: ap_id} = user,
579 %Object{data: %{"id" => id}} = object,
584 "type" => "Announce",
587 "to" => [user.follower_address, object.data["actor"]],
588 "cc" => [Pleroma.Constants.as_public()],
589 "context" => object.data["context"]
591 |> Maps.put_if_present("id", activity_id)
595 %User{ap_id: actor, follower_address: follower_address},
597 data: %{"id" => undone_activity_id, "context" => context},
598 actor: undone_activity_actor
605 "object" => undone_activity_id,
606 "to" => [follower_address, undone_activity_actor],
607 "cc" => [Pleroma.Constants.as_public()],
610 |> Maps.put_if_present("id", activity_id)
613 @spec add_announce_to_object(Activity.t(), Object.t()) ::
614 {:ok, Object.t()} | {:error, Ecto.Changeset.t()}
615 def add_announce_to_object(
616 %Activity{data: %{"actor" => actor}},
619 unless actor |> User.get_cached_by_ap_id() |> User.invisible?() do
620 announcements = take_announcements(object)
622 with announcements <- Enum.uniq([actor | announcements]) do
623 update_element_in_object("announcement", announcements, object)
630 def add_announce_to_object(_, object), do: {:ok, object}
632 @spec remove_announce_from_object(Activity.t(), Object.t()) ::
633 {:ok, Object.t()} | {:error, Ecto.Changeset.t()}
634 def remove_announce_from_object(%Activity{data: %{"actor" => actor}}, object) do
635 with announcements <- List.delete(take_announcements(object), actor) do
636 update_element_in_object("announcement", announcements, object)
640 defp take_announcements(%{data: %{"announcements" => announcements}} = _)
641 when is_list(announcements),
644 defp take_announcements(_), do: []
646 #### Unfollow-related helpers
648 def make_unfollow_data(follower, followed, follow_activity, activity_id) do
651 "actor" => follower.ap_id,
652 "to" => [followed.ap_id],
653 "object" => follow_activity.data
655 |> Maps.put_if_present("id", activity_id)
658 #### Block-related helpers
659 @spec fetch_latest_block(User.t(), User.t()) :: Activity.t() | nil
660 def fetch_latest_block(%User{ap_id: blocker_id}, %User{ap_id: blocked_id}) do
662 |> Activity.Queries.by_type()
663 |> where(actor: ^blocker_id)
664 # this is to use the index
665 |> Activity.Queries.by_object_id(blocked_id)
666 |> order_by([activity], fragment("? desc nulls last", activity.id))
671 def make_block_data(blocker, blocked, activity_id) do
674 "actor" => blocker.ap_id,
675 "to" => [blocked.ap_id],
676 "object" => blocked.ap_id
678 |> Maps.put_if_present("id", activity_id)
681 #### Create-related helpers
683 def make_create_data(params, additional) do
684 published = params.published || make_date()
688 "to" => params.to |> Enum.uniq(),
689 "actor" => params.actor.ap_id,
690 "object" => params.object,
691 "published" => published,
692 "context" => params.context
694 |> Map.merge(additional)
697 #### Flag-related helpers
698 @spec make_flag_data(map(), map()) :: map()
699 def make_flag_data(%{actor: actor, context: context, content: content} = params, additional) do
702 "actor" => actor.ap_id,
703 "content" => content,
704 "object" => build_flag_object(params),
705 "context" => context,
708 |> Map.merge(additional)
711 def make_flag_data(_, _), do: %{}
713 defp build_flag_object(%{account: account, statuses: statuses}) do
714 [account.ap_id | build_flag_object(%{statuses: statuses})]
717 defp build_flag_object(%{statuses: statuses}) do
718 Enum.map(statuses || [], &build_flag_object/1)
721 defp build_flag_object(%Activity{data: %{"id" => id}, object: %{data: data}}) do
722 activity_actor = User.get_by_ap_id(data["actor"])
727 "content" => data["content"],
728 "published" => data["published"],
732 %{user: activity_actor, skip_visibility_check: true}
737 defp build_flag_object(act) when is_map(act) or is_binary(act) do
740 %Activity{} = act -> act.data["id"]
741 act when is_map(act) -> act["id"]
742 act when is_binary(act) -> act
745 case Activity.get_by_ap_id_with_object(id) do
746 %Activity{} = activity ->
747 build_flag_object(activity)
750 if activity = Activity.get_by_object_ap_id_with_object(id) do
751 build_flag_object(activity)
753 %{"id" => id, "deleted" => true}
758 defp build_flag_object(_), do: []
760 #### Report-related helpers
761 def get_reports(params, page, page_size) do
764 |> Map.put(:type, "Flag")
765 |> Map.put(:skip_preload, true)
766 |> Map.put(:preload_report_notes, true)
767 |> Map.put(:total, true)
768 |> Map.put(:limit, page_size)
769 |> Map.put(:offset, (page - 1) * page_size)
771 ActivityPub.fetch_activities([], params, :offset)
774 def update_report_state(%Activity{} = activity, state)
775 when state in @strip_status_report_states do
776 {:ok, stripped_activity} = strip_report_status_data(activity)
780 |> Map.put("state", state)
781 |> Map.put("object", stripped_activity.data["object"])
784 |> Changeset.change(data: new_data)
788 def update_report_state(%Activity{} = activity, state) when state in @supported_report_states do
789 new_data = Map.put(activity.data, "state", state)
792 |> Changeset.change(data: new_data)
796 def update_report_state(activity_ids, state) when state in @supported_report_states do
797 activities_num = length(activity_ids)
799 from(a in Activity, where: a.id in ^activity_ids)
800 |> update(set: [data: fragment("jsonb_set(data, '{state}', ?)", ^state)])
801 |> Repo.update_all([])
803 {^activities_num, _} -> :ok
804 _ -> {:error, activity_ids}
808 def update_report_state(_, _), do: {:error, "Unsupported state"}
810 def strip_report_status_data(activity) do
811 [actor | reported_activities] = activity.data["object"]
813 stripped_activities =
814 Enum.map(reported_activities, fn
815 act when is_map(act) -> act["id"]
816 act when is_binary(act) -> act
819 new_data = put_in(activity.data, ["object"], [actor | stripped_activities])
821 {:ok, %{activity | data: new_data}}
824 def update_activity_visibility(activity, visibility) when visibility in @valid_visibilities do
825 [to, cc, recipients] =
827 |> get_updated_targets(visibility)
828 |> Enum.map(&Enum.uniq/1)
837 |> Object.change(%{data: object_data})
838 |> Object.update_and_set_cache()
846 |> Map.put(:object, object)
847 |> Activity.change(%{data: activity_data, recipients: recipients})
851 def update_activity_visibility(_, _), do: {:error, "Unsupported visibility"}
853 defp get_updated_targets(
854 %Activity{data: %{"to" => to} = data, recipients: recipients},
857 cc = Map.get(data, "cc", [])
858 follower_address = User.get_cached_by_ap_id(data["actor"]).follower_address
859 public = Pleroma.Constants.as_public()
863 to = [public | List.delete(to, follower_address)]
864 cc = [follower_address | List.delete(cc, public)]
865 recipients = [public | recipients]
869 to = [follower_address | List.delete(to, public)]
870 cc = List.delete(cc, public)
871 recipients = List.delete(recipients, public)
875 to = [follower_address | List.delete(to, public)]
876 cc = [public | List.delete(cc, follower_address)]
877 recipients = recipients ++ [follower_address, public]
885 def get_existing_votes(actor, %{data: %{"id" => id}}) do
887 |> Activity.Queries.by_actor()
888 |> Activity.Queries.by_type("Create")
889 |> Activity.with_preloaded_object()
890 |> where([a, object: o], fragment("(?)->>'inReplyTo' = ?", o.data, ^to_string(id)))
891 |> where([a, object: o], fragment("(?)->>'type' = 'Answer'", o.data))