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
16 alias Pleroma.Web.ActivityPub.ActivityPub
17 alias Pleroma.Web.ActivityPub.Visibility
18 alias Pleroma.Web.AdminAPI.AccountView
19 alias Pleroma.Web.Endpoint
20 alias Pleroma.Web.Router.Helpers
25 require Pleroma.Constants
27 @supported_object_types [
37 @strip_status_report_states ~w(closed resolved)
38 @supported_report_states ~w(open closed resolved)
39 @valid_visibilities ~w(public unlisted private direct)
41 # Some implementations send the actor URI as the actor field, others send the entire actor object,
42 # so figure out what the actor's URI is based on what we have.
43 def get_ap_id(%{"id" => id} = _), do: id
44 def get_ap_id(id), do: id
46 def normalize_params(params) do
47 Map.put(params, "actor", get_ap_id(params["actor"]))
50 @spec determine_explicit_mentions(map()) :: [any]
51 def determine_explicit_mentions(%{"tag" => tag}) when is_list(tag) do
53 %{"type" => "Mention", "href" => href} -> [href]
58 def determine_explicit_mentions(%{"tag" => tag} = object) when is_map(tag) do
60 |> Map.put("tag", [tag])
61 |> determine_explicit_mentions()
64 def determine_explicit_mentions(_), do: []
66 @spec label_in_collection?(any(), any()) :: boolean()
67 defp label_in_collection?(ap_id, coll) when is_binary(coll), do: ap_id == coll
68 defp label_in_collection?(ap_id, coll) when is_list(coll), do: ap_id in coll
69 defp label_in_collection?(_, _), do: false
71 @spec label_in_message?(String.t(), map()) :: boolean()
72 def label_in_message?(label, params),
74 [params["to"], params["cc"], params["bto"], params["bcc"]]
75 |> Enum.any?(&label_in_collection?(label, &1))
77 @spec unaddressed_message?(map()) :: boolean()
78 def unaddressed_message?(params),
80 [params["to"], params["cc"], params["bto"], params["bcc"]]
81 |> Enum.all?(&is_nil(&1))
83 @spec recipient_in_message(User.t(), User.t(), map()) :: boolean()
84 def recipient_in_message(%User{ap_id: ap_id} = recipient, %User{} = actor, params),
86 label_in_message?(ap_id, params) || unaddressed_message?(params) ||
87 User.following?(recipient, actor)
89 defp extract_list(target) when is_binary(target), do: [target]
90 defp extract_list(lst) when is_list(lst), do: lst
91 defp extract_list(_), do: []
93 def maybe_splice_recipient(ap_id, params) do
95 !label_in_collection?(ap_id, params["to"]) &&
96 !label_in_collection?(ap_id, params["cc"])
99 cc = [ap_id | extract_list(params["cc"])]
103 |> Maps.safe_put_in(["object", "cc"], cc)
109 def make_json_ld_header do
112 "https://www.w3.org/ns/activitystreams",
113 "#{Web.base_url()}/schemas/litepub-0.1.jsonld",
122 DateTime.utc_now() |> DateTime.to_iso8601()
125 def generate_activity_id do
126 generate_id("activities")
129 def generate_context_id do
130 generate_id("contexts")
133 def generate_object_id do
134 Helpers.o_status_url(Endpoint, :object, UUID.generate())
137 def generate_id(type) do
138 "#{Web.base_url()}/#{type}/#{UUID.generate()}"
141 def get_notified_from_object(%{"type" => type} = object) when type in @supported_object_types do
142 fake_create_activity = %{
143 "to" => object["to"],
144 "cc" => object["cc"],
149 get_notified_from_object(fake_create_activity)
152 def get_notified_from_object(object) do
153 Notification.get_notified_from_activity(%Activity{data: object}, false)
156 def create_context(context) do
157 context = context || generate_id("contexts")
159 # Ecto has problems accessing the constraint inside the jsonb,
160 # so we explicitly check for the existed object before insert
161 object = Object.get_cached_by_ap_id(context)
163 with true <- is_nil(object),
164 changeset <- Object.context_mapping(context),
165 {:ok, inserted_object} <- Repo.insert(changeset) do
174 Enqueues an activity for federation if it's local
176 @spec maybe_federate(any()) :: :ok
177 def maybe_federate(%Activity{local: true, data: %{"type" => type}} = activity) do
178 outgoing_blocks = Config.get([:activitypub, :outgoing_blocks])
180 with true <- Config.get!([:instance, :federating]),
181 true <- type != "Block" || outgoing_blocks,
182 false <- Visibility.is_local_public?(activity) do
183 Pleroma.Web.Federator.publish(activity)
189 def maybe_federate(_), do: :ok
192 Adds an id and a published data if they aren't there,
193 also adds it to an included object
195 @spec lazy_put_activity_defaults(map(), boolean) :: map()
196 def lazy_put_activity_defaults(map, fake? \\ false)
198 def lazy_put_activity_defaults(map, true) do
200 |> Map.put_new("id", "pleroma:fakeid")
201 |> Map.put_new_lazy("published", &make_date/0)
202 |> Map.put_new("context", "pleroma:fakecontext")
203 |> Map.put_new("context_id", -1)
204 |> lazy_put_object_defaults(true)
207 def lazy_put_activity_defaults(map, _fake?) do
208 %{data: %{"id" => context}, id: context_id} = create_context(map["context"])
211 |> Map.put_new_lazy("id", &generate_activity_id/0)
212 |> Map.put_new_lazy("published", &make_date/0)
213 |> Map.put_new("context", context)
214 |> Map.put_new("context_id", context_id)
215 |> lazy_put_object_defaults(false)
218 # Adds an id and published date if they aren't there.
220 @spec lazy_put_object_defaults(map(), boolean()) :: map()
221 defp lazy_put_object_defaults(%{"object" => map} = activity, true)
225 |> Map.put_new("id", "pleroma:fake_object_id")
226 |> Map.put_new_lazy("published", &make_date/0)
227 |> Map.put_new("context", activity["context"])
228 |> Map.put_new("context_id", activity["context_id"])
229 |> Map.put_new("fake", true)
231 %{activity | "object" => object}
234 defp lazy_put_object_defaults(%{"object" => map} = activity, _)
238 |> Map.put_new_lazy("id", &generate_object_id/0)
239 |> Map.put_new_lazy("published", &make_date/0)
240 |> Map.put_new("context", activity["context"])
241 |> Map.put_new("context_id", activity["context_id"])
243 %{activity | "object" => object}
246 defp lazy_put_object_defaults(activity, _), do: activity
249 Inserts a full object if it is contained in an activity.
251 def insert_full_object(%{"object" => %{"type" => type} = object_data} = map)
252 when type in @supported_object_types do
253 with {:ok, object} <- Object.create(object_data) do
254 map = Map.put(map, "object", object.data["id"])
260 def insert_full_object(map), do: {:ok, map, nil}
262 #### Like-related helpers
265 Returns an existing like if a user already liked an object
267 @spec get_existing_like(String.t(), map()) :: Activity.t() | nil
268 def get_existing_like(actor, %{data: %{"id" => id}}) do
270 |> Activity.Queries.by_actor()
271 |> Activity.Queries.by_object_id(id)
272 |> Activity.Queries.by_type("Like")
278 Returns like activities targeting an object
280 def get_object_likes(%{data: %{"id" => id}}) do
282 |> Activity.Queries.by_object_id()
283 |> Activity.Queries.by_type("Like")
287 @spec make_like_data(User.t(), map(), String.t()) :: map()
289 %User{ap_id: ap_id} = actor,
290 %{data: %{"actor" => object_actor_id, "id" => id}} = object,
293 object_actor = User.get_cached_by_ap_id(object_actor_id)
296 if Visibility.is_public?(object) do
297 [actor.follower_address, object.data["actor"]]
299 [object.data["actor"]]
303 (object.data["to"] ++ (object.data["cc"] || []))
304 |> List.delete(actor.ap_id)
305 |> List.delete(object_actor.follower_address)
313 "context" => object.data["context"]
315 |> Maps.put_if_present("id", activity_id)
318 def make_emoji_reaction_data(user, object, emoji, activity_id) do
319 make_like_data(user, object, activity_id)
320 |> Map.put("type", "EmojiReact")
321 |> Map.put("content", emoji)
324 @spec update_element_in_object(String.t(), list(any), Object.t(), integer() | nil) ::
325 {:ok, Object.t()} | {:error, Ecto.Changeset.t()}
326 def update_element_in_object(property, element, object, count \\ nil) do
334 %{"#{property}_count" => length, "#{property}s" => element}
338 |> Changeset.change(data: data)
339 |> Object.update_and_set_cache()
342 @spec add_emoji_reaction_to_object(Activity.t(), Object.t()) ::
343 {:ok, Object.t()} | {:error, Ecto.Changeset.t()}
345 def add_emoji_reaction_to_object(
346 %Activity{data: %{"content" => emoji, "actor" => actor}},
349 reactions = get_cached_emoji_reactions(object)
352 case Enum.find_index(reactions, fn [candidate, _] -> emoji == candidate end) do
354 reactions ++ [[emoji, [actor]]]
360 fn [emoji, users] -> [emoji, Enum.uniq([actor | users])] end
364 count = emoji_count(new_reactions)
366 update_element_in_object("reaction", new_reactions, object, count)
369 def emoji_count(reactions_list) do
370 Enum.reduce(reactions_list, 0, fn [_, users], acc -> acc + length(users) end)
373 def remove_emoji_reaction_from_object(
374 %Activity{data: %{"content" => emoji, "actor" => actor}},
377 reactions = get_cached_emoji_reactions(object)
380 case Enum.find_index(reactions, fn [candidate, _] -> emoji == candidate end) do
388 fn [emoji, users] -> [emoji, List.delete(users, actor)] end
390 |> Enum.reject(fn [_, users] -> Enum.empty?(users) end)
393 count = emoji_count(new_reactions)
394 update_element_in_object("reaction", new_reactions, object, count)
397 def get_cached_emoji_reactions(object) do
398 if is_list(object.data["reactions"]) do
399 object.data["reactions"]
405 @spec add_like_to_object(Activity.t(), Object.t()) ::
406 {:ok, Object.t()} | {:error, Ecto.Changeset.t()}
407 def add_like_to_object(%Activity{data: %{"actor" => actor}}, object) do
408 [actor | fetch_likes(object)]
410 |> update_likes_in_object(object)
413 @spec remove_like_from_object(Activity.t(), Object.t()) ::
414 {:ok, Object.t()} | {:error, Ecto.Changeset.t()}
415 def remove_like_from_object(%Activity{data: %{"actor" => actor}}, object) do
418 |> List.delete(actor)
419 |> update_likes_in_object(object)
422 defp update_likes_in_object(likes, object) do
423 update_element_in_object("like", likes, object)
426 defp fetch_likes(object) do
427 if is_list(object.data["likes"]) do
434 #### Follow-related helpers
437 Updates a follow activity's state (for locked accounts).
439 @spec update_follow_state_for_all(Activity.t(), String.t()) :: {:ok, Activity | nil}
440 def update_follow_state_for_all(
441 %Activity{data: %{"actor" => actor, "object" => object}} = activity,
445 |> Activity.Queries.by_type()
446 |> Activity.Queries.by_actor(actor)
447 |> Activity.Queries.by_object_id(object)
448 |> where(fragment("data->>'state' = 'pending'"))
449 |> update(set: [data: fragment("jsonb_set(data, '{state}', ?)", ^state)])
450 |> Repo.update_all([])
452 activity = Activity.get_by_id(activity.id)
457 def update_follow_state(
458 %Activity{} = activity,
461 new_data = Map.put(activity.data, "state", state)
462 changeset = Changeset.change(activity, data: new_data)
464 with {:ok, activity} <- Repo.update(changeset) do
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)
512 |> Activity.Queries.by_type()
513 |> where(actor: ^ap_id)
514 |> where([activity], fragment("?->>'content' = ?", activity.data, ^emoji))
515 |> Activity.Queries.by_object_id(object_ap_id)
516 |> order_by([activity], fragment("? desc nulls last", activity.id))
521 #### Announce-related helpers
524 Returns an existing announce activity if the notice has already been announced
526 @spec get_existing_announce(String.t(), map()) :: Activity.t() | nil
527 def get_existing_announce(actor, %{data: %{"id" => ap_id}}) do
529 |> Activity.Queries.by_type()
530 |> where(actor: ^actor)
531 # this is to use the index
532 |> Activity.Queries.by_object_id(ap_id)
537 Make announce activity data for the given actor and object
539 # for relayed messages, we only want to send to subscribers
540 def make_announce_data(
541 %User{ap_id: ap_id} = user,
542 %Object{data: %{"id" => id}} = object,
547 "type" => "Announce",
550 "to" => [user.follower_address],
552 "context" => object.data["context"]
554 |> Maps.put_if_present("id", activity_id)
557 def make_announce_data(
558 %User{ap_id: ap_id} = user,
559 %Object{data: %{"id" => id}} = object,
564 "type" => "Announce",
567 "to" => [user.follower_address, object.data["actor"]],
568 "cc" => [Pleroma.Constants.as_public()],
569 "context" => object.data["context"]
571 |> Maps.put_if_present("id", activity_id)
575 %User{ap_id: actor, follower_address: follower_address},
577 data: %{"id" => undone_activity_id, "context" => context},
578 actor: undone_activity_actor
585 "object" => undone_activity_id,
586 "to" => [follower_address, undone_activity_actor],
587 "cc" => [Pleroma.Constants.as_public()],
590 |> Maps.put_if_present("id", activity_id)
593 @spec add_announce_to_object(Activity.t(), Object.t()) ::
594 {:ok, Object.t()} | {:error, Ecto.Changeset.t()}
595 def add_announce_to_object(
596 %Activity{data: %{"actor" => actor}},
599 unless actor |> User.get_cached_by_ap_id() |> User.invisible?() do
600 announcements = take_announcements(object)
602 with announcements <- Enum.uniq([actor | announcements]) do
603 update_element_in_object("announcement", announcements, object)
610 def add_announce_to_object(_, object), do: {:ok, object}
612 @spec remove_announce_from_object(Activity.t(), Object.t()) ::
613 {:ok, Object.t()} | {:error, Ecto.Changeset.t()}
614 def remove_announce_from_object(%Activity{data: %{"actor" => actor}}, object) do
615 with announcements <- List.delete(take_announcements(object), actor) do
616 update_element_in_object("announcement", announcements, object)
620 defp take_announcements(%{data: %{"announcements" => announcements}} = _)
621 when is_list(announcements),
624 defp take_announcements(_), do: []
626 #### Unfollow-related helpers
628 def make_unfollow_data(follower, followed, follow_activity, activity_id) do
631 "actor" => follower.ap_id,
632 "to" => [followed.ap_id],
633 "object" => follow_activity.data
635 |> Maps.put_if_present("id", activity_id)
638 #### Block-related helpers
639 @spec fetch_latest_block(User.t(), User.t()) :: Activity.t() | nil
640 def fetch_latest_block(%User{ap_id: blocker_id}, %User{ap_id: blocked_id}) do
642 |> Activity.Queries.by_type()
643 |> where(actor: ^blocker_id)
644 # this is to use the index
645 |> Activity.Queries.by_object_id(blocked_id)
646 |> order_by([activity], fragment("? desc nulls last", activity.id))
651 def make_block_data(blocker, blocked, activity_id) do
654 "actor" => blocker.ap_id,
655 "to" => [blocked.ap_id],
656 "object" => blocked.ap_id
658 |> Maps.put_if_present("id", activity_id)
661 #### Create-related helpers
663 def make_create_data(params, additional) do
664 published = params.published || make_date()
668 "to" => params.to |> Enum.uniq(),
669 "actor" => params.actor.ap_id,
670 "object" => params.object,
671 "published" => published,
672 "context" => params.context
674 |> Map.merge(additional)
677 #### Listen-related helpers
678 def make_listen_data(params, additional) do
679 published = params.published || make_date()
683 "to" => params.to |> Enum.uniq(),
684 "actor" => params.actor.ap_id,
685 "object" => params.object,
686 "published" => published,
687 "context" => params.context
689 |> Map.merge(additional)
692 #### Flag-related helpers
693 @spec make_flag_data(map(), map()) :: map()
694 def make_flag_data(%{actor: actor, context: context, content: content} = params, additional) do
697 "actor" => actor.ap_id,
698 "content" => content,
699 "object" => build_flag_object(params),
700 "context" => context,
703 |> Map.merge(additional)
706 def make_flag_data(_, _), do: %{}
708 defp build_flag_object(%{account: account, statuses: statuses}) do
709 [account.ap_id | build_flag_object(%{statuses: statuses})]
712 defp build_flag_object(%{statuses: statuses}) do
713 Enum.map(statuses || [], &build_flag_object/1)
716 defp build_flag_object(%Activity{data: %{"id" => id}, object: %{data: data}}) do
717 activity_actor = User.get_by_ap_id(data["actor"])
722 "content" => data["content"],
723 "published" => data["published"],
727 %{user: activity_actor, skip_visibility_check: true}
732 defp build_flag_object(act) when is_map(act) or is_binary(act) do
735 %Activity{} = act -> act.data["id"]
736 act when is_map(act) -> act["id"]
737 act when is_binary(act) -> act
740 case Activity.get_by_ap_id_with_object(id) do
741 %Activity{} = activity ->
742 build_flag_object(activity)
745 if activity = Activity.get_by_object_ap_id_with_object(id) do
746 build_flag_object(activity)
748 %{"id" => id, "deleted" => true}
753 defp build_flag_object(_), do: []
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 def update_report_state(%Activity{} = activity, state)
770 when state in @strip_status_report_states do
771 {:ok, stripped_activity} = strip_report_status_data(activity)
775 |> Map.put("state", state)
776 |> Map.put("object", stripped_activity.data["object"])
779 |> Changeset.change(data: new_data)
783 def update_report_state(%Activity{} = activity, state) when state in @supported_report_states do
784 new_data = Map.put(activity.data, "state", state)
787 |> Changeset.change(data: new_data)
791 def update_report_state(activity_ids, state) when state in @supported_report_states do
792 activities_num = length(activity_ids)
794 from(a in Activity, where: a.id in ^activity_ids)
795 |> update(set: [data: fragment("jsonb_set(data, '{state}', ?)", ^state)])
796 |> Repo.update_all([])
798 {^activities_num, _} -> :ok
799 _ -> {:error, activity_ids}
803 def update_report_state(_, _), do: {:error, "Unsupported state"}
805 def strip_report_status_data(activity) do
806 [actor | reported_activities] = activity.data["object"]
808 stripped_activities =
809 Enum.map(reported_activities, fn
810 act when is_map(act) -> act["id"]
811 act when is_binary(act) -> act
814 new_data = put_in(activity.data, ["object"], [actor | stripped_activities])
816 {:ok, %{activity | data: new_data}}
819 def update_activity_visibility(activity, visibility) when visibility in @valid_visibilities do
820 [to, cc, recipients] =
822 |> get_updated_targets(visibility)
823 |> Enum.map(&Enum.uniq/1)
832 |> Object.change(%{data: object_data})
833 |> Object.update_and_set_cache()
841 |> Map.put(:object, object)
842 |> Activity.change(%{data: activity_data, recipients: recipients})
846 def update_activity_visibility(_, _), do: {:error, "Unsupported visibility"}
848 defp get_updated_targets(
849 %Activity{data: %{"to" => to} = data, recipients: recipients},
852 cc = Map.get(data, "cc", [])
853 follower_address = User.get_cached_by_ap_id(data["actor"]).follower_address
854 public = Pleroma.Constants.as_public()
858 to = [public | List.delete(to, follower_address)]
859 cc = [follower_address | List.delete(cc, public)]
860 recipients = [public | recipients]
864 to = [follower_address | List.delete(to, public)]
865 cc = List.delete(cc, public)
866 recipients = List.delete(recipients, public)
870 to = [follower_address | List.delete(to, public)]
871 cc = [public | List.delete(cc, follower_address)]
872 recipients = recipients ++ [follower_address, public]
880 def get_existing_votes(actor, %{data: %{"id" => id}}) do
882 |> Activity.Queries.by_actor()
883 |> Activity.Queries.by_type("Create")
884 |> Activity.with_preloaded_object()
885 |> where([a, object: o], fragment("(?)->>'inReplyTo' = ?", o.data, ^to_string(id)))
886 |> where([a, object: o], fragment("(?)->>'type' = 'Answer'", o.data))