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 @spec maybe_federate(any()) :: :ok
170 def maybe_federate(%Activity{local: true} = activity) do
171 if Pleroma.Config.get!([:instance, :federating]) do
173 case activity.data["type"] do
179 Pleroma.Web.Federator.publish(activity, priority)
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 def lazy_put_activity_defaults(map, fake \\ false) do
194 %{data: %{"id" => context}, id: context_id} = create_context(map["context"])
197 |> Map.put_new_lazy("id", &generate_activity_id/0)
198 |> Map.put_new_lazy("published", &make_date/0)
199 |> Map.put_new("context", context)
200 |> Map.put_new("context_id", context_id)
203 |> Map.put_new("id", "pleroma:fakeid")
204 |> Map.put_new_lazy("published", &make_date/0)
205 |> Map.put_new("context", "pleroma:fakecontext")
206 |> Map.put_new("context_id", -1)
209 if is_map(map["object"]) do
210 object = lazy_put_object_defaults(map["object"], map, fake)
211 %{map | "object" => object}
218 Adds an id and published date if they aren't there.
220 def lazy_put_object_defaults(map, activity \\ %{}, fake)
222 def lazy_put_object_defaults(map, activity, true = _fake) do
224 |> Map.put_new_lazy("published", &make_date/0)
225 |> Map.put_new("id", "pleroma:fake_object_id")
226 |> Map.put_new("context", activity["context"])
227 |> Map.put_new("fake", true)
228 |> Map.put_new("context_id", activity["context_id"])
231 def lazy_put_object_defaults(map, activity, _fake) do
233 |> Map.put_new_lazy("id", &generate_object_id/0)
234 |> Map.put_new_lazy("published", &make_date/0)
235 |> Map.put_new("context", activity["context"])
236 |> Map.put_new("context_id", activity["context_id"])
240 Inserts a full object if it is contained in an activity.
242 def insert_full_object(%{"object" => %{"type" => type} = object_data} = map)
243 when is_map(object_data) and type in @supported_object_types do
244 with {:ok, object} <- Object.create(object_data) do
247 |> Map.put("object", object.data["id"])
253 def insert_full_object(map), do: {:ok, map, nil}
255 #### Like-related helpers
258 Returns an existing like if a user already liked an object
260 @spec get_existing_like(String.t(), map()) :: Activity.t() | nil
261 def get_existing_like(actor, %{data: %{"id" => id}}) do
263 |> Activity.Queries.by_actor()
264 |> Activity.Queries.by_object_id(id)
265 |> Activity.Queries.by_type("Like")
266 |> Activity.Queries.limit(1)
271 Returns like activities targeting an object
273 def get_object_likes(%{data: %{"id" => id}}) do
275 |> Activity.Queries.by_object_id()
276 |> Activity.Queries.by_type("Like")
280 def make_emoji_reaction_data(user, object, emoji, activity_id) do
281 make_like_data(user, object, activity_id)
282 |> Map.put("type", "EmojiReaction")
283 |> Map.put("content", emoji)
286 @spec make_like_data(User.t(), map(), String.t()) :: map()
288 %User{ap_id: ap_id} = actor,
289 %{data: %{"actor" => object_actor_id, "id" => id}} = object,
292 object_actor = User.get_cached_by_ap_id(object_actor_id)
295 if Visibility.is_public?(object) do
296 [actor.follower_address, object.data["actor"]]
298 [object.data["actor"]]
302 (object.data["to"] ++ (object.data["cc"] || []))
303 |> List.delete(actor.ap_id)
304 |> List.delete(object_actor.follower_address)
312 "context" => object.data["context"]
314 |> maybe_put("id", activity_id)
317 @spec update_element_in_object(String.t(), list(any), Object.t()) ::
318 {:ok, Object.t()} | {:error, Ecto.Changeset.t()}
319 def update_element_in_object(property, element, object) do
321 if is_map(element) 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 = object.data["reactions"] || %{}
350 emoji_actors = reactions[emoji] || []
351 new_emoji_actors = [actor | emoji_actors] |> Enum.uniq()
352 new_reactions = Map.put(reactions, emoji, new_emoji_actors)
353 update_element_in_object("reaction", new_reactions, object)
356 @spec add_like_to_object(Activity.t(), Object.t()) ::
357 {:ok, Object.t()} | {:error, Ecto.Changeset.t()}
358 def add_like_to_object(%Activity{data: %{"actor" => actor}}, object) do
359 [actor | fetch_likes(object)]
361 |> update_likes_in_object(object)
364 @spec remove_like_from_object(Activity.t(), Object.t()) ::
365 {:ok, Object.t()} | {:error, Ecto.Changeset.t()}
366 def remove_like_from_object(%Activity{data: %{"actor" => actor}}, object) do
369 |> List.delete(actor)
370 |> update_likes_in_object(object)
373 defp update_likes_in_object(likes, object) do
374 update_element_in_object("like", likes, object)
377 defp fetch_likes(object) do
378 if is_list(object.data["likes"]) do
385 #### Follow-related helpers
388 Updates a follow activity's state (for locked accounts).
390 def update_follow_state_for_all(
391 %Activity{data: %{"actor" => actor, "object" => object}} = activity,
395 Ecto.Adapters.SQL.query!(
397 "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'",
398 [state, actor, object]
401 User.set_follow_state_cache(actor, object, state)
402 activity = Activity.get_by_id(activity.id)
410 def update_follow_state(
411 %Activity{data: %{"actor" => actor, "object" => object}} = activity,
416 |> Map.put("state", state),
417 changeset <- Changeset.change(activity, data: new_data),
418 {:ok, activity} <- Repo.update(changeset),
419 _ <- User.set_follow_state_cache(actor, object, state) do
425 Makes a follow activity data for the given follower and followed
427 def make_follow_data(
428 %User{ap_id: follower_id},
429 %User{ap_id: followed_id} = _followed,
434 "actor" => follower_id,
435 "to" => [followed_id],
436 "cc" => [Pleroma.Constants.as_public()],
437 "object" => followed_id,
440 |> maybe_put("id", activity_id)
443 def fetch_latest_follow(%User{ap_id: follower_id}, %User{ap_id: followed_id}) do
446 activity in Activity,
449 "? ->> 'type' = 'Follow'",
452 where: activity.actor == ^follower_id,
453 # this is to use the index
456 "coalesce((?)->'object'->>'id', (?)->>'object') = ?",
461 order_by: [fragment("? desc nulls last", activity.id)],
468 #### Announce-related helpers
471 Retruns an existing announce activity if the notice has already been announced
473 def get_existing_announce(actor, %{data: %{"id" => id}}) do
476 activity in Activity,
477 where: activity.actor == ^actor,
478 # this is to use the index
481 "coalesce((?)->'object'->>'id', (?)->>'object') = ?",
486 where: fragment("(?)->>'type' = 'Announce'", activity.data)
493 Make announce activity data for the given actor and object
495 # for relayed messages, we only want to send to subscribers
496 def make_announce_data(
497 %User{ap_id: ap_id} = user,
498 %Object{data: %{"id" => id}} = object,
503 "type" => "Announce",
506 "to" => [user.follower_address],
508 "context" => object.data["context"]
510 |> maybe_put("id", activity_id)
513 def make_announce_data(
514 %User{ap_id: ap_id} = user,
515 %Object{data: %{"id" => id}} = object,
520 "type" => "Announce",
523 "to" => [user.follower_address, object.data["actor"]],
524 "cc" => [Pleroma.Constants.as_public()],
525 "context" => object.data["context"]
527 |> maybe_put("id", activity_id)
531 Make unannounce activity data for the given actor and object
533 def make_unannounce_data(
534 %User{ap_id: ap_id} = user,
535 %Activity{data: %{"context" => context}} = activity,
541 "object" => activity.data,
542 "to" => [user.follower_address, activity.data["actor"]],
543 "cc" => [Pleroma.Constants.as_public()],
546 |> maybe_put("id", activity_id)
549 def make_unlike_data(
550 %User{ap_id: ap_id} = user,
551 %Activity{data: %{"context" => context}} = activity,
557 "object" => activity.data,
558 "to" => [user.follower_address, activity.data["actor"]],
559 "cc" => [Pleroma.Constants.as_public()],
562 |> maybe_put("id", activity_id)
565 def add_announce_to_object(
567 data: %{"actor" => actor, "cc" => [Pleroma.Constants.as_public()]}
572 if is_list(object.data["announcements"]), do: object.data["announcements"], else: []
574 with announcements <- [actor | announcements] |> Enum.uniq() do
575 update_element_in_object("announcement", announcements, object)
579 def add_announce_to_object(_, object), do: {:ok, object}
581 def remove_announce_from_object(%Activity{data: %{"actor" => actor}}, object) do
583 if is_list(object.data["announcements"]), do: object.data["announcements"], else: []
585 with announcements <- announcements |> List.delete(actor) do
586 update_element_in_object("announcement", announcements, object)
590 #### Unfollow-related helpers
592 def make_unfollow_data(follower, followed, follow_activity, activity_id) do
595 "actor" => follower.ap_id,
596 "to" => [followed.ap_id],
597 "object" => follow_activity.data
599 |> maybe_put("id", activity_id)
602 #### Block-related helpers
603 def fetch_latest_block(%User{ap_id: blocker_id}, %User{ap_id: blocked_id}) do
606 activity in Activity,
609 "? ->> 'type' = 'Block'",
612 where: activity.actor == ^blocker_id,
613 # this is to use the index
616 "coalesce((?)->'object'->>'id', (?)->>'object') = ?",
621 order_by: [fragment("? desc nulls last", activity.id)],
628 def make_block_data(blocker, blocked, activity_id) do
631 "actor" => blocker.ap_id,
632 "to" => [blocked.ap_id],
633 "object" => blocked.ap_id
635 |> maybe_put("id", activity_id)
638 def make_unblock_data(blocker, blocked, block_activity, activity_id) do
641 "actor" => blocker.ap_id,
642 "to" => [blocked.ap_id],
643 "object" => block_activity.data
645 |> maybe_put("id", activity_id)
648 #### Create-related helpers
650 def make_create_data(params, additional) do
651 published = params.published || make_date()
655 "to" => params.to |> Enum.uniq(),
656 "actor" => params.actor.ap_id,
657 "object" => params.object,
658 "published" => published,
659 "context" => params.context
661 |> Map.merge(additional)
664 #### Flag-related helpers
666 def make_flag_data(params, additional) do
668 Enum.map(params.statuses || [], fn
669 %Activity{} = act -> act.data["id"]
670 act when is_map(act) -> act["id"]
671 act when is_binary(act) -> act
674 object = [params.account.ap_id] ++ status_ap_ids
678 "actor" => params.actor.ap_id,
679 "content" => params.content,
681 "context" => params.context,
684 |> Map.merge(additional)
688 Fetches the OrderedCollection/OrderedCollectionPage from `from`, limiting the amount of pages fetched after
689 the first one to `pages_left` pages.
690 If the amount of pages is higher than the collection has, it returns whatever was there.
692 def fetch_ordered_collection(from, pages_left, acc \\ []) do
693 with {:ok, response} <- Tesla.get(from),
694 {:ok, collection} <- Jason.decode(response.body) do
695 case collection["type"] do
696 "OrderedCollection" ->
697 # If we've encountered the OrderedCollection and not the page,
698 # just call the same function on the page address
699 fetch_ordered_collection(collection["first"], pages_left)
701 "OrderedCollectionPage" ->
703 # There are still more pages
704 if Map.has_key?(collection, "next") do
705 # There are still more pages, go deeper saving what we have into the accumulator
706 fetch_ordered_collection(
709 acc ++ collection["orderedItems"]
712 # No more pages left, just return whatever we already have
713 acc ++ collection["orderedItems"]
716 # Got the amount of pages needed, add them all to the accumulator
717 acc ++ collection["orderedItems"]
721 {:error, "Not an OrderedCollection or OrderedCollectionPage"}
726 #### Report-related helpers
728 def update_report_state(%Activity{} = activity, state) when state in @supported_report_states do
729 with new_data <- Map.put(activity.data, "state", state),
730 changeset <- Changeset.change(activity, data: new_data),
731 {:ok, activity} <- Repo.update(changeset) do
736 def update_report_state(_, _), do: {:error, "Unsupported state"}
738 def update_activity_visibility(activity, visibility) when visibility in @valid_visibilities do
739 [to, cc, recipients] =
741 |> get_updated_targets(visibility)
742 |> Enum.map(&Enum.uniq/1)
751 |> Object.change(%{data: object_data})
752 |> Object.update_and_set_cache()
760 |> Map.put(:object, object)
761 |> Activity.change(%{data: activity_data, recipients: recipients})
765 def update_activity_visibility(_, _), do: {:error, "Unsupported visibility"}
767 defp get_updated_targets(
768 %Activity{data: %{"to" => to} = data, recipients: recipients},
771 cc = Map.get(data, "cc", [])
772 follower_address = User.get_cached_by_ap_id(data["actor"]).follower_address
773 public = Pleroma.Constants.as_public()
777 to = [public | List.delete(to, follower_address)]
778 cc = [follower_address | List.delete(cc, public)]
779 recipients = [public | recipients]
783 to = [follower_address | List.delete(to, public)]
784 cc = List.delete(cc, public)
785 recipients = List.delete(recipients, public)
789 to = [follower_address | List.delete(to, public)]
790 cc = [public | List.delete(cc, follower_address)]
791 recipients = recipients ++ [follower_address, public]
799 def get_existing_votes(actor, %{data: %{"id" => id}}) do
802 [activity, object: object] in Activity.with_preloaded_object(Activity),
803 where: fragment("(?)->>'type' = 'Create'", activity.data),
804 where: fragment("(?)->>'actor' = ?", activity.data, ^actor),
807 "(?)->>'inReplyTo' = ?",
811 where: fragment("(?)->>'type' = 'Answer'", object.data)
817 defp maybe_put(map, _key, nil), do: map
818 defp maybe_put(map, key, value), do: Map.put(map, key, value)