1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2020 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 do
179 Pleroma.Web.Federator.publish(activity)
185 def maybe_federate(_), do: :ok
188 Adds an id and a published data if they aren't there,
189 also adds it to an included object
191 @spec lazy_put_activity_defaults(map(), boolean) :: map()
192 def lazy_put_activity_defaults(map, fake? \\ false)
194 def lazy_put_activity_defaults(map, true) do
196 |> Map.put_new("id", "pleroma:fakeid")
197 |> Map.put_new_lazy("published", &make_date/0)
198 |> Map.put_new("context", "pleroma:fakecontext")
199 |> Map.put_new("context_id", -1)
200 |> lazy_put_object_defaults(true)
203 def lazy_put_activity_defaults(map, _fake?) do
204 %{data: %{"id" => context}, id: context_id} = create_context(map["context"])
207 |> Map.put_new_lazy("id", &generate_activity_id/0)
208 |> Map.put_new_lazy("published", &make_date/0)
209 |> Map.put_new("context", context)
210 |> Map.put_new("context_id", context_id)
211 |> lazy_put_object_defaults(false)
214 # Adds an id and published date if they aren't there.
216 @spec lazy_put_object_defaults(map(), boolean()) :: map()
217 defp lazy_put_object_defaults(%{"object" => map} = activity, true)
221 |> Map.put_new("id", "pleroma:fake_object_id")
222 |> Map.put_new_lazy("published", &make_date/0)
223 |> Map.put_new("context", activity["context"])
224 |> Map.put_new("context_id", activity["context_id"])
225 |> Map.put_new("fake", true)
227 %{activity | "object" => object}
230 defp lazy_put_object_defaults(%{"object" => map} = activity, _)
234 |> Map.put_new_lazy("id", &generate_object_id/0)
235 |> Map.put_new_lazy("published", &make_date/0)
236 |> Map.put_new("context", activity["context"])
237 |> Map.put_new("context_id", activity["context_id"])
239 %{activity | "object" => object}
242 defp lazy_put_object_defaults(activity, _), do: activity
245 Inserts a full object if it is contained in an activity.
247 def insert_full_object(%{"object" => %{"type" => type} = object_data} = map)
248 when type in @supported_object_types do
249 with {:ok, object} <- Object.create(object_data) do
250 map = Map.put(map, "object", object.data["id"])
256 def insert_full_object(map), do: {:ok, map, nil}
258 #### Like-related helpers
261 Returns an existing like if a user already liked an object
263 @spec get_existing_like(String.t(), map()) :: Activity.t() | nil
264 def get_existing_like(actor, %{data: %{"id" => id}}) do
266 |> Activity.Queries.by_actor()
267 |> Activity.Queries.by_object_id(id)
268 |> Activity.Queries.by_type("Like")
274 Returns like activities targeting an object
276 def get_object_likes(%{data: %{"id" => id}}) do
278 |> Activity.Queries.by_object_id()
279 |> Activity.Queries.by_type("Like")
283 @spec make_like_data(User.t(), map(), String.t()) :: map()
285 %User{ap_id: ap_id} = actor,
286 %{data: %{"actor" => object_actor_id, "id" => id}} = object,
289 object_actor = User.get_cached_by_ap_id(object_actor_id)
292 if Visibility.is_public?(object) do
293 [actor.follower_address, object.data["actor"]]
295 [object.data["actor"]]
299 (object.data["to"] ++ (object.data["cc"] || []))
300 |> List.delete(actor.ap_id)
301 |> List.delete(object_actor.follower_address)
309 "context" => object.data["context"]
311 |> Maps.put_if_present("id", activity_id)
314 def make_emoji_reaction_data(user, object, emoji, activity_id) do
315 make_like_data(user, object, activity_id)
316 |> Map.put("type", "EmojiReact")
317 |> Map.put("content", emoji)
320 @spec update_element_in_object(String.t(), list(any), Object.t(), integer() | nil) ::
321 {:ok, Object.t()} | {:error, Ecto.Changeset.t()}
322 def update_element_in_object(property, element, object, count \\ nil) do
330 %{"#{property}_count" => length, "#{property}s" => element}
334 |> Changeset.change(data: data)
335 |> Object.update_and_set_cache()
338 @spec add_emoji_reaction_to_object(Activity.t(), Object.t()) ::
339 {:ok, Object.t()} | {:error, Ecto.Changeset.t()}
341 def add_emoji_reaction_to_object(
342 %Activity{data: %{"content" => emoji, "actor" => actor}},
345 reactions = get_cached_emoji_reactions(object)
348 case Enum.find_index(reactions, fn [candidate, _] -> emoji == candidate end) do
350 reactions ++ [[emoji, [actor]]]
356 fn [emoji, users] -> [emoji, Enum.uniq([actor | users])] end
360 count = emoji_count(new_reactions)
362 update_element_in_object("reaction", new_reactions, object, count)
365 def emoji_count(reactions_list) do
366 Enum.reduce(reactions_list, 0, fn [_, users], acc -> acc + length(users) end)
369 def remove_emoji_reaction_from_object(
370 %Activity{data: %{"content" => emoji, "actor" => actor}},
373 reactions = get_cached_emoji_reactions(object)
376 case Enum.find_index(reactions, fn [candidate, _] -> emoji == candidate end) do
384 fn [emoji, users] -> [emoji, List.delete(users, actor)] end
386 |> Enum.reject(fn [_, users] -> Enum.empty?(users) end)
389 count = emoji_count(new_reactions)
390 update_element_in_object("reaction", new_reactions, object, count)
393 def get_cached_emoji_reactions(object) do
394 if is_list(object.data["reactions"]) do
395 object.data["reactions"]
401 @spec add_like_to_object(Activity.t(), Object.t()) ::
402 {:ok, Object.t()} | {:error, Ecto.Changeset.t()}
403 def add_like_to_object(%Activity{data: %{"actor" => actor}}, object) do
404 [actor | fetch_likes(object)]
406 |> update_likes_in_object(object)
409 @spec remove_like_from_object(Activity.t(), Object.t()) ::
410 {:ok, Object.t()} | {:error, Ecto.Changeset.t()}
411 def remove_like_from_object(%Activity{data: %{"actor" => actor}}, object) do
414 |> List.delete(actor)
415 |> update_likes_in_object(object)
418 defp update_likes_in_object(likes, object) do
419 update_element_in_object("like", likes, object)
422 defp fetch_likes(object) do
423 if is_list(object.data["likes"]) do
430 #### Follow-related helpers
433 Updates a follow activity's state (for locked accounts).
435 @spec update_follow_state_for_all(Activity.t(), String.t()) :: {:ok, Activity | nil}
436 def update_follow_state_for_all(
437 %Activity{data: %{"actor" => actor, "object" => object}} = activity,
441 |> Activity.Queries.by_type()
442 |> Activity.Queries.by_actor(actor)
443 |> Activity.Queries.by_object_id(object)
444 |> where(fragment("data->>'state' = 'pending'"))
445 |> update(set: [data: fragment("jsonb_set(data, '{state}', ?)", ^state)])
446 |> Repo.update_all([])
448 activity = Activity.get_by_id(activity.id)
453 def update_follow_state(
454 %Activity{} = activity,
457 new_data = Map.put(activity.data, "state", state)
458 changeset = Changeset.change(activity, data: new_data)
460 with {:ok, activity} <- Repo.update(changeset) do
466 Makes a follow activity data for the given follower and followed
468 def make_follow_data(
469 %User{ap_id: follower_id},
470 %User{ap_id: followed_id} = _followed,
475 "actor" => follower_id,
476 "to" => [followed_id],
477 "cc" => [Pleroma.Constants.as_public()],
478 "object" => followed_id,
481 |> Maps.put_if_present("id", activity_id)
484 def fetch_latest_follow(%User{ap_id: follower_id}, %User{ap_id: followed_id}) do
486 |> Activity.Queries.by_type()
487 |> where(actor: ^follower_id)
488 # this is to use the index
489 |> Activity.Queries.by_object_id(followed_id)
490 |> order_by([activity], fragment("? desc nulls last", activity.id))
495 def fetch_latest_undo(%User{ap_id: ap_id}) do
497 |> Activity.Queries.by_type()
498 |> where(actor: ^ap_id)
499 |> order_by([activity], fragment("? desc nulls last", activity.id))
504 def get_latest_reaction(internal_activity_id, %{ap_id: ap_id}, emoji) do
505 %{data: %{"object" => object_ap_id}} = Activity.get_by_id(internal_activity_id)
508 |> Activity.Queries.by_type()
509 |> where(actor: ^ap_id)
510 |> where([activity], fragment("?->>'content' = ?", activity.data, ^emoji))
511 |> Activity.Queries.by_object_id(object_ap_id)
512 |> order_by([activity], fragment("? desc nulls last", activity.id))
517 #### Announce-related helpers
520 Returns an existing announce activity if the notice has already been announced
522 @spec get_existing_announce(String.t(), map()) :: Activity.t() | nil
523 def get_existing_announce(actor, %{data: %{"id" => ap_id}}) do
525 |> Activity.Queries.by_type()
526 |> where(actor: ^actor)
527 # this is to use the index
528 |> Activity.Queries.by_object_id(ap_id)
533 Make announce activity data for the given actor and object
535 # for relayed messages, we only want to send to subscribers
536 def make_announce_data(
537 %User{ap_id: ap_id} = user,
538 %Object{data: %{"id" => id}} = object,
543 "type" => "Announce",
546 "to" => [user.follower_address],
548 "context" => object.data["context"]
550 |> Maps.put_if_present("id", activity_id)
553 def make_announce_data(
554 %User{ap_id: ap_id} = user,
555 %Object{data: %{"id" => id}} = object,
560 "type" => "Announce",
563 "to" => [user.follower_address, object.data["actor"]],
564 "cc" => [Pleroma.Constants.as_public()],
565 "context" => object.data["context"]
567 |> Maps.put_if_present("id", activity_id)
571 %User{ap_id: actor, follower_address: follower_address},
573 data: %{"id" => undone_activity_id, "context" => context},
574 actor: undone_activity_actor
581 "object" => undone_activity_id,
582 "to" => [follower_address, undone_activity_actor],
583 "cc" => [Pleroma.Constants.as_public()],
586 |> Maps.put_if_present("id", activity_id)
589 @spec add_announce_to_object(Activity.t(), Object.t()) ::
590 {:ok, Object.t()} | {:error, Ecto.Changeset.t()}
591 def add_announce_to_object(
592 %Activity{data: %{"actor" => actor}},
595 unless actor |> User.get_cached_by_ap_id() |> User.invisible?() do
596 announcements = take_announcements(object)
598 with announcements <- Enum.uniq([actor | announcements]) do
599 update_element_in_object("announcement", announcements, object)
606 def add_announce_to_object(_, object), do: {:ok, object}
608 @spec remove_announce_from_object(Activity.t(), Object.t()) ::
609 {:ok, Object.t()} | {:error, Ecto.Changeset.t()}
610 def remove_announce_from_object(%Activity{data: %{"actor" => actor}}, object) do
611 with announcements <- List.delete(take_announcements(object), actor) do
612 update_element_in_object("announcement", announcements, object)
616 defp take_announcements(%{data: %{"announcements" => announcements}} = _)
617 when is_list(announcements),
620 defp take_announcements(_), do: []
622 #### Unfollow-related helpers
624 def make_unfollow_data(follower, followed, follow_activity, activity_id) do
627 "actor" => follower.ap_id,
628 "to" => [followed.ap_id],
629 "object" => follow_activity.data
631 |> Maps.put_if_present("id", activity_id)
634 #### Block-related helpers
635 @spec fetch_latest_block(User.t(), User.t()) :: Activity.t() | nil
636 def fetch_latest_block(%User{ap_id: blocker_id}, %User{ap_id: blocked_id}) do
638 |> Activity.Queries.by_type()
639 |> where(actor: ^blocker_id)
640 # this is to use the index
641 |> Activity.Queries.by_object_id(blocked_id)
642 |> order_by([activity], fragment("? desc nulls last", activity.id))
647 def make_block_data(blocker, blocked, activity_id) do
650 "actor" => blocker.ap_id,
651 "to" => [blocked.ap_id],
652 "object" => blocked.ap_id
654 |> Maps.put_if_present("id", activity_id)
657 #### Create-related helpers
659 def make_create_data(params, additional) do
660 published = params.published || make_date()
664 "to" => params.to |> Enum.uniq(),
665 "actor" => params.actor.ap_id,
666 "object" => params.object,
667 "published" => published,
668 "context" => params.context
670 |> Map.merge(additional)
673 #### Listen-related helpers
674 def make_listen_data(params, additional) do
675 published = params.published || make_date()
679 "to" => params.to |> Enum.uniq(),
680 "actor" => params.actor.ap_id,
681 "object" => params.object,
682 "published" => published,
683 "context" => params.context
685 |> Map.merge(additional)
688 #### Flag-related helpers
689 @spec make_flag_data(map(), map()) :: map()
690 def make_flag_data(%{actor: actor, context: context, content: content} = params, additional) do
693 "actor" => actor.ap_id,
694 "content" => content,
695 "object" => build_flag_object(params),
696 "context" => context,
699 |> Map.merge(additional)
702 def make_flag_data(_, _), do: %{}
704 defp build_flag_object(%{account: account, statuses: statuses} = _) do
705 [account.ap_id] ++ build_flag_object(%{statuses: statuses})
708 defp build_flag_object(%{statuses: statuses}) do
709 Enum.map(statuses || [], &build_flag_object/1)
712 defp build_flag_object(act) when is_map(act) or is_binary(act) do
715 %Activity{} = act -> act.data["id"]
716 act when is_map(act) -> act["id"]
717 act when is_binary(act) -> act
720 case Activity.get_by_ap_id_with_object(id) do
721 %Activity{} = activity ->
722 activity_actor = User.get_by_ap_id(activity.object.data["actor"])
726 "id" => activity.data["id"],
727 "content" => activity.object.data["content"],
728 "published" => activity.object.data["published"],
732 %{user: activity_actor, skip_visibility_check: true}
737 %{"id" => id, "deleted" => true}
741 defp build_flag_object(_), do: []
743 #### Report-related helpers
744 def get_reports(params, page, page_size) do
747 |> Map.put(:type, "Flag")
748 |> Map.put(:skip_preload, true)
749 |> Map.put(:preload_report_notes, true)
750 |> Map.put(:total, true)
751 |> Map.put(:limit, page_size)
752 |> Map.put(:offset, (page - 1) * page_size)
754 ActivityPub.fetch_activities([], params, :offset)
757 def update_report_state(%Activity{} = activity, state)
758 when state in @strip_status_report_states do
759 {:ok, stripped_activity} = strip_report_status_data(activity)
763 |> Map.put("state", state)
764 |> Map.put("object", stripped_activity.data["object"])
767 |> Changeset.change(data: new_data)
771 def update_report_state(%Activity{} = activity, state) when state in @supported_report_states do
772 new_data = Map.put(activity.data, "state", state)
775 |> Changeset.change(data: new_data)
779 def update_report_state(activity_ids, state) when state in @supported_report_states do
780 activities_num = length(activity_ids)
782 from(a in Activity, where: a.id in ^activity_ids)
783 |> update(set: [data: fragment("jsonb_set(data, '{state}', ?)", ^state)])
784 |> Repo.update_all([])
786 {^activities_num, _} -> :ok
787 _ -> {:error, activity_ids}
791 def update_report_state(_, _), do: {:error, "Unsupported state"}
793 def strip_report_status_data(activity) do
794 [actor | reported_activities] = activity.data["object"]
796 stripped_activities =
797 Enum.map(reported_activities, fn
798 act when is_map(act) -> act["id"]
799 act when is_binary(act) -> act
802 new_data = put_in(activity.data, ["object"], [actor | stripped_activities])
804 {:ok, %{activity | data: new_data}}
807 def update_activity_visibility(activity, visibility) when visibility in @valid_visibilities do
808 [to, cc, recipients] =
810 |> get_updated_targets(visibility)
811 |> Enum.map(&Enum.uniq/1)
820 |> Object.change(%{data: object_data})
821 |> Object.update_and_set_cache()
829 |> Map.put(:object, object)
830 |> Activity.change(%{data: activity_data, recipients: recipients})
834 def update_activity_visibility(_, _), do: {:error, "Unsupported visibility"}
836 defp get_updated_targets(
837 %Activity{data: %{"to" => to} = data, recipients: recipients},
840 cc = Map.get(data, "cc", [])
841 follower_address = User.get_cached_by_ap_id(data["actor"]).follower_address
842 public = Pleroma.Constants.as_public()
846 to = [public | List.delete(to, follower_address)]
847 cc = [follower_address | List.delete(cc, public)]
848 recipients = [public | recipients]
852 to = [follower_address | List.delete(to, public)]
853 cc = List.delete(cc, public)
854 recipients = List.delete(recipients, public)
858 to = [follower_address | List.delete(to, public)]
859 cc = [public | List.delete(cc, follower_address)]
860 recipients = recipients ++ [follower_address, public]
868 def get_existing_votes(actor, %{data: %{"id" => id}}) do
870 |> Activity.Queries.by_actor()
871 |> Activity.Queries.by_type("Create")
872 |> Activity.with_preloaded_object()
873 |> where([a, object: o], fragment("(?)->>'inReplyTo' = ?", o.data, ^to_string(id)))
874 |> where([a, object: o], fragment("(?)->>'type' = 'Answer'", o.data))