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.AdminAPI.AccountView
16 alias Pleroma.Web.Endpoint
17 alias Pleroma.Web.Router.Helpers
22 require Pleroma.Constants
24 @supported_object_types ["Article", "Note", "Video", "Page", "Question", "Answer", "Audio"]
25 @supported_report_states ~w(open closed resolved)
26 @valid_visibilities ~w(public unlisted private direct)
28 # Some implementations send the actor URI as the actor field, others send the entire actor object,
29 # so figure out what the actor's URI is based on what we have.
30 def get_ap_id(%{"id" => id} = _), do: id
31 def get_ap_id(id), do: id
33 def normalize_params(params) do
34 Map.put(params, "actor", get_ap_id(params["actor"]))
37 @spec determine_explicit_mentions(map()) :: map()
38 def determine_explicit_mentions(%{"tag" => tag} = _) when is_list(tag) do
40 %{"type" => "Mention", "href" => href} -> [href]
45 def determine_explicit_mentions(%{"tag" => tag} = object) when is_map(tag) do
47 |> Map.put("tag", [tag])
48 |> determine_explicit_mentions()
51 def determine_explicit_mentions(_), do: []
53 @spec recipient_in_collection(any(), any()) :: boolean()
54 defp recipient_in_collection(ap_id, coll) when is_binary(coll), do: ap_id == coll
55 defp recipient_in_collection(ap_id, coll) when is_list(coll), do: ap_id in coll
56 defp recipient_in_collection(_, _), do: false
58 @spec recipient_in_message(User.t(), User.t(), map()) :: boolean()
59 def recipient_in_message(%User{ap_id: ap_id} = recipient, %User{} = actor, params) do
60 addresses = [params["to"], params["cc"], params["bto"], params["bcc"]]
63 Enum.any?(addresses, &recipient_in_collection(ap_id, &1)) -> true
64 # if the message is unaddressed at all, then assume it is directly addressed
66 Enum.all?(addresses, &is_nil(&1)) -> true
67 # if the message is sent from somebody the user is following, then assume it
68 # is addressed to the recipient
69 User.following?(recipient, actor) -> true
74 defp extract_list(target) when is_binary(target), do: [target]
75 defp extract_list(lst) when is_list(lst), do: lst
76 defp extract_list(_), do: []
78 def maybe_splice_recipient(ap_id, params) do
80 !recipient_in_collection(ap_id, params["to"]) &&
81 !recipient_in_collection(ap_id, params["cc"])
84 cc_list = extract_list(params["cc"])
85 Map.put(params, "cc", [ap_id | cc_list])
91 def make_json_ld_header do
94 "https://www.w3.org/ns/activitystreams",
95 "#{Web.base_url()}/schemas/litepub-0.1.jsonld",
104 DateTime.utc_now() |> DateTime.to_iso8601()
107 def generate_activity_id do
108 generate_id("activities")
111 def generate_context_id do
112 generate_id("contexts")
115 def generate_object_id do
116 Helpers.o_status_url(Endpoint, :object, UUID.generate())
119 def generate_id(type) do
120 "#{Web.base_url()}/#{type}/#{UUID.generate()}"
123 def get_notified_from_object(%{"type" => type} = object) when type in @supported_object_types do
124 fake_create_activity = %{
125 "to" => object["to"],
126 "cc" => object["cc"],
131 get_notified_from_object(fake_create_activity)
134 def get_notified_from_object(object) do
135 Notification.get_notified_from_activity(%Activity{data: object}, false)
138 def create_context(context) do
139 context = context || generate_id("contexts")
141 # Ecto has problems accessing the constraint inside the jsonb,
142 # so we explicitly check for the existed object before insert
143 object = Object.get_cached_by_ap_id(context)
145 with true <- is_nil(object),
146 changeset <- Object.context_mapping(context),
147 {:ok, inserted_object} <- Repo.insert(changeset) do
156 Enqueues an activity for federation if it's local
158 @spec maybe_federate(any()) :: :ok
159 def maybe_federate(%Activity{local: true} = activity) do
160 if Pleroma.Config.get!([:instance, :federating]) do
161 Pleroma.Web.Federator.publish(activity)
167 def maybe_federate(_), do: :ok
170 Adds an id and a published data if they aren't there,
171 also adds it to an included object
173 @spec lazy_put_activity_defaults(map(), boolean) :: map()
174 def lazy_put_activity_defaults(map, fake? \\ false)
176 def lazy_put_activity_defaults(map, true) do
178 |> Map.put_new("id", "pleroma:fakeid")
179 |> Map.put_new_lazy("published", &make_date/0)
180 |> Map.put_new("context", "pleroma:fakecontext")
181 |> Map.put_new("context_id", -1)
182 |> lazy_put_object_defaults(true)
185 def lazy_put_activity_defaults(map, _fake?) do
186 %{data: %{"id" => context}, id: context_id} = create_context(map["context"])
189 |> Map.put_new_lazy("id", &generate_activity_id/0)
190 |> Map.put_new_lazy("published", &make_date/0)
191 |> Map.put_new("context", context)
192 |> Map.put_new("context_id", context_id)
193 |> lazy_put_object_defaults(false)
196 # Adds an id and published date if they aren't there.
198 @spec lazy_put_object_defaults(map(), boolean()) :: map()
199 defp lazy_put_object_defaults(%{"object" => map} = activity, true)
203 |> Map.put_new("id", "pleroma:fake_object_id")
204 |> Map.put_new_lazy("published", &make_date/0)
205 |> Map.put_new("context", activity["context"])
206 |> Map.put_new("context_id", activity["context_id"])
207 |> Map.put_new("fake", true)
209 %{activity | "object" => object}
212 defp lazy_put_object_defaults(%{"object" => map} = activity, _)
216 |> Map.put_new_lazy("id", &generate_object_id/0)
217 |> Map.put_new_lazy("published", &make_date/0)
218 |> Map.put_new("context", activity["context"])
219 |> Map.put_new("context_id", activity["context_id"])
221 %{activity | "object" => object}
224 defp lazy_put_object_defaults(activity, _), do: activity
227 Inserts a full object if it is contained in an activity.
229 def insert_full_object(%{"object" => %{"type" => type} = object_data} = map)
230 when is_map(object_data) and type in @supported_object_types do
231 with {:ok, object} <- Object.create(object_data) do
232 map = Map.put(map, "object", object.data["id"])
238 def insert_full_object(map), do: {:ok, map, nil}
240 #### Like-related helpers
243 Returns an existing like if a user already liked an object
245 @spec get_existing_like(String.t(), map()) :: Activity.t() | nil
246 def get_existing_like(actor, %{data: %{"id" => id}}) do
248 |> Activity.Queries.by_actor()
249 |> Activity.Queries.by_object_id(id)
250 |> Activity.Queries.by_type("Like")
255 @spec make_like_data(User.t(), map(), String.t()) :: map()
257 %User{ap_id: ap_id} = actor,
258 %{data: %{"actor" => object_actor_id, "id" => id}} = object,
261 object_actor = User.get_cached_by_ap_id(object_actor_id)
264 if Visibility.is_public?(object) do
265 [actor.follower_address, object.data["actor"]]
267 [object.data["actor"]]
271 (object.data["to"] ++ (object.data["cc"] || []))
272 |> List.delete(actor.ap_id)
273 |> List.delete(object_actor.follower_address)
281 "context" => object.data["context"]
283 |> maybe_put("id", activity_id)
286 @spec update_element_in_object(String.t(), list(any), Object.t()) ::
287 {:ok, Object.t()} | {:error, Ecto.Changeset.t()}
288 def update_element_in_object(property, element, object) do
292 %{"#{property}_count" => length(element), "#{property}s" => element}
296 |> Changeset.change(data: data)
297 |> Object.update_and_set_cache()
300 @spec add_like_to_object(Activity.t(), Object.t()) ::
301 {:ok, Object.t()} | {:error, Ecto.Changeset.t()}
302 def add_like_to_object(%Activity{data: %{"actor" => actor}}, object) do
303 [actor | fetch_likes(object)]
305 |> update_likes_in_object(object)
308 @spec remove_like_from_object(Activity.t(), Object.t()) ::
309 {:ok, Object.t()} | {:error, Ecto.Changeset.t()}
310 def remove_like_from_object(%Activity{data: %{"actor" => actor}}, object) do
313 |> List.delete(actor)
314 |> update_likes_in_object(object)
317 defp update_likes_in_object(likes, object) do
318 update_element_in_object("like", likes, object)
321 defp fetch_likes(object) do
322 if is_list(object.data["likes"]) do
329 #### Follow-related helpers
332 Updates a follow activity's state (for locked accounts).
334 @spec update_follow_state_for_all(Activity.t(), String.t()) :: {:ok, Activity} | {:error, any()}
335 def update_follow_state_for_all(
336 %Activity{data: %{"actor" => actor, "object" => object}} = activity,
340 |> Activity.Queries.by_type()
341 |> Activity.Queries.by_actor(actor)
342 |> Activity.Queries.by_object_id(object)
343 |> where(fragment("data->>'state' = 'pending'"))
344 |> update(set: [data: fragment("jsonb_set(data, '{state}', ?)", ^state)])
345 |> Repo.update_all([])
347 User.set_follow_state_cache(actor, object, state)
349 activity = Activity.get_by_id(activity.id)
354 def update_follow_state(
355 %Activity{data: %{"actor" => actor, "object" => object}} = activity,
358 new_data = Map.put(activity.data, "state", state)
359 changeset = Changeset.change(activity, data: new_data)
361 with {:ok, activity} <- Repo.update(changeset) do
362 User.set_follow_state_cache(actor, object, state)
368 Makes a follow activity data for the given follower and followed
370 def make_follow_data(
371 %User{ap_id: follower_id},
372 %User{ap_id: followed_id} = _followed,
377 "actor" => follower_id,
378 "to" => [followed_id],
379 "cc" => [Pleroma.Constants.as_public()],
380 "object" => followed_id,
383 |> maybe_put("id", activity_id)
386 def fetch_latest_follow(%User{ap_id: follower_id}, %User{ap_id: followed_id}) do
388 |> Activity.Queries.by_type()
389 |> where(actor: ^follower_id)
390 # this is to use the index
391 |> Activity.Queries.by_object_id(followed_id)
392 |> order_by([activity], fragment("? desc nulls last", activity.id))
397 #### Announce-related helpers
400 Retruns an existing announce activity if the notice has already been announced
402 @spec get_existing_announce(String.t(), map()) :: Activity.t() | nil
403 def get_existing_announce(actor, %{data: %{"id" => ap_id}}) do
405 |> Activity.Queries.by_type()
406 |> where(actor: ^actor)
407 # this is to use the index
408 |> Activity.Queries.by_object_id(ap_id)
413 Make announce activity data for the given actor and object
415 # for relayed messages, we only want to send to subscribers
416 def make_announce_data(
417 %User{ap_id: ap_id} = user,
418 %Object{data: %{"id" => id}} = object,
423 "type" => "Announce",
426 "to" => [user.follower_address],
428 "context" => object.data["context"]
430 |> maybe_put("id", activity_id)
433 def make_announce_data(
434 %User{ap_id: ap_id} = user,
435 %Object{data: %{"id" => id}} = object,
440 "type" => "Announce",
443 "to" => [user.follower_address, object.data["actor"]],
444 "cc" => [Pleroma.Constants.as_public()],
445 "context" => object.data["context"]
447 |> maybe_put("id", activity_id)
451 Make unannounce activity data for the given actor and object
453 def make_unannounce_data(
454 %User{ap_id: ap_id} = user,
455 %Activity{data: %{"context" => context, "object" => object}} = activity,
458 object = Object.normalize(object)
463 "object" => activity.data,
464 "to" => [user.follower_address, object.data["actor"]],
465 "cc" => [Pleroma.Constants.as_public()],
468 |> maybe_put("id", activity_id)
471 def make_unlike_data(
472 %User{ap_id: ap_id} = user,
473 %Activity{data: %{"context" => context, "object" => object}} = activity,
476 object = Object.normalize(object)
481 "object" => activity.data,
482 "to" => [user.follower_address, object.data["actor"]],
483 "cc" => [Pleroma.Constants.as_public()],
486 |> maybe_put("id", activity_id)
489 @spec add_announce_to_object(Activity.t(), Object.t()) ::
490 {:ok, Object.t()} | {:error, Ecto.Changeset.t()}
491 def add_announce_to_object(
492 %Activity{data: %{"actor" => actor}},
495 announcements = take_announcements(object)
497 with announcements <- Enum.uniq([actor | announcements]) do
498 update_element_in_object("announcement", announcements, object)
502 def add_announce_to_object(_, object), do: {:ok, object}
504 @spec remove_announce_from_object(Activity.t(), Object.t()) ::
505 {:ok, Object.t()} | {:error, Ecto.Changeset.t()}
506 def remove_announce_from_object(%Activity{data: %{"actor" => actor}}, object) do
507 with announcements <- List.delete(take_announcements(object), actor) do
508 update_element_in_object("announcement", announcements, object)
512 defp take_announcements(%{data: %{"announcements" => announcements}} = _)
513 when is_list(announcements),
516 defp take_announcements(_), do: []
518 #### Unfollow-related helpers
520 def make_unfollow_data(follower, followed, follow_activity, activity_id) do
523 "actor" => follower.ap_id,
524 "to" => [followed.ap_id],
525 "object" => follow_activity.data
527 |> maybe_put("id", activity_id)
530 #### Block-related helpers
531 @spec fetch_latest_block(User.t(), User.t()) :: Activity.t() | nil
532 def fetch_latest_block(%User{ap_id: blocker_id}, %User{ap_id: blocked_id}) do
534 |> Activity.Queries.by_type()
535 |> where(actor: ^blocker_id)
536 # this is to use the index
537 |> Activity.Queries.by_object_id(blocked_id)
538 |> order_by([activity], fragment("? desc nulls last", activity.id))
543 def make_block_data(blocker, blocked, activity_id) do
546 "actor" => blocker.ap_id,
547 "to" => [blocked.ap_id],
548 "object" => blocked.ap_id
550 |> maybe_put("id", activity_id)
553 def make_unblock_data(blocker, blocked, block_activity, activity_id) do
556 "actor" => blocker.ap_id,
557 "to" => [blocked.ap_id],
558 "object" => block_activity.data
560 |> maybe_put("id", activity_id)
563 #### Create-related helpers
565 def make_create_data(params, additional) do
566 published = params.published || make_date()
570 "to" => params.to |> Enum.uniq(),
571 "actor" => params.actor.ap_id,
572 "object" => params.object,
573 "published" => published,
574 "context" => params.context
576 |> Map.merge(additional)
579 #### Listen-related helpers
580 def make_listen_data(params, additional) do
581 published = params.published || make_date()
585 "to" => params.to |> Enum.uniq(),
586 "actor" => params.actor.ap_id,
587 "object" => params.object,
588 "published" => published,
589 "context" => params.context
591 |> Map.merge(additional)
594 #### Flag-related helpers
595 @spec make_flag_data(map(), map()) :: map()
596 def make_flag_data(%{actor: actor, context: context, content: content} = params, additional) do
599 "actor" => actor.ap_id,
600 "content" => content,
601 "object" => build_flag_object(params),
602 "context" => context,
605 |> Map.merge(additional)
608 def make_flag_data(_, _), do: %{}
610 defp build_flag_object(%{account: account, statuses: statuses} = _) do
612 Enum.map(statuses || [], fn act ->
615 %Activity{} = act -> act.data["id"]
616 act when is_map(act) -> act["id"]
617 act when is_binary(act) -> act
620 activity = Activity.get_by_ap_id_with_object(id)
621 actor = User.get_by_ap_id(activity.object.data["actor"])
625 "id" => activity.data["id"],
626 "content" => activity.object.data["content"],
627 "published" => activity.object.data["published"],
628 "actor" => AccountView.render("show.json", %{user: actor})
633 defp build_flag_object(_), do: []
636 Fetches the OrderedCollection/OrderedCollectionPage from `from`, limiting the amount of pages fetched after
637 the first one to `pages_left` pages.
638 If the amount of pages is higher than the collection has, it returns whatever was there.
640 def fetch_ordered_collection(from, pages_left, acc \\ []) do
641 with {:ok, response} <- Tesla.get(from),
642 {:ok, collection} <- Jason.decode(response.body) do
643 case collection["type"] do
644 "OrderedCollection" ->
645 # If we've encountered the OrderedCollection and not the page,
646 # just call the same function on the page address
647 fetch_ordered_collection(collection["first"], pages_left)
649 "OrderedCollectionPage" ->
651 # There are still more pages
652 if Map.has_key?(collection, "next") do
653 # There are still more pages, go deeper saving what we have into the accumulator
654 fetch_ordered_collection(
657 acc ++ collection["orderedItems"]
660 # No more pages left, just return whatever we already have
661 acc ++ collection["orderedItems"]
664 # Got the amount of pages needed, add them all to the accumulator
665 acc ++ collection["orderedItems"]
669 {:error, "Not an OrderedCollection or OrderedCollectionPage"}
674 #### Report-related helpers
676 def update_report_state(%Activity{} = activity, state) when state in @supported_report_states do
677 new_data = Map.put(activity.data, "state", state)
680 |> Changeset.change(data: new_data)
684 def update_report_state(_, _), do: {:error, "Unsupported state"}
686 def update_activity_visibility(activity, visibility) when visibility in @valid_visibilities do
687 [to, cc, recipients] =
689 |> get_updated_targets(visibility)
690 |> Enum.map(&Enum.uniq/1)
699 |> Object.change(%{data: object_data})
700 |> Object.update_and_set_cache()
708 |> Map.put(:object, object)
709 |> Activity.change(%{data: activity_data, recipients: recipients})
713 def update_activity_visibility(_, _), do: {:error, "Unsupported visibility"}
715 defp get_updated_targets(
716 %Activity{data: %{"to" => to} = data, recipients: recipients},
719 cc = Map.get(data, "cc", [])
720 follower_address = User.get_cached_by_ap_id(data["actor"]).follower_address
721 public = Pleroma.Constants.as_public()
725 to = [public | List.delete(to, follower_address)]
726 cc = [follower_address | List.delete(cc, public)]
727 recipients = [public | recipients]
731 to = [follower_address | List.delete(to, public)]
732 cc = List.delete(cc, public)
733 recipients = List.delete(recipients, public)
737 to = [follower_address | List.delete(to, public)]
738 cc = [public | List.delete(cc, follower_address)]
739 recipients = recipients ++ [follower_address, public]
747 def get_existing_votes(actor, %{data: %{"id" => id}}) do
749 |> Activity.Queries.by_actor()
750 |> Activity.Queries.by_type("Create")
751 |> Activity.with_preloaded_object()
752 |> where([a, object: o], fragment("(?)->>'inReplyTo' = ?", o.data, ^to_string(id)))
753 |> where([a, object: o], fragment("(?)->>'type' = 'Answer'", o.data))
757 def maybe_put(map, _key, nil), do: map
758 def maybe_put(map, key, value), do: Map.put(map, key, value)