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 create_context(context) do
158 context = context || generate_id("contexts")
160 # Ecto has problems accessing the constraint inside the jsonb,
161 # so we explicitly check for the existed object before insert
162 object = Object.get_cached_by_ap_id(context)
164 with true <- is_nil(object),
165 changeset <- Object.context_mapping(context),
166 {:ok, inserted_object} <- Repo.insert(changeset) do
175 Enqueues an activity for federation if it's local
177 @spec maybe_federate(any()) :: :ok
178 def maybe_federate(%Activity{local: true, data: %{"type" => type}} = activity) do
179 outgoing_blocks = Config.get([:activitypub, :outgoing_blocks])
181 with true <- Config.get!([:instance, :federating]),
182 true <- type != "Block" || outgoing_blocks,
183 false <- Visibility.is_local_public?(activity) do
184 Pleroma.Web.Federator.publish(activity)
190 def maybe_federate(_), do: :ok
193 Adds an id and a published data if they aren't there,
194 also adds it to an included object
196 @spec lazy_put_activity_defaults(map(), boolean) :: map()
197 def lazy_put_activity_defaults(map, fake? \\ false)
199 def lazy_put_activity_defaults(map, true) do
201 |> Map.put_new("id", "pleroma:fakeid")
202 |> Map.put_new_lazy("published", &make_date/0)
203 |> Map.put_new("context", "pleroma:fakecontext")
204 |> Map.put_new("context_id", -1)
205 |> lazy_put_object_defaults(true)
208 def lazy_put_activity_defaults(map, _fake?) do
209 %{data: %{"id" => context}, id: context_id} = create_context(map["context"])
212 |> Map.put_new_lazy("id", &generate_activity_id/0)
213 |> Map.put_new_lazy("published", &make_date/0)
214 |> Map.put_new("context", context)
215 |> Map.put_new("context_id", context_id)
216 |> lazy_put_object_defaults(false)
219 # Adds an id and published date if they aren't there.
221 @spec lazy_put_object_defaults(map(), boolean()) :: map()
222 defp lazy_put_object_defaults(%{"object" => map} = activity, true)
226 |> Map.put_new("id", "pleroma:fake_object_id")
227 |> Map.put_new_lazy("published", &make_date/0)
228 |> Map.put_new("context", activity["context"])
229 |> Map.put_new("context_id", activity["context_id"])
230 |> Map.put_new("fake", true)
232 %{activity | "object" => object}
235 defp lazy_put_object_defaults(%{"object" => map} = activity, _)
239 |> Map.put_new_lazy("id", &generate_object_id/0)
240 |> Map.put_new_lazy("published", &make_date/0)
241 |> Map.put_new("context", activity["context"])
242 |> Map.put_new("context_id", activity["context_id"])
244 %{activity | "object" => object}
247 defp lazy_put_object_defaults(activity, _), do: activity
250 Inserts a full object if it is contained in an activity.
252 def insert_full_object(%{"object" => %{"type" => type} = object_data} = map)
253 when type in @supported_object_types do
254 with {:ok, object} <- Object.create(object_data) do
255 map = Map.put(map, "object", object.data["id"])
261 def insert_full_object(map), do: {:ok, map, nil}
263 #### Like-related helpers
266 Returns an existing like if a user already liked an object
268 @spec get_existing_like(String.t(), map()) :: Activity.t() | nil
269 def get_existing_like(actor, %{data: %{"id" => id}}) do
271 |> Activity.Queries.by_actor()
272 |> Activity.Queries.by_object_id(id)
273 |> Activity.Queries.by_type("Like")
279 Returns like activities targeting an object
281 def get_object_likes(%{data: %{"id" => id}}) do
283 |> Activity.Queries.by_object_id()
284 |> Activity.Queries.by_type("Like")
288 @spec make_like_data(User.t(), map(), String.t()) :: map()
290 %User{ap_id: ap_id} = actor,
291 %{data: %{"actor" => object_actor_id, "id" => id}} = object,
294 object_actor = User.get_cached_by_ap_id(object_actor_id)
297 if Visibility.is_public?(object) do
298 [actor.follower_address, object.data["actor"]]
300 [object.data["actor"]]
304 (object.data["to"] ++ (object.data["cc"] || []))
305 |> List.delete(actor.ap_id)
306 |> List.delete(object_actor.follower_address)
314 "context" => object.data["context"]
316 |> Maps.put_if_present("id", activity_id)
319 def make_emoji_reaction_data(user, object, emoji, activity_id) do
320 make_like_data(user, object, activity_id)
321 |> Map.put("type", "EmojiReact")
322 |> Map.put("content", emoji)
325 @spec update_element_in_object(String.t(), list(any), Object.t(), integer() | nil) ::
326 {:ok, Object.t()} | {:error, Ecto.Changeset.t()}
327 def update_element_in_object(property, element, object, count \\ nil) do
335 %{"#{property}_count" => length, "#{property}s" => element}
339 |> Changeset.change(data: data)
340 |> Object.update_and_set_cache()
343 @spec add_emoji_reaction_to_object(Activity.t(), Object.t()) ::
344 {:ok, Object.t()} | {:error, Ecto.Changeset.t()}
346 def add_emoji_reaction_to_object(
347 %Activity{data: %{"content" => emoji, "actor" => actor}} = activity,
350 reactions = get_cached_emoji_reactions(object)
351 emoji = stripped_emoji_name(emoji)
352 url = emoji_url(emoji, activity)
355 case Enum.find_index(reactions, fn [candidate, _, candidate_url] ->
356 if is_nil(candidate_url) do
363 reactions ++ [[emoji, [actor], url]]
369 fn [emoji, users, url] -> [emoji, Enum.uniq([actor | users]), url] end
373 count = emoji_count(new_reactions)
375 update_element_in_object("reaction", new_reactions, object, count)
378 defp stripped_emoji_name(name) do
380 |> String.replace_leading(":", "")
381 |> String.replace_trailing(":", "")
389 %{"type" => "Emoji", "name" => name, "icon" => %{"url" => url}}
396 defp emoji_url(_, _), do: nil
398 def emoji_count(reactions_list) do
399 Enum.reduce(reactions_list, 0, fn [_, users, _], acc -> acc + length(users) end)
402 def remove_emoji_reaction_from_object(
403 %Activity{data: %{"content" => emoji, "actor" => actor}} = activity,
406 emoji = stripped_emoji_name(emoji)
407 reactions = get_cached_emoji_reactions(object)
408 url = emoji_url(emoji, activity)
411 case Enum.find_index(reactions, fn [candidate, _, candidate_url] ->
412 if is_nil(candidate_url) do
425 fn [emoji, users, url] -> [emoji, List.delete(users, actor), url] end
427 |> Enum.reject(fn [_, users, _] -> Enum.empty?(users) end)
430 count = emoji_count(new_reactions)
431 update_element_in_object("reaction", new_reactions, object, count)
434 def get_cached_emoji_reactions(object) do
435 if is_list(object.data["reactions"]) do
436 object.data["reactions"]
442 @spec add_like_to_object(Activity.t(), Object.t()) ::
443 {:ok, Object.t()} | {:error, Ecto.Changeset.t()}
444 def add_like_to_object(%Activity{data: %{"actor" => actor}}, object) do
445 [actor | fetch_likes(object)]
447 |> update_likes_in_object(object)
450 @spec remove_like_from_object(Activity.t(), Object.t()) ::
451 {:ok, Object.t()} | {:error, Ecto.Changeset.t()}
452 def remove_like_from_object(%Activity{data: %{"actor" => actor}}, object) do
455 |> List.delete(actor)
456 |> update_likes_in_object(object)
459 defp update_likes_in_object(likes, object) do
460 update_element_in_object("like", likes, object)
463 defp fetch_likes(object) do
464 if is_list(object.data["likes"]) do
471 #### Follow-related helpers
474 Updates a follow activity's state (for locked accounts).
476 @spec update_follow_state_for_all(Activity.t(), String.t()) :: {:ok, Activity | nil}
477 def update_follow_state_for_all(
478 %Activity{data: %{"actor" => actor, "object" => object}} = activity,
482 |> Activity.Queries.by_type()
483 |> Activity.Queries.by_actor(actor)
484 |> Activity.Queries.by_object_id(object)
485 |> where(fragment("data->>'state' = 'pending'") or fragment("data->>'state' = 'accept'"))
486 |> update(set: [data: fragment("jsonb_set(data, '{state}', ?)", ^state)])
487 |> Repo.update_all([])
489 activity = Activity.get_by_id(activity.id)
494 def update_follow_state(
495 %Activity{} = activity,
498 new_data = Map.put(activity.data, "state", state)
499 changeset = Changeset.change(activity, data: new_data)
501 with {:ok, activity} <- Repo.update(changeset) do
507 Makes a follow activity data for the given follower and followed
509 def make_follow_data(
510 %User{ap_id: follower_id},
511 %User{ap_id: followed_id} = _followed,
516 "actor" => follower_id,
517 "to" => [followed_id],
518 "cc" => [Pleroma.Constants.as_public()],
519 "object" => followed_id,
522 |> Maps.put_if_present("id", activity_id)
525 def fetch_latest_follow(%User{ap_id: follower_id}, %User{ap_id: followed_id}) do
527 |> Activity.Queries.by_type()
528 |> where(actor: ^follower_id)
529 # this is to use the index
530 |> Activity.Queries.by_object_id(followed_id)
531 |> order_by([activity], fragment("? desc nulls last", activity.id))
536 def fetch_latest_undo(%User{ap_id: ap_id}) do
538 |> Activity.Queries.by_type()
539 |> where(actor: ^ap_id)
540 |> order_by([activity], fragment("? desc nulls last", activity.id))
545 def get_latest_reaction(internal_activity_id, %{ap_id: ap_id}, emoji) do
546 %{data: %{"object" => object_ap_id}} = Activity.get_by_id(internal_activity_id)
548 emoji = Pleroma.Emoji.maybe_quote(emoji)
551 |> Activity.Queries.by_type()
552 |> where(actor: ^ap_id)
553 |> where([activity], fragment("?->>'content' = ?", activity.data, ^emoji))
554 |> Activity.Queries.by_object_id(object_ap_id)
555 |> order_by([activity], fragment("? desc nulls last", activity.id))
560 #### Announce-related helpers
563 Returns an existing announce activity if the notice has already been announced
565 @spec get_existing_announce(String.t(), map()) :: Activity.t() | nil
566 def get_existing_announce(actor, %{data: %{"id" => ap_id}}) do
568 |> Activity.Queries.by_type()
569 |> where(actor: ^actor)
570 # this is to use the index
571 |> Activity.Queries.by_object_id(ap_id)
576 Make announce activity data for the given actor and object
578 # for relayed messages, we only want to send to subscribers
579 def make_announce_data(
580 %User{ap_id: ap_id} = user,
581 %Object{data: %{"id" => id}} = object,
586 "type" => "Announce",
589 "to" => [user.follower_address],
591 "context" => object.data["context"]
593 |> Maps.put_if_present("id", activity_id)
596 def make_announce_data(
597 %User{ap_id: ap_id} = user,
598 %Object{data: %{"id" => id}} = object,
603 "type" => "Announce",
606 "to" => [user.follower_address, object.data["actor"]],
607 "cc" => [Pleroma.Constants.as_public()],
608 "context" => object.data["context"]
610 |> Maps.put_if_present("id", activity_id)
614 %User{ap_id: actor, follower_address: follower_address},
616 data: %{"id" => undone_activity_id, "context" => context},
617 actor: undone_activity_actor
624 "object" => undone_activity_id,
625 "to" => [follower_address, undone_activity_actor],
626 "cc" => [Pleroma.Constants.as_public()],
629 |> Maps.put_if_present("id", activity_id)
632 @spec add_announce_to_object(Activity.t(), Object.t()) ::
633 {:ok, Object.t()} | {:error, Ecto.Changeset.t()}
634 def add_announce_to_object(
635 %Activity{data: %{"actor" => actor}},
638 unless actor |> User.get_cached_by_ap_id() |> User.invisible?() do
639 announcements = take_announcements(object)
641 with announcements <- Enum.uniq([actor | announcements]) do
642 update_element_in_object("announcement", announcements, object)
649 def add_announce_to_object(_, object), do: {:ok, object}
651 @spec remove_announce_from_object(Activity.t(), Object.t()) ::
652 {:ok, Object.t()} | {:error, Ecto.Changeset.t()}
653 def remove_announce_from_object(%Activity{data: %{"actor" => actor}}, object) do
654 with announcements <- List.delete(take_announcements(object), actor) do
655 update_element_in_object("announcement", announcements, object)
659 defp take_announcements(%{data: %{"announcements" => announcements}} = _)
660 when is_list(announcements),
663 defp take_announcements(_), do: []
665 #### Unfollow-related helpers
667 def make_unfollow_data(follower, followed, follow_activity, activity_id) do
670 "actor" => follower.ap_id,
671 "to" => [followed.ap_id],
672 "object" => follow_activity.data
674 |> Maps.put_if_present("id", activity_id)
677 #### Block-related helpers
678 @spec fetch_latest_block(User.t(), User.t()) :: Activity.t() | nil
679 def fetch_latest_block(%User{ap_id: blocker_id}, %User{ap_id: blocked_id}) do
681 |> Activity.Queries.by_type()
682 |> where(actor: ^blocker_id)
683 # this is to use the index
684 |> Activity.Queries.by_object_id(blocked_id)
685 |> order_by([activity], fragment("? desc nulls last", activity.id))
690 def make_block_data(blocker, blocked, activity_id) do
693 "actor" => blocker.ap_id,
694 "to" => [blocked.ap_id],
695 "object" => blocked.ap_id
697 |> Maps.put_if_present("id", activity_id)
700 #### Create-related helpers
702 def make_create_data(params, additional) do
703 published = params.published || make_date()
707 "to" => params.to |> Enum.uniq(),
708 "actor" => params.actor.ap_id,
709 "object" => params.object,
710 "published" => published,
711 "context" => params.context
713 |> Map.merge(additional)
716 #### Flag-related helpers
717 @spec make_flag_data(map(), map()) :: map()
718 def make_flag_data(%{actor: actor, context: context, content: content} = params, additional) do
721 "actor" => actor.ap_id,
722 "content" => content,
723 "object" => build_flag_object(params),
724 "context" => context,
727 |> Map.merge(additional)
730 def make_flag_data(_, _), do: %{}
732 defp build_flag_object(%{account: account, statuses: statuses}) do
733 [account.ap_id | build_flag_object(%{statuses: statuses})]
736 defp build_flag_object(%{statuses: statuses}) do
737 Enum.map(statuses || [], &build_flag_object/1)
740 defp build_flag_object(%Activity{data: %{"id" => id}, object: %{data: data}}) do
741 activity_actor = User.get_by_ap_id(data["actor"])
746 "content" => data["content"],
747 "published" => data["published"],
751 %{user: activity_actor, skip_visibility_check: true}
756 defp build_flag_object(act) when is_map(act) or is_binary(act) do
759 %Activity{} = act -> act.data["id"]
760 act when is_map(act) -> act["id"]
761 act when is_binary(act) -> act
764 case Activity.get_by_ap_id_with_object(id) do
765 %Activity{} = activity ->
766 build_flag_object(activity)
769 if activity = Activity.get_by_object_ap_id_with_object(id) do
770 build_flag_object(activity)
772 %{"id" => id, "deleted" => true}
777 defp build_flag_object(_), do: []
779 #### Report-related helpers
780 def get_reports(params, page, page_size) do
783 |> Map.put(:type, "Flag")
784 |> Map.put(:skip_preload, true)
785 |> Map.put(:preload_report_notes, true)
786 |> Map.put(:total, true)
787 |> Map.put(:limit, page_size)
788 |> Map.put(:offset, (page - 1) * page_size)
790 ActivityPub.fetch_activities([], params, :offset)
793 def update_report_state(%Activity{} = activity, state)
794 when state in @strip_status_report_states do
795 {:ok, stripped_activity} = strip_report_status_data(activity)
799 |> Map.put("state", state)
800 |> Map.put("object", stripped_activity.data["object"])
803 |> Changeset.change(data: new_data)
807 def update_report_state(%Activity{} = activity, state) when state in @supported_report_states do
808 new_data = Map.put(activity.data, "state", state)
811 |> Changeset.change(data: new_data)
815 def update_report_state(activity_ids, state) when state in @supported_report_states do
816 activities_num = length(activity_ids)
818 from(a in Activity, where: a.id in ^activity_ids)
819 |> update(set: [data: fragment("jsonb_set(data, '{state}', ?)", ^state)])
820 |> Repo.update_all([])
822 {^activities_num, _} -> :ok
823 _ -> {:error, activity_ids}
827 def update_report_state(_, _), do: {:error, "Unsupported state"}
829 def strip_report_status_data(activity) do
830 [actor | reported_activities] = activity.data["object"]
832 stripped_activities =
833 Enum.map(reported_activities, fn
834 act when is_map(act) -> act["id"]
835 act when is_binary(act) -> act
838 new_data = put_in(activity.data, ["object"], [actor | stripped_activities])
840 {:ok, %{activity | data: new_data}}
843 def update_activity_visibility(activity, visibility) when visibility in @valid_visibilities do
844 [to, cc, recipients] =
846 |> get_updated_targets(visibility)
847 |> Enum.map(&Enum.uniq/1)
856 |> Object.change(%{data: object_data})
857 |> Object.update_and_set_cache()
865 |> Map.put(:object, object)
866 |> Activity.change(%{data: activity_data, recipients: recipients})
870 def update_activity_visibility(_, _), do: {:error, "Unsupported visibility"}
872 defp get_updated_targets(
873 %Activity{data: %{"to" => to} = data, recipients: recipients},
876 cc = Map.get(data, "cc", [])
877 follower_address = User.get_cached_by_ap_id(data["actor"]).follower_address
878 public = Pleroma.Constants.as_public()
882 to = [public | List.delete(to, follower_address)]
883 cc = [follower_address | List.delete(cc, public)]
884 recipients = [public | recipients]
888 to = [follower_address | List.delete(to, public)]
889 cc = List.delete(cc, public)
890 recipients = List.delete(recipients, public)
894 to = [follower_address | List.delete(to, public)]
895 cc = [public | List.delete(cc, follower_address)]
896 recipients = recipients ++ [follower_address, public]
904 def get_existing_votes(actor, %{data: %{"id" => id}}) do
906 |> Activity.Queries.by_actor()
907 |> Activity.Queries.by_type("Create")
908 |> Activity.with_preloaded_object()
909 |> where([a, object: o], fragment("(?)->>'inReplyTo' = ?", o.data, ^to_string(id)))
910 |> where([a, object: o], fragment("(?)->>'type' = 'Answer'", o.data))