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_list = extract_list(params["cc"])
100 Map.put(params, "cc", [ap_id | cc_list])
106 def make_json_ld_header do
109 "https://www.w3.org/ns/activitystreams",
110 "#{Web.base_url()}/schemas/litepub-0.1.jsonld",
119 DateTime.utc_now() |> DateTime.to_iso8601()
122 def generate_activity_id do
123 generate_id("activities")
126 def generate_context_id do
127 generate_id("contexts")
130 def generate_object_id do
131 Helpers.o_status_url(Endpoint, :object, UUID.generate())
134 def generate_id(type) do
135 "#{Web.base_url()}/#{type}/#{UUID.generate()}"
138 def get_notified_from_object(%{"type" => type} = object) when type in @supported_object_types do
139 fake_create_activity = %{
140 "to" => object["to"],
141 "cc" => object["cc"],
146 get_notified_from_object(fake_create_activity)
149 def get_notified_from_object(object) do
150 Notification.get_notified_from_activity(%Activity{data: object}, false)
153 def create_context(context) do
154 context = context || generate_id("contexts")
156 # Ecto has problems accessing the constraint inside the jsonb,
157 # so we explicitly check for the existed object before insert
158 object = Object.get_cached_by_ap_id(context)
160 with true <- is_nil(object),
161 changeset <- Object.context_mapping(context),
162 {:ok, inserted_object} <- Repo.insert(changeset) do
171 Enqueues an activity for federation if it's local
173 @spec maybe_federate(any()) :: :ok
174 def maybe_federate(%Activity{local: true, data: %{"type" => type}} = activity) do
175 outgoing_blocks = Config.get([:activitypub, :outgoing_blocks])
177 with true <- Config.get!([:instance, :federating]),
178 true <- type != "Block" || outgoing_blocks,
179 false <- Visibility.is_local_public?(activity) do
180 Pleroma.Web.Federator.publish(activity)
186 def maybe_federate(_), do: :ok
189 Adds an id and a published data if they aren't there,
190 also adds it to an included object
192 @spec lazy_put_activity_defaults(map(), boolean) :: map()
193 def lazy_put_activity_defaults(map, fake? \\ false)
195 def lazy_put_activity_defaults(map, true) do
197 |> Map.put_new("id", "pleroma:fakeid")
198 |> Map.put_new_lazy("published", &make_date/0)
199 |> Map.put_new("context", "pleroma:fakecontext")
200 |> Map.put_new("context_id", -1)
201 |> lazy_put_object_defaults(true)
204 def lazy_put_activity_defaults(map, _fake?) do
205 %{data: %{"id" => context}, id: context_id} = create_context(map["context"])
208 |> Map.put_new_lazy("id", &generate_activity_id/0)
209 |> Map.put_new_lazy("published", &make_date/0)
210 |> Map.put_new("context", context)
211 |> Map.put_new("context_id", context_id)
212 |> lazy_put_object_defaults(false)
215 # Adds an id and published date if they aren't there.
217 @spec lazy_put_object_defaults(map(), boolean()) :: map()
218 defp lazy_put_object_defaults(%{"object" => map} = activity, true)
222 |> Map.put_new("id", "pleroma:fake_object_id")
223 |> Map.put_new_lazy("published", &make_date/0)
224 |> Map.put_new("context", activity["context"])
225 |> Map.put_new("context_id", activity["context_id"])
226 |> Map.put_new("fake", true)
228 %{activity | "object" => object}
231 defp lazy_put_object_defaults(%{"object" => map} = activity, _)
235 |> Map.put_new_lazy("id", &generate_object_id/0)
236 |> Map.put_new_lazy("published", &make_date/0)
237 |> Map.put_new("context", activity["context"])
238 |> Map.put_new("context_id", activity["context_id"])
240 %{activity | "object" => object}
243 defp lazy_put_object_defaults(activity, _), do: activity
246 Inserts a full object if it is contained in an activity.
248 def insert_full_object(%{"object" => %{"type" => type} = object_data} = map)
249 when type in @supported_object_types do
250 with {:ok, object} <- Object.create(object_data) do
251 map = Map.put(map, "object", object.data["id"])
257 def insert_full_object(map), do: {:ok, map, nil}
259 #### Like-related helpers
262 Returns an existing like if a user already liked an object
264 @spec get_existing_like(String.t(), map()) :: Activity.t() | nil
265 def get_existing_like(actor, %{data: %{"id" => id}}) do
267 |> Activity.Queries.by_actor()
268 |> Activity.Queries.by_object_id(id)
269 |> Activity.Queries.by_type("Like")
275 Returns like activities targeting an object
277 def get_object_likes(%{data: %{"id" => id}}) do
279 |> Activity.Queries.by_object_id()
280 |> Activity.Queries.by_type("Like")
284 @spec make_like_data(User.t(), map(), String.t()) :: map()
286 %User{ap_id: ap_id} = actor,
287 %{data: %{"actor" => object_actor_id, "id" => id}} = object,
290 object_actor = User.get_cached_by_ap_id(object_actor_id)
293 if Visibility.is_public?(object) do
294 [actor.follower_address, object.data["actor"]]
296 [object.data["actor"]]
300 (object.data["to"] ++ (object.data["cc"] || []))
301 |> List.delete(actor.ap_id)
302 |> List.delete(object_actor.follower_address)
310 "context" => object.data["context"]
312 |> Maps.put_if_present("id", activity_id)
315 def make_emoji_reaction_data(user, object, emoji, activity_id) do
316 make_like_data(user, object, activity_id)
317 |> Map.put("type", "EmojiReact")
318 |> Map.put("content", emoji)
321 @spec update_element_in_object(String.t(), list(any), Object.t(), integer() | nil) ::
322 {:ok, Object.t()} | {:error, Ecto.Changeset.t()}
323 def update_element_in_object(property, element, object, count \\ nil) do
331 %{"#{property}_count" => length, "#{property}s" => element}
335 |> Changeset.change(data: data)
336 |> Object.update_and_set_cache()
339 @spec add_emoji_reaction_to_object(Activity.t(), Object.t()) ::
340 {:ok, Object.t()} | {:error, Ecto.Changeset.t()}
342 def add_emoji_reaction_to_object(
343 %Activity{data: %{"content" => emoji, "actor" => actor}},
346 reactions = get_cached_emoji_reactions(object)
349 case Enum.find_index(reactions, fn [candidate, _] -> emoji == candidate end) do
351 reactions ++ [[emoji, [actor]]]
357 fn [emoji, users] -> [emoji, Enum.uniq([actor | users])] end
361 count = emoji_count(new_reactions)
363 update_element_in_object("reaction", new_reactions, object, count)
366 def emoji_count(reactions_list) do
367 Enum.reduce(reactions_list, 0, fn [_, users], acc -> acc + length(users) end)
370 def remove_emoji_reaction_from_object(
371 %Activity{data: %{"content" => emoji, "actor" => actor}},
374 reactions = get_cached_emoji_reactions(object)
377 case Enum.find_index(reactions, fn [candidate, _] -> emoji == candidate end) do
385 fn [emoji, users] -> [emoji, List.delete(users, actor)] end
387 |> Enum.reject(fn [_, users] -> Enum.empty?(users) end)
390 count = emoji_count(new_reactions)
391 update_element_in_object("reaction", new_reactions, object, count)
394 def get_cached_emoji_reactions(object) do
395 if is_list(object.data["reactions"]) do
396 object.data["reactions"]
402 @spec add_like_to_object(Activity.t(), Object.t()) ::
403 {:ok, Object.t()} | {:error, Ecto.Changeset.t()}
404 def add_like_to_object(%Activity{data: %{"actor" => actor}}, object) do
405 [actor | fetch_likes(object)]
407 |> update_likes_in_object(object)
410 @spec remove_like_from_object(Activity.t(), Object.t()) ::
411 {:ok, Object.t()} | {:error, Ecto.Changeset.t()}
412 def remove_like_from_object(%Activity{data: %{"actor" => actor}}, object) do
415 |> List.delete(actor)
416 |> update_likes_in_object(object)
419 defp update_likes_in_object(likes, object) do
420 update_element_in_object("like", likes, object)
423 defp fetch_likes(object) do
424 if is_list(object.data["likes"]) do
431 #### Follow-related helpers
434 Updates a follow activity's state (for locked accounts).
436 @spec update_follow_state_for_all(Activity.t(), String.t()) :: {:ok, Activity | nil}
437 def update_follow_state_for_all(
438 %Activity{data: %{"actor" => actor, "object" => object}} = activity,
442 |> Activity.Queries.by_type()
443 |> Activity.Queries.by_actor(actor)
444 |> Activity.Queries.by_object_id(object)
445 |> where(fragment("data->>'state' = 'pending'"))
446 |> update(set: [data: fragment("jsonb_set(data, '{state}', ?)", ^state)])
447 |> Repo.update_all([])
449 activity = Activity.get_by_id(activity.id)
454 def update_follow_state(
455 %Activity{} = activity,
458 new_data = Map.put(activity.data, "state", state)
459 changeset = Changeset.change(activity, data: new_data)
461 with {:ok, activity} <- Repo.update(changeset) do
467 Makes a follow activity data for the given follower and followed
469 def make_follow_data(
470 %User{ap_id: follower_id},
471 %User{ap_id: followed_id} = _followed,
476 "actor" => follower_id,
477 "to" => [followed_id],
478 "cc" => [Pleroma.Constants.as_public()],
479 "object" => followed_id,
482 |> Maps.put_if_present("id", activity_id)
485 def fetch_latest_follow(%User{ap_id: follower_id}, %User{ap_id: followed_id}) do
487 |> Activity.Queries.by_type()
488 |> where(actor: ^follower_id)
489 # this is to use the index
490 |> Activity.Queries.by_object_id(followed_id)
491 |> order_by([activity], fragment("? desc nulls last", activity.id))
496 def fetch_latest_undo(%User{ap_id: ap_id}) do
498 |> Activity.Queries.by_type()
499 |> where(actor: ^ap_id)
500 |> order_by([activity], fragment("? desc nulls last", activity.id))
505 def get_latest_reaction(internal_activity_id, %{ap_id: ap_id}, emoji) do
506 %{data: %{"object" => object_ap_id}} = Activity.get_by_id(internal_activity_id)
509 |> Activity.Queries.by_type()
510 |> where(actor: ^ap_id)
511 |> where([activity], fragment("?->>'content' = ?", activity.data, ^emoji))
512 |> Activity.Queries.by_object_id(object_ap_id)
513 |> order_by([activity], fragment("? desc nulls last", activity.id))
518 #### Announce-related helpers
521 Returns an existing announce activity if the notice has already been announced
523 @spec get_existing_announce(String.t(), map()) :: Activity.t() | nil
524 def get_existing_announce(actor, %{data: %{"id" => ap_id}}) do
526 |> Activity.Queries.by_type()
527 |> where(actor: ^actor)
528 # this is to use the index
529 |> Activity.Queries.by_object_id(ap_id)
534 Make announce activity data for the given actor and object
536 # for relayed messages, we only want to send to subscribers
537 def make_announce_data(
538 %User{ap_id: ap_id} = user,
539 %Object{data: %{"id" => id}} = object,
544 "type" => "Announce",
547 "to" => [user.follower_address],
549 "context" => object.data["context"]
551 |> Maps.put_if_present("id", activity_id)
554 def make_announce_data(
555 %User{ap_id: ap_id} = user,
556 %Object{data: %{"id" => id}} = object,
561 "type" => "Announce",
564 "to" => [user.follower_address, object.data["actor"]],
565 "cc" => [Pleroma.Constants.as_public()],
566 "context" => object.data["context"]
568 |> Maps.put_if_present("id", activity_id)
572 %User{ap_id: actor, follower_address: follower_address},
574 data: %{"id" => undone_activity_id, "context" => context},
575 actor: undone_activity_actor
582 "object" => undone_activity_id,
583 "to" => [follower_address, undone_activity_actor],
584 "cc" => [Pleroma.Constants.as_public()],
587 |> Maps.put_if_present("id", activity_id)
590 @spec add_announce_to_object(Activity.t(), Object.t()) ::
591 {:ok, Object.t()} | {:error, Ecto.Changeset.t()}
592 def add_announce_to_object(
593 %Activity{data: %{"actor" => actor}},
596 unless actor |> User.get_cached_by_ap_id() |> User.invisible?() do
597 announcements = take_announcements(object)
599 with announcements <- Enum.uniq([actor | announcements]) do
600 update_element_in_object("announcement", announcements, object)
607 def add_announce_to_object(_, object), do: {:ok, object}
609 @spec remove_announce_from_object(Activity.t(), Object.t()) ::
610 {:ok, Object.t()} | {:error, Ecto.Changeset.t()}
611 def remove_announce_from_object(%Activity{data: %{"actor" => actor}}, object) do
612 with announcements <- List.delete(take_announcements(object), actor) do
613 update_element_in_object("announcement", announcements, object)
617 defp take_announcements(%{data: %{"announcements" => announcements}} = _)
618 when is_list(announcements),
621 defp take_announcements(_), do: []
623 #### Unfollow-related helpers
625 def make_unfollow_data(follower, followed, follow_activity, activity_id) do
628 "actor" => follower.ap_id,
629 "to" => [followed.ap_id],
630 "object" => follow_activity.data
632 |> Maps.put_if_present("id", activity_id)
635 #### Block-related helpers
636 @spec fetch_latest_block(User.t(), User.t()) :: Activity.t() | nil
637 def fetch_latest_block(%User{ap_id: blocker_id}, %User{ap_id: blocked_id}) do
639 |> Activity.Queries.by_type()
640 |> where(actor: ^blocker_id)
641 # this is to use the index
642 |> Activity.Queries.by_object_id(blocked_id)
643 |> order_by([activity], fragment("? desc nulls last", activity.id))
648 def make_block_data(blocker, blocked, activity_id) do
651 "actor" => blocker.ap_id,
652 "to" => [blocked.ap_id],
653 "object" => blocked.ap_id
655 |> Maps.put_if_present("id", activity_id)
658 #### Create-related helpers
660 def make_create_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 #### Listen-related helpers
675 def make_listen_data(params, additional) do
676 published = params.published || make_date()
680 "to" => params.to |> Enum.uniq(),
681 "actor" => params.actor.ap_id,
682 "object" => params.object,
683 "published" => published,
684 "context" => params.context
686 |> Map.merge(additional)
689 #### Flag-related helpers
690 @spec make_flag_data(map(), map()) :: map()
691 def make_flag_data(%{actor: actor, context: context, content: content} = params, additional) do
694 "actor" => actor.ap_id,
695 "content" => content,
696 "object" => build_flag_object(params),
697 "context" => context,
700 |> Map.merge(additional)
703 def make_flag_data(_, _), do: %{}
705 defp build_flag_object(%{account: account, statuses: statuses}) do
706 [account.ap_id | build_flag_object(%{statuses: statuses})]
709 defp build_flag_object(%{statuses: statuses}) do
710 Enum.map(statuses || [], &build_flag_object/1)
713 defp build_flag_object(%Activity{data: %{"id" => id}, object: %{data: data}}) do
714 activity_actor = User.get_by_ap_id(data["actor"])
719 "content" => data["content"],
720 "published" => data["published"],
724 %{user: activity_actor, skip_visibility_check: true}
729 defp build_flag_object(act) when is_map(act) or is_binary(act) do
732 %Activity{} = act -> act.data["id"]
733 act when is_map(act) -> act["id"]
734 act when is_binary(act) -> act
737 case Activity.get_by_ap_id_with_object(id) do
738 %Activity{} = activity ->
739 build_flag_object(activity)
742 if activity = Activity.get_by_object_ap_id_with_object(id) do
743 build_flag_object(activity)
745 %{"id" => id, "deleted" => true}
750 defp build_flag_object(_), do: []
752 #### Report-related helpers
753 def get_reports(params, page, page_size) do
756 |> Map.put(:type, "Flag")
757 |> Map.put(:skip_preload, true)
758 |> Map.put(:preload_report_notes, true)
759 |> Map.put(:total, true)
760 |> Map.put(:limit, page_size)
761 |> Map.put(:offset, (page - 1) * page_size)
763 ActivityPub.fetch_activities([], params, :offset)
766 def update_report_state(%Activity{} = activity, state)
767 when state in @strip_status_report_states do
768 {:ok, stripped_activity} = strip_report_status_data(activity)
772 |> Map.put("state", state)
773 |> Map.put("object", stripped_activity.data["object"])
776 |> Changeset.change(data: new_data)
780 def update_report_state(%Activity{} = activity, state) when state in @supported_report_states do
781 new_data = Map.put(activity.data, "state", state)
784 |> Changeset.change(data: new_data)
788 def update_report_state(activity_ids, state) when state in @supported_report_states do
789 activities_num = length(activity_ids)
791 from(a in Activity, where: a.id in ^activity_ids)
792 |> update(set: [data: fragment("jsonb_set(data, '{state}', ?)", ^state)])
793 |> Repo.update_all([])
795 {^activities_num, _} -> :ok
796 _ -> {:error, activity_ids}
800 def update_report_state(_, _), do: {:error, "Unsupported state"}
802 def strip_report_status_data(activity) do
803 [actor | reported_activities] = activity.data["object"]
805 stripped_activities =
806 Enum.map(reported_activities, fn
807 act when is_map(act) -> act["id"]
808 act when is_binary(act) -> act
811 new_data = put_in(activity.data, ["object"], [actor | stripped_activities])
813 {:ok, %{activity | data: new_data}}
816 def update_activity_visibility(activity, visibility) when visibility in @valid_visibilities do
817 [to, cc, recipients] =
819 |> get_updated_targets(visibility)
820 |> Enum.map(&Enum.uniq/1)
829 |> Object.change(%{data: object_data})
830 |> Object.update_and_set_cache()
838 |> Map.put(:object, object)
839 |> Activity.change(%{data: activity_data, recipients: recipients})
843 def update_activity_visibility(_, _), do: {:error, "Unsupported visibility"}
845 defp get_updated_targets(
846 %Activity{data: %{"to" => to} = data, recipients: recipients},
849 cc = Map.get(data, "cc", [])
850 follower_address = User.get_cached_by_ap_id(data["actor"]).follower_address
851 public = Pleroma.Constants.as_public()
855 to = [public | List.delete(to, follower_address)]
856 cc = [follower_address | List.delete(cc, public)]
857 recipients = [public | recipients]
861 to = [follower_address | List.delete(to, public)]
862 cc = List.delete(cc, public)
863 recipients = List.delete(recipients, public)
867 to = [follower_address | List.delete(to, public)]
868 cc = [public | List.delete(cc, follower_address)]
869 recipients = recipients ++ [follower_address, public]
877 def get_existing_votes(actor, %{data: %{"id" => id}}) do
879 |> Activity.Queries.by_actor()
880 |> Activity.Queries.by_type("Create")
881 |> Activity.with_preloaded_object()
882 |> where([a, object: o], fragment("(?)->>'inReplyTo' = ?", o.data, ^to_string(id)))
883 |> where([a, object: o], fragment("(?)->>'type' = 'Answer'", o.data))