1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2019 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
5 defmodule Pleroma.Web.ActivityPub.Utils do
9 alias Pleroma.Notification
14 alias Pleroma.Web.ActivityPub.Visibility
15 alias Pleroma.Web.Endpoint
16 alias Pleroma.Web.Router.Helpers
21 require Pleroma.Constants
23 @supported_object_types ["Article", "Note", "Video", "Page", "Question", "Answer"]
24 @supported_report_states ~w(open closed resolved)
25 @valid_visibilities ~w(public unlisted private direct)
27 # Some implementations send the actor URI as the actor field, others send the entire actor object,
28 # so figure out what the actor's URI is based on what we have.
29 def get_ap_id(%{"id" => id} = _), do: id
30 def get_ap_id(id), do: id
32 def normalize_params(params) do
33 Map.put(params, "actor", get_ap_id(params["actor"]))
36 def determine_explicit_mentions(%{"tag" => tag} = _object) when is_list(tag) do
38 |> Enum.filter(fn x -> is_map(x) end)
39 |> Enum.filter(fn x -> x["type"] == "Mention" end)
40 |> Enum.map(fn x -> x["href"] end)
43 def determine_explicit_mentions(%{"tag" => tag} = object) when is_map(tag) do
44 Map.put(object, "tag", [tag])
45 |> determine_explicit_mentions()
48 def determine_explicit_mentions(_), do: []
50 defp recipient_in_collection(ap_id, coll) when is_binary(coll), do: ap_id == coll
51 defp recipient_in_collection(ap_id, coll) when is_list(coll), do: ap_id in coll
52 defp recipient_in_collection(_, _), do: false
54 def recipient_in_message(%User{ap_id: ap_id} = recipient, %User{} = actor, params) do
56 recipient_in_collection(ap_id, params["to"]) ->
59 recipient_in_collection(ap_id, params["cc"]) ->
62 recipient_in_collection(ap_id, params["bto"]) ->
65 recipient_in_collection(ap_id, params["bcc"]) ->
68 # if the message is unaddressed at all, then assume it is directly addressed
70 !params["to"] && !params["cc"] && !params["bto"] && !params["bcc"] ->
73 # if the message is sent from somebody the user is following, then assume it
74 # is addressed to the recipient
75 User.following?(recipient, actor) ->
83 defp extract_list(target) when is_binary(target), do: [target]
84 defp extract_list(lst) when is_list(lst), do: lst
85 defp extract_list(_), do: []
87 def maybe_splice_recipient(ap_id, params) do
89 !recipient_in_collection(ap_id, params["to"]) &&
90 !recipient_in_collection(ap_id, params["cc"])
92 cc_list = extract_list(params["cc"])
96 |> Map.put("cc", [ap_id | cc_list])
102 def make_json_ld_header do
105 "https://www.w3.org/ns/activitystreams",
106 "#{Web.base_url()}/schemas/litepub-0.1.jsonld",
115 DateTime.utc_now() |> DateTime.to_iso8601()
118 def generate_activity_id do
119 generate_id("activities")
122 def generate_context_id do
123 generate_id("contexts")
126 def generate_object_id do
127 Helpers.o_status_url(Endpoint, :object, UUID.generate())
130 def generate_id(type) do
131 "#{Web.base_url()}/#{type}/#{UUID.generate()}"
134 def get_notified_from_object(%{"type" => type} = object) when type in @supported_object_types do
135 fake_create_activity = %{
136 "to" => object["to"],
137 "cc" => object["cc"],
142 Notification.get_notified_from_activity(%Activity{data: fake_create_activity}, false)
145 def get_notified_from_object(object) do
146 Notification.get_notified_from_activity(%Activity{data: object}, false)
149 def create_context(context) do
150 context = context || generate_id("contexts")
152 # Ecto has problems accessing the constraint inside the jsonb,
153 # so we explicitly check for the existed object before insert
154 object = Object.get_cached_by_ap_id(context)
156 with true <- is_nil(object),
157 changeset <- Object.context_mapping(context),
158 {:ok, inserted_object} <- Repo.insert(changeset) do
167 Enqueues an activity for federation if it's local
169 def maybe_federate(%Activity{local: true} = activity) do
170 if Pleroma.Config.get!([:instance, :federating]) do
172 case activity.data["type"] do
178 Pleroma.Web.Federator.publish(activity, priority)
184 def maybe_federate(_), do: :ok
187 Adds an id and a published data if they aren't there,
188 also adds it to an included object
190 def lazy_put_activity_defaults(map, fake \\ false) do
193 %{data: %{"id" => context}, id: context_id} = 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 |> Map.put_new("context_id", context_id)
202 |> Map.put_new("id", "pleroma:fakeid")
203 |> Map.put_new_lazy("published", &make_date/0)
204 |> Map.put_new("context", "pleroma:fakecontext")
205 |> Map.put_new("context_id", -1)
208 if is_map(map["object"]) do
209 object = lazy_put_object_defaults(map["object"], map, fake)
210 %{map | "object" => object}
217 Adds an id and published date if they aren't there.
219 def lazy_put_object_defaults(map, activity \\ %{}, fake)
221 def lazy_put_object_defaults(map, activity, true = _fake) do
223 |> Map.put_new_lazy("published", &make_date/0)
224 |> Map.put_new("id", "pleroma:fake_object_id")
225 |> Map.put_new("context", activity["context"])
226 |> Map.put_new("fake", true)
227 |> Map.put_new("context_id", activity["context_id"])
230 def lazy_put_object_defaults(map, activity, _fake) do
232 |> Map.put_new_lazy("id", &generate_object_id/0)
233 |> Map.put_new_lazy("published", &make_date/0)
234 |> Map.put_new("context", activity["context"])
235 |> Map.put_new("context_id", activity["context_id"])
239 Inserts a full object if it is contained in an activity.
241 def insert_full_object(%{"object" => %{"type" => type} = object_data} = map)
242 when is_map(object_data) and type in @supported_object_types do
243 with {:ok, object} <- Object.create(object_data) do
246 |> Map.put("object", object.data["id"])
252 def insert_full_object(map), do: {:ok, map, nil}
254 #### Like-related helpers
257 Returns an existing like if a user already liked an object
259 def get_existing_like(actor, %{data: %{"id" => id}}) do
262 activity in Activity,
263 where: fragment("(?)->>'actor' = ?", activity.data, ^actor),
264 # this is to use the index
267 "coalesce((?)->'object'->>'id', (?)->>'object') = ?",
272 where: fragment("(?)->>'type' = 'Like'", activity.data)
279 Returns like activities targeting an object
281 def get_object_likes(%{data: %{"id" => id}}) do
284 activity in Activity,
285 # this is to use the index
288 "coalesce((?)->'object'->>'id', (?)->>'object') = ?",
293 where: fragment("(?)->>'type' = 'Like'", activity.data)
300 %User{ap_id: ap_id} = actor,
301 %{data: %{"actor" => object_actor_id, "id" => id}} = object,
304 object_actor = User.get_cached_by_ap_id(object_actor_id)
307 if Visibility.is_public?(object) do
308 [actor.follower_address, object.data["actor"]]
310 [object.data["actor"]]
314 (object.data["to"] ++ (object.data["cc"] || []))
315 |> List.delete(actor.ap_id)
316 |> List.delete(object_actor.follower_address)
324 "context" => object.data["context"]
327 if activity_id, do: Map.put(data, "id", activity_id), else: data
330 def update_element_in_object(property, element, object) do
333 |> Map.put("#{property}_count", length(element))
334 |> Map.put("#{property}s", element),
335 changeset <- Changeset.change(object, data: new_data),
336 {:ok, object} <- Object.update_and_set_cache(changeset) do
341 def update_likes_in_object(likes, object) do
342 update_element_in_object("like", likes, object)
345 def add_like_to_object(%Activity{data: %{"actor" => actor}}, object) do
346 likes = if is_list(object.data["likes"]), do: object.data["likes"], else: []
348 with likes <- [actor | likes] |> Enum.uniq() do
349 update_likes_in_object(likes, object)
353 def remove_like_from_object(%Activity{data: %{"actor" => actor}}, object) do
354 likes = if is_list(object.data["likes"]), do: object.data["likes"], else: []
356 with likes <- likes |> List.delete(actor) do
357 update_likes_in_object(likes, object)
361 #### Follow-related helpers
364 Updates a follow activity's state (for locked accounts).
366 def update_follow_state_for_all(
367 %Activity{data: %{"actor" => actor, "object" => object}} = activity,
371 Ecto.Adapters.SQL.query!(
373 "UPDATE activities SET data = jsonb_set(data, '{state}', $1) WHERE data->>'type' = 'Follow' AND data->>'actor' = $2 AND data->>'object' = $3 AND data->>'state' = 'pending'",
374 [state, actor, object]
377 activity = Activity.get_by_id(activity.id)
385 def update_follow_state(%Activity{} = activity, state) do
388 |> Map.put("state", state),
389 changeset <- Changeset.change(activity, data: new_data),
390 {:ok, activity} <- Repo.update(changeset) do
396 Makes a follow activity data for the given follower and followed
398 def make_follow_data(
399 %User{ap_id: follower_id},
400 %User{ap_id: followed_id} = _followed,
405 "actor" => follower_id,
406 "to" => [followed_id],
407 "cc" => [Pleroma.Constants.as_public()],
408 "object" => followed_id,
412 data = if activity_id, do: Map.put(data, "id", activity_id), else: data
417 def fetch_latest_follow(%User{ap_id: follower_id}, %User{ap_id: followed_id}) do
420 activity in Activity,
423 "? ->> 'type' = 'Follow'",
426 where: activity.actor == ^follower_id,
427 # this is to use the index
430 "coalesce((?)->'object'->>'id', (?)->>'object') = ?",
435 order_by: [fragment("? desc nulls last", activity.id)],
442 #### Announce-related helpers
445 Retruns an existing announce activity if the notice has already been announced
447 def get_existing_announce(actor, %{data: %{"id" => id}}) do
450 activity in Activity,
451 where: activity.actor == ^actor,
452 # this is to use the index
455 "coalesce((?)->'object'->>'id', (?)->>'object') = ?",
460 where: fragment("(?)->>'type' = 'Announce'", activity.data)
467 Make announce activity data for the given actor and object
469 # for relayed messages, we only want to send to subscribers
470 def make_announce_data(
471 %User{ap_id: ap_id} = user,
472 %Object{data: %{"id" => id}} = object,
477 "type" => "Announce",
480 "to" => [user.follower_address],
482 "context" => object.data["context"]
485 if activity_id, do: Map.put(data, "id", activity_id), else: data
488 def make_announce_data(
489 %User{ap_id: ap_id} = user,
490 %Object{data: %{"id" => id}} = object,
495 "type" => "Announce",
498 "to" => [user.follower_address, object.data["actor"]],
499 "cc" => [Pleroma.Constants.as_public()],
500 "context" => object.data["context"]
503 if activity_id, do: Map.put(data, "id", activity_id), else: data
507 Make unannounce activity data for the given actor and object
509 def make_unannounce_data(
510 %User{ap_id: ap_id} = user,
511 %Activity{data: %{"context" => context}} = activity,
517 "object" => activity.data,
518 "to" => [user.follower_address, activity.data["actor"]],
519 "cc" => [Pleroma.Constants.as_public()],
523 if activity_id, do: Map.put(data, "id", activity_id), else: data
526 def make_unlike_data(
527 %User{ap_id: ap_id} = user,
528 %Activity{data: %{"context" => context}} = activity,
534 "object" => activity.data,
535 "to" => [user.follower_address, activity.data["actor"]],
536 "cc" => [Pleroma.Constants.as_public()],
540 if activity_id, do: Map.put(data, "id", activity_id), else: data
543 def add_announce_to_object(
545 data: %{"actor" => actor, "cc" => [Pleroma.Constants.as_public()]}
550 if is_list(object.data["announcements"]), do: object.data["announcements"], else: []
552 with announcements <- [actor | announcements] |> Enum.uniq() do
553 update_element_in_object("announcement", announcements, object)
557 def add_announce_to_object(_, object), do: {:ok, object}
559 def remove_announce_from_object(%Activity{data: %{"actor" => actor}}, object) do
561 if is_list(object.data["announcements"]), do: object.data["announcements"], else: []
563 with announcements <- announcements |> List.delete(actor) do
564 update_element_in_object("announcement", announcements, object)
568 #### Unfollow-related helpers
570 def make_unfollow_data(follower, followed, follow_activity, activity_id) do
573 "actor" => follower.ap_id,
574 "to" => [followed.ap_id],
575 "object" => follow_activity.data
578 if activity_id, do: Map.put(data, "id", activity_id), else: data
581 #### Block-related helpers
582 def fetch_latest_block(%User{ap_id: blocker_id}, %User{ap_id: blocked_id}) do
585 activity in Activity,
588 "? ->> 'type' = 'Block'",
591 where: activity.actor == ^blocker_id,
592 # this is to use the index
595 "coalesce((?)->'object'->>'id', (?)->>'object') = ?",
600 order_by: [fragment("? desc nulls last", activity.id)],
607 def make_block_data(blocker, blocked, activity_id) do
610 "actor" => blocker.ap_id,
611 "to" => [blocked.ap_id],
612 "object" => blocked.ap_id
615 if activity_id, do: Map.put(data, "id", activity_id), else: data
618 def make_unblock_data(blocker, blocked, block_activity, activity_id) do
621 "actor" => blocker.ap_id,
622 "to" => [blocked.ap_id],
623 "object" => block_activity.data
626 if activity_id, do: Map.put(data, "id", activity_id), else: data
629 #### Create-related helpers
631 def make_create_data(params, additional) do
632 published = params.published || make_date()
636 "to" => params.to |> Enum.uniq(),
637 "actor" => params.actor.ap_id,
638 "object" => params.object,
639 "published" => published,
640 "context" => params.context
642 |> Map.merge(additional)
645 #### Flag-related helpers
647 def make_flag_data(params, additional) do
649 Enum.map(params.statuses || [], fn
650 %Activity{} = act -> act.data["id"]
651 act when is_map(act) -> act["id"]
652 act when is_binary(act) -> act
655 object = [params.account.ap_id] ++ status_ap_ids
659 "actor" => params.actor.ap_id,
660 "content" => params.content,
662 "context" => params.context,
665 |> Map.merge(additional)
669 Fetches the OrderedCollection/OrderedCollectionPage from `from`, limiting the amount of pages fetched after
670 the first one to `pages_left` pages.
671 If the amount of pages is higher than the collection has, it returns whatever was there.
673 def fetch_ordered_collection(from, pages_left, acc \\ []) do
674 with {:ok, response} <- Tesla.get(from),
675 {:ok, collection} <- Jason.decode(response.body) do
676 case collection["type"] do
677 "OrderedCollection" ->
678 # If we've encountered the OrderedCollection and not the page,
679 # just call the same function on the page address
680 fetch_ordered_collection(collection["first"], pages_left)
682 "OrderedCollectionPage" ->
684 # There are still more pages
685 if Map.has_key?(collection, "next") do
686 # There are still more pages, go deeper saving what we have into the accumulator
687 fetch_ordered_collection(
690 acc ++ collection["orderedItems"]
693 # No more pages left, just return whatever we already have
694 acc ++ collection["orderedItems"]
697 # Got the amount of pages needed, add them all to the accumulator
698 acc ++ collection["orderedItems"]
702 {:error, "Not an OrderedCollection or OrderedCollectionPage"}
707 #### Report-related helpers
709 def update_report_state(%Activity{} = activity, state) when state in @supported_report_states do
710 with new_data <- Map.put(activity.data, "state", state),
711 changeset <- Changeset.change(activity, data: new_data),
712 {:ok, activity} <- Repo.update(changeset) do
717 def update_report_state(_, _), do: {:error, "Unsupported state"}
719 def update_activity_visibility(activity, visibility) when visibility in @valid_visibilities do
720 [to, cc, recipients] =
722 |> get_updated_targets(visibility)
723 |> Enum.map(&Enum.uniq/1)
732 |> Object.change(%{data: object_data})
733 |> Object.update_and_set_cache()
741 |> Map.put(:object, object)
742 |> Activity.change(%{data: activity_data, recipients: recipients})
746 def update_activity_visibility(_, _), do: {:error, "Unsupported visibility"}
748 defp get_updated_targets(
749 %Activity{data: %{"to" => to} = data, recipients: recipients},
752 cc = Map.get(data, "cc", [])
753 follower_address = User.get_cached_by_ap_id(data["actor"]).follower_address
754 public = Pleroma.Constants.as_public()
758 to = [public | List.delete(to, follower_address)]
759 cc = [follower_address | List.delete(cc, public)]
760 recipients = [public | recipients]
764 to = [follower_address | List.delete(to, public)]
765 cc = List.delete(cc, public)
766 recipients = List.delete(recipients, public)
770 to = [follower_address | List.delete(to, public)]
771 cc = [public | List.delete(cc, follower_address)]
772 recipients = recipients ++ [follower_address, public]
780 def get_existing_votes(actor, %{data: %{"id" => id}}) do
783 [activity, object: object] in Activity.with_preloaded_object(Activity),
784 where: fragment("(?)->>'type' = 'Create'", activity.data),
785 where: fragment("(?)->>'actor' = ?", activity.data, ^actor),
788 "(?)->>'inReplyTo' = ?",
792 where: fragment("(?)->>'type' = 'Answer'", object.data)