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
22 @supported_object_types ["Article", "Note", "Video", "Page", "Question", "Answer"]
23 @supported_report_states ~w(open closed resolved)
24 @valid_visibilities ~w(public unlisted private direct)
26 # Some implementations send the actor URI as the actor field, others send the entire actor object,
27 # so figure out what the actor's URI is based on what we have.
28 def get_ap_id(object) do
35 def normalize_params(params) do
36 Map.put(params, "actor", get_ap_id(params["actor"]))
39 def determine_explicit_mentions(%{"tag" => tag} = _object) when is_list(tag) do
41 |> Enum.filter(fn x -> is_map(x) end)
42 |> Enum.filter(fn x -> x["type"] == "Mention" end)
43 |> Enum.map(fn x -> x["href"] end)
46 def determine_explicit_mentions(%{"tag" => tag} = object) when is_map(tag) do
47 Map.put(object, "tag", [tag])
48 |> determine_explicit_mentions()
51 def determine_explicit_mentions(_), do: []
53 defp recipient_in_collection(ap_id, coll) when is_binary(coll), do: ap_id == coll
54 defp recipient_in_collection(ap_id, coll) when is_list(coll), do: ap_id in coll
55 defp recipient_in_collection(_, _), do: false
57 def recipient_in_message(%User{ap_id: ap_id} = recipient, %User{} = actor, params) do
59 recipient_in_collection(ap_id, params["to"]) ->
62 recipient_in_collection(ap_id, params["cc"]) ->
65 recipient_in_collection(ap_id, params["bto"]) ->
68 recipient_in_collection(ap_id, params["bcc"]) ->
71 # if the message is unaddressed at all, then assume it is directly addressed
73 !params["to"] && !params["cc"] && !params["bto"] && !params["bcc"] ->
76 # if the message is sent from somebody the user is following, then assume it
77 # is addressed to the recipient
78 User.following?(recipient, actor) ->
86 defp extract_list(target) when is_binary(target), do: [target]
87 defp extract_list(lst) when is_list(lst), do: lst
88 defp extract_list(_), do: []
90 def maybe_splice_recipient(ap_id, params) do
92 !recipient_in_collection(ap_id, params["to"]) &&
93 !recipient_in_collection(ap_id, params["cc"])
95 cc_list = extract_list(params["cc"])
99 |> Map.put("cc", [ap_id | cc_list])
105 def make_json_ld_header do
108 "https://www.w3.org/ns/activitystreams",
109 "#{Web.base_url()}/schemas/litepub-0.1.jsonld",
118 DateTime.utc_now() |> DateTime.to_iso8601()
121 def generate_activity_id do
122 generate_id("activities")
125 def generate_context_id do
126 generate_id("contexts")
129 def generate_object_id do
130 Helpers.o_status_url(Endpoint, :object, UUID.generate())
133 def generate_id(type) do
134 "#{Web.base_url()}/#{type}/#{UUID.generate()}"
137 def get_notified_from_object(%{"type" => type} = object) when type in @supported_object_types do
138 fake_create_activity = %{
139 "to" => object["to"],
140 "cc" => object["cc"],
145 Notification.get_notified_from_activity(%Activity{data: fake_create_activity}, false)
148 def get_notified_from_object(object) do
149 Notification.get_notified_from_activity(%Activity{data: object}, false)
152 def create_context(context) do
153 context = context || generate_id("contexts")
155 # Ecto has problems accessing the constraint inside the jsonb,
156 # so we explicitly check for the existed object before insert
157 object = Object.get_cached_by_ap_id(context)
159 with true <- is_nil(object),
160 changeset <- Object.context_mapping(context),
161 {:ok, inserted_object} <- Repo.insert(changeset) do
170 Enqueues an activity for federation if it's local
172 def maybe_federate(%Activity{local: true} = activity) do
174 case activity.data["type"] do
180 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 def update_object_in_activities(%{data: %{"id" => id}} = object) do
256 # Update activities that already had this. Could be done in a seperate process.
257 # Alternatively, just don't do this and fetch the current object each time. Most
258 # could probably be taken from cache.
259 relevant_activities = Activity.get_all_create_by_object_ap_id(id)
261 Enum.map(relevant_activities, fn activity ->
262 new_activity_data = activity.data |> Map.put("object", object.data)
263 changeset = Changeset.change(activity, data: new_activity_data)
264 Repo.update(changeset)
268 #### Like-related helpers
271 Returns an existing like if a user already liked an object
273 def get_existing_like(actor, %{data: %{"id" => id}}) do
276 activity in Activity,
277 where: fragment("(?)->>'actor' = ?", activity.data, ^actor),
278 # this is to use the index
281 "coalesce((?)->'object'->>'id', (?)->>'object') = ?",
286 where: fragment("(?)->>'type' = 'Like'", activity.data)
293 Returns like activities targeting an object
295 def get_object_likes(%{data: %{"id" => id}}) do
298 activity in Activity,
299 # this is to use the index
302 "coalesce((?)->'object'->>'id', (?)->>'object') = ?",
307 where: fragment("(?)->>'type' = 'Like'", activity.data)
314 %User{ap_id: ap_id} = actor,
315 %{data: %{"actor" => object_actor_id, "id" => id}} = object,
318 object_actor = User.get_cached_by_ap_id(object_actor_id)
321 if Visibility.is_public?(object) do
322 [actor.follower_address, object.data["actor"]]
324 [object.data["actor"]]
328 (object.data["to"] ++ (object.data["cc"] || []))
329 |> List.delete(actor.ap_id)
330 |> List.delete(object_actor.follower_address)
338 "context" => object.data["context"]
341 if activity_id, do: Map.put(data, "id", activity_id), else: data
344 def update_element_in_object(property, element, object) do
347 |> Map.put("#{property}_count", length(element))
348 |> Map.put("#{property}s", element),
349 changeset <- Changeset.change(object, data: new_data),
350 {:ok, object} <- Object.update_and_set_cache(changeset),
351 _ <- update_object_in_activities(object) do
356 def update_likes_in_object(likes, object) do
357 update_element_in_object("like", likes, object)
360 def add_like_to_object(%Activity{data: %{"actor" => actor}}, object) do
361 likes = if is_list(object.data["likes"]), do: object.data["likes"], else: []
363 with likes <- [actor | likes] |> Enum.uniq() do
364 update_likes_in_object(likes, object)
368 def remove_like_from_object(%Activity{data: %{"actor" => actor}}, object) do
369 likes = if is_list(object.data["likes"]), do: object.data["likes"], else: []
371 with likes <- likes |> List.delete(actor) do
372 update_likes_in_object(likes, object)
376 #### Follow-related helpers
379 Updates a follow activity's state (for locked accounts).
381 def update_follow_state_for_all(
382 %Activity{data: %{"actor" => actor, "object" => object}} = activity,
386 Ecto.Adapters.SQL.query!(
388 "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'",
389 [state, actor, object]
392 activity = Activity.get_by_id(activity.id)
400 def update_follow_state(%Activity{} = activity, state) do
403 |> Map.put("state", state),
404 changeset <- Changeset.change(activity, data: new_data),
405 {:ok, activity} <- Repo.update(changeset) do
411 Makes a follow activity data for the given follower and followed
413 def make_follow_data(
414 %User{ap_id: follower_id},
415 %User{ap_id: followed_id} = _followed,
420 "actor" => follower_id,
421 "to" => [followed_id],
422 "cc" => ["https://www.w3.org/ns/activitystreams#Public"],
423 "object" => followed_id,
427 data = if activity_id, do: Map.put(data, "id", activity_id), else: data
432 def fetch_latest_follow(%User{ap_id: follower_id}, %User{ap_id: followed_id}) do
435 activity in Activity,
438 "? ->> 'type' = 'Follow'",
441 where: activity.actor == ^follower_id,
442 # this is to use the index
445 "coalesce((?)->'object'->>'id', (?)->>'object') = ?",
450 order_by: [fragment("? desc nulls last", activity.id)],
457 #### Announce-related helpers
460 Retruns an existing announce activity if the notice has already been announced
462 def get_existing_announce(actor, %{data: %{"id" => id}}) do
465 activity in Activity,
466 where: activity.actor == ^actor,
467 # this is to use the index
470 "coalesce((?)->'object'->>'id', (?)->>'object') = ?",
475 where: fragment("(?)->>'type' = 'Announce'", activity.data)
482 Make announce activity data for the given actor and object
484 # for relayed messages, we only want to send to subscribers
485 def make_announce_data(
486 %User{ap_id: ap_id} = user,
487 %Object{data: %{"id" => id}} = object,
492 "type" => "Announce",
495 "to" => [user.follower_address],
497 "context" => object.data["context"]
500 if activity_id, do: Map.put(data, "id", activity_id), else: data
503 def make_announce_data(
504 %User{ap_id: ap_id} = user,
505 %Object{data: %{"id" => id}} = object,
510 "type" => "Announce",
513 "to" => [user.follower_address, object.data["actor"]],
514 "cc" => ["https://www.w3.org/ns/activitystreams#Public"],
515 "context" => object.data["context"]
518 if activity_id, do: Map.put(data, "id", activity_id), else: data
522 Make unannounce activity data for the given actor and object
524 def make_unannounce_data(
525 %User{ap_id: ap_id} = user,
526 %Activity{data: %{"context" => context}} = activity,
532 "object" => activity.data,
533 "to" => [user.follower_address, activity.data["actor"]],
534 "cc" => ["https://www.w3.org/ns/activitystreams#Public"],
538 if activity_id, do: Map.put(data, "id", activity_id), else: data
541 def make_unlike_data(
542 %User{ap_id: ap_id} = user,
543 %Activity{data: %{"context" => context}} = activity,
549 "object" => activity.data,
550 "to" => [user.follower_address, activity.data["actor"]],
551 "cc" => ["https://www.w3.org/ns/activitystreams#Public"],
555 if activity_id, do: Map.put(data, "id", activity_id), else: data
558 def add_announce_to_object(
560 data: %{"actor" => actor, "cc" => ["https://www.w3.org/ns/activitystreams#Public"]}
565 if is_list(object.data["announcements"]), do: object.data["announcements"], else: []
567 with announcements <- [actor | announcements] |> Enum.uniq() do
568 update_element_in_object("announcement", announcements, object)
572 def add_announce_to_object(_, object), do: {:ok, object}
574 def remove_announce_from_object(%Activity{data: %{"actor" => actor}}, object) do
576 if is_list(object.data["announcements"]), do: object.data["announcements"], else: []
578 with announcements <- announcements |> List.delete(actor) do
579 update_element_in_object("announcement", announcements, object)
583 #### Unfollow-related helpers
585 def make_unfollow_data(follower, followed, follow_activity, activity_id) do
588 "actor" => follower.ap_id,
589 "to" => [followed.ap_id],
590 "object" => follow_activity.data
593 if activity_id, do: Map.put(data, "id", activity_id), else: data
596 #### Block-related helpers
597 def fetch_latest_block(%User{ap_id: blocker_id}, %User{ap_id: blocked_id}) do
600 activity in Activity,
603 "? ->> 'type' = 'Block'",
606 where: activity.actor == ^blocker_id,
607 # this is to use the index
610 "coalesce((?)->'object'->>'id', (?)->>'object') = ?",
615 order_by: [fragment("? desc nulls last", activity.id)],
622 def make_block_data(blocker, blocked, activity_id) do
625 "actor" => blocker.ap_id,
626 "to" => [blocked.ap_id],
627 "object" => blocked.ap_id
630 if activity_id, do: Map.put(data, "id", activity_id), else: data
633 def make_unblock_data(blocker, blocked, block_activity, activity_id) do
636 "actor" => blocker.ap_id,
637 "to" => [blocked.ap_id],
638 "object" => block_activity.data
641 if activity_id, do: Map.put(data, "id", activity_id), else: data
644 #### Create-related helpers
646 def make_create_data(params, additional) do
647 published = params.published || make_date()
651 "to" => params.to |> Enum.uniq(),
652 "actor" => params.actor.ap_id,
653 "object" => params.object,
654 "published" => published,
655 "context" => params.context
657 |> Map.merge(additional)
660 #### Flag-related helpers
662 def make_flag_data(params, additional) do
664 Enum.map(params.statuses || [], fn
665 %Activity{} = act -> act.data["id"]
666 act when is_map(act) -> act["id"]
667 act when is_binary(act) -> act
670 object = [params.account.ap_id] ++ status_ap_ids
674 "actor" => params.actor.ap_id,
675 "content" => params.content,
677 "context" => params.context,
680 |> Map.merge(additional)
684 Fetches the OrderedCollection/OrderedCollectionPage from `from`, limiting the amount of pages fetched after
685 the first one to `pages_left` pages.
686 If the amount of pages is higher than the collection has, it returns whatever was there.
688 def fetch_ordered_collection(from, pages_left, acc \\ []) do
689 with {:ok, response} <- Tesla.get(from),
690 {:ok, collection} <- Jason.decode(response.body) do
691 case collection["type"] do
692 "OrderedCollection" ->
693 # If we've encountered the OrderedCollection and not the page,
694 # just call the same function on the page address
695 fetch_ordered_collection(collection["first"], pages_left)
697 "OrderedCollectionPage" ->
699 # There are still more pages
700 if Map.has_key?(collection, "next") do
701 # There are still more pages, go deeper saving what we have into the accumulator
702 fetch_ordered_collection(
705 acc ++ collection["orderedItems"]
708 # No more pages left, just return whatever we already have
709 acc ++ collection["orderedItems"]
712 # Got the amount of pages needed, add them all to the accumulator
713 acc ++ collection["orderedItems"]
717 {:error, "Not an OrderedCollection or OrderedCollectionPage"}
722 #### Report-related helpers
724 def update_report_state(%Activity{} = activity, state) when state in @supported_report_states do
725 with new_data <- Map.put(activity.data, "state", state),
726 changeset <- Changeset.change(activity, data: new_data),
727 {:ok, activity} <- Repo.update(changeset) do
732 def update_report_state(_, _), do: {:error, "Unsupported state"}
734 def update_activity_visibility(activity, visibility) when visibility in @valid_visibilities do
735 [to, cc, recipients] =
737 |> get_updated_targets(visibility)
738 |> Enum.map(&Enum.uniq/1)
747 |> Object.change(%{data: object_data})
748 |> Object.update_and_set_cache()
756 |> Map.put(:object, object)
757 |> Activity.change(%{data: activity_data, recipients: recipients})
761 def update_activity_visibility(_, _), do: {:error, "Unsupported visibility"}
763 defp get_updated_targets(
764 %Activity{data: %{"to" => to} = data, recipients: recipients},
767 cc = Map.get(data, "cc", [])
768 follower_address = User.get_cached_by_ap_id(data["actor"]).follower_address
769 public = "https://www.w3.org/ns/activitystreams#Public"
773 to = [public | List.delete(to, follower_address)]
774 cc = [follower_address | List.delete(cc, public)]
775 recipients = [public | recipients]
779 to = [follower_address | List.delete(to, public)]
780 cc = List.delete(cc, public)
781 recipients = List.delete(recipients, public)
785 to = [follower_address | List.delete(to, public)]
786 cc = [public | List.delete(cc, follower_address)]
787 recipients = recipients ++ [follower_address, public]
795 def get_existing_votes(actor, %{data: %{"id" => id}}) do
798 [activity, object: object] in Activity.with_preloaded_object(Activity),
799 where: fragment("(?)->>'type' = 'Create'", activity.data),
800 where: fragment("(?)->>'actor' = ?", activity.data, ^actor),
803 "(?)->>'inReplyTo' = ?",
807 where: fragment("(?)->>'type' = 'Answer'", object.data)