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"]
24 # Some implementations send the actor URI as the actor field, others send the entire actor object,
25 # so figure out what the actor's URI is based on what we have.
26 def get_ap_id(object) do
33 def normalize_params(params) do
34 Map.put(params, "actor", get_ap_id(params["actor"]))
37 def determine_explicit_mentions(%{"tag" => tag} = _object) when is_list(tag) do
39 |> Enum.filter(fn x -> is_map(x) end)
40 |> Enum.filter(fn x -> x["type"] == "Mention" end)
41 |> Enum.map(fn x -> x["href"] end)
44 def determine_explicit_mentions(%{"tag" => tag} = object) when is_map(tag) do
45 Map.put(object, "tag", [tag])
46 |> determine_explicit_mentions()
49 def determine_explicit_mentions(_), do: []
51 defp recipient_in_collection(ap_id, coll) when is_binary(coll), do: ap_id == coll
52 defp recipient_in_collection(ap_id, coll) when is_list(coll), do: ap_id in coll
53 defp recipient_in_collection(_, _), do: false
55 def recipient_in_message(ap_id, params) do
57 recipient_in_collection(ap_id, params["to"]) ->
60 recipient_in_collection(ap_id, params["cc"]) ->
63 recipient_in_collection(ap_id, params["bto"]) ->
66 recipient_in_collection(ap_id, params["bcc"]) ->
69 # if the message is unaddressed at all, then assume it is directly addressed
71 !params["to"] && !params["cc"] && !params["bto"] && !params["bcc"] ->
79 defp extract_list(target) when is_binary(target), do: [target]
80 defp extract_list(lst) when is_list(lst), do: lst
81 defp extract_list(_), do: []
83 def maybe_splice_recipient(ap_id, params) do
85 !recipient_in_collection(ap_id, params["to"]) &&
86 !recipient_in_collection(ap_id, params["cc"])
88 cc_list = extract_list(params["cc"])
92 |> Map.put("cc", [ap_id | cc_list])
98 def make_json_ld_header do
101 "https://www.w3.org/ns/activitystreams",
102 "#{Web.base_url()}/schemas/litepub-0.1.jsonld"
108 DateTime.utc_now() |> DateTime.to_iso8601()
111 def generate_activity_id do
112 generate_id("activities")
115 def generate_context_id do
116 generate_id("contexts")
119 def generate_object_id do
120 Helpers.o_status_url(Endpoint, :object, UUID.generate())
123 def generate_id(type) do
124 "#{Web.base_url()}/#{type}/#{UUID.generate()}"
127 def get_notified_from_object(%{"type" => type} = object) when type in @supported_object_types do
128 fake_create_activity = %{
129 "to" => object["to"],
130 "cc" => object["cc"],
135 Notification.get_notified_from_activity(%Activity{data: fake_create_activity}, false)
138 def get_notified_from_object(object) do
139 Notification.get_notified_from_activity(%Activity{data: object}, false)
142 def create_context(context) do
143 context = context || generate_id("contexts")
144 changeset = Object.context_mapping(context)
146 case Repo.insert(changeset) do
150 # This should be solved by an upsert, but it seems ecto
151 # has problems accessing the constraint inside the jsonb.
153 Object.get_cached_by_ap_id(context)
158 Enqueues an activity for federation if it's local
160 def maybe_federate(%Activity{local: true} = activity) do
162 case activity.data["type"] do
168 Pleroma.Web.Federator.publish(activity, priority)
172 def maybe_federate(_), do: :ok
175 Adds an id and a published data if they aren't there,
176 also adds it to an included object
178 def lazy_put_activity_defaults(map) do
179 %{data: %{"id" => context}, id: context_id} = create_context(map["context"])
183 |> Map.put_new_lazy("id", &generate_activity_id/0)
184 |> Map.put_new_lazy("published", &make_date/0)
185 |> Map.put_new("context", context)
186 |> Map.put_new("context_id", context_id)
188 if is_map(map["object"]) do
189 object = lazy_put_object_defaults(map["object"], map)
190 %{map | "object" => object}
197 Adds an id and published date if they aren't there.
199 def lazy_put_object_defaults(map, activity \\ %{}) do
201 |> Map.put_new_lazy("id", &generate_object_id/0)
202 |> Map.put_new_lazy("published", &make_date/0)
203 |> Map.put_new("context", activity["context"])
204 |> Map.put_new("context_id", activity["context_id"])
208 Inserts a full object if it is contained in an activity.
210 def insert_full_object(%{"object" => %{"type" => type} = object_data})
211 when is_map(object_data) and type in @supported_object_types do
212 with {:ok, object} <- Object.create(object_data) do
217 def insert_full_object(_), do: {:ok, nil}
219 def update_object_in_activities(%{data: %{"id" => id}} = object) do
221 # Update activities that already had this. Could be done in a seperate process.
222 # Alternatively, just don't do this and fetch the current object each time. Most
223 # could probably be taken from cache.
224 relevant_activities = Activity.get_all_create_by_object_ap_id(id)
226 Enum.map(relevant_activities, fn activity ->
227 new_activity_data = activity.data |> Map.put("object", object.data)
228 changeset = Changeset.change(activity, data: new_activity_data)
229 Repo.update(changeset)
233 #### Like-related helpers
236 Returns an existing like if a user already liked an object
238 def get_existing_like(actor, %{data: %{"id" => id}}) do
241 activity in Activity,
242 where: fragment("(?)->>'actor' = ?", activity.data, ^actor),
243 # this is to use the index
246 "coalesce((?)->'object'->>'id', (?)->>'object') = ?",
251 where: fragment("(?)->>'type' = 'Like'", activity.data)
258 Returns like activities targeting an object
260 def get_object_likes(%{data: %{"id" => id}}) do
263 activity in Activity,
264 # this is to use the index
267 "coalesce((?)->'object'->>'id', (?)->>'object') = ?",
272 where: fragment("(?)->>'type' = 'Like'", activity.data)
279 %User{ap_id: ap_id} = actor,
280 %{data: %{"actor" => object_actor_id, "id" => id}} = object,
283 object_actor = User.get_cached_by_ap_id(object_actor_id)
286 if Visibility.is_public?(object) do
287 [actor.follower_address, object.data["actor"]]
289 [object.data["actor"]]
293 (object.data["to"] ++ (object.data["cc"] || []))
294 |> List.delete(actor.ap_id)
295 |> List.delete(object_actor.follower_address)
303 "context" => object.data["context"]
306 if activity_id, do: Map.put(data, "id", activity_id), else: data
309 def update_element_in_object(property, element, object) do
312 |> Map.put("#{property}_count", length(element))
313 |> Map.put("#{property}s", element),
314 changeset <- Changeset.change(object, data: new_data),
315 {:ok, object} <- Object.update_and_set_cache(changeset),
316 _ <- update_object_in_activities(object) do
321 def update_likes_in_object(likes, object) do
322 update_element_in_object("like", likes, object)
325 def add_like_to_object(%Activity{data: %{"actor" => actor}}, object) do
326 likes = if is_list(object.data["likes"]), do: object.data["likes"], else: []
328 with likes <- [actor | likes] |> Enum.uniq() do
329 update_likes_in_object(likes, object)
333 def remove_like_from_object(%Activity{data: %{"actor" => actor}}, object) do
334 likes = if is_list(object.data["likes"]), do: object.data["likes"], else: []
336 with likes <- likes |> List.delete(actor) do
337 update_likes_in_object(likes, object)
341 #### Follow-related helpers
344 Updates a follow activity's state (for locked accounts).
346 def update_follow_state(
347 %Activity{data: %{"actor" => actor, "object" => object, "state" => "pending"}} = activity,
351 Ecto.Adapters.SQL.query!(
353 "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'",
354 [state, actor, object]
357 activity = Repo.get(Activity, activity.id)
365 def update_follow_state(%Activity{} = activity, state) do
368 |> Map.put("state", state),
369 changeset <- Changeset.change(activity, data: new_data),
370 {:ok, activity} <- Repo.update(changeset) do
376 Makes a follow activity data for the given follower and followed
378 def make_follow_data(
379 %User{ap_id: follower_id},
380 %User{ap_id: followed_id} = _followed,
385 "actor" => follower_id,
386 "to" => [followed_id],
387 "cc" => ["https://www.w3.org/ns/activitystreams#Public"],
388 "object" => followed_id,
392 data = if activity_id, do: Map.put(data, "id", activity_id), else: data
397 def fetch_latest_follow(%User{ap_id: follower_id}, %User{ap_id: followed_id}) do
400 activity in Activity,
403 "? ->> 'type' = 'Follow'",
406 where: activity.actor == ^follower_id,
407 # this is to use the index
410 "coalesce((?)->'object'->>'id', (?)->>'object') = ?",
415 order_by: [fragment("? desc nulls last", activity.id)],
422 #### Announce-related helpers
425 Retruns an existing announce activity if the notice has already been announced
427 def get_existing_announce(actor, %{data: %{"id" => id}}) do
430 activity in Activity,
431 where: activity.actor == ^actor,
432 # this is to use the index
435 "coalesce((?)->'object'->>'id', (?)->>'object') = ?",
440 where: fragment("(?)->>'type' = 'Announce'", activity.data)
447 Make announce activity data for the given actor and object
449 # for relayed messages, we only want to send to subscribers
450 def make_announce_data(
451 %User{ap_id: ap_id} = user,
452 %Object{data: %{"id" => id}} = object,
457 "type" => "Announce",
460 "to" => [user.follower_address],
462 "context" => object.data["context"]
465 if activity_id, do: Map.put(data, "id", activity_id), else: data
468 def make_announce_data(
469 %User{ap_id: ap_id} = user,
470 %Object{data: %{"id" => id}} = object,
475 "type" => "Announce",
478 "to" => [user.follower_address, object.data["actor"]],
479 "cc" => ["https://www.w3.org/ns/activitystreams#Public"],
480 "context" => object.data["context"]
483 if activity_id, do: Map.put(data, "id", activity_id), else: data
487 Make unannounce activity data for the given actor and object
489 def make_unannounce_data(
490 %User{ap_id: ap_id} = user,
491 %Activity{data: %{"context" => context}} = activity,
497 "object" => activity.data,
498 "to" => [user.follower_address, activity.data["actor"]],
499 "cc" => ["https://www.w3.org/ns/activitystreams#Public"],
503 if activity_id, do: Map.put(data, "id", activity_id), else: data
506 def make_unlike_data(
507 %User{ap_id: ap_id} = user,
508 %Activity{data: %{"context" => context}} = activity,
514 "object" => activity.data,
515 "to" => [user.follower_address, activity.data["actor"]],
516 "cc" => ["https://www.w3.org/ns/activitystreams#Public"],
520 if activity_id, do: Map.put(data, "id", activity_id), else: data
523 def add_announce_to_object(
525 data: %{"actor" => actor, "cc" => ["https://www.w3.org/ns/activitystreams#Public"]}
530 if is_list(object.data["announcements"]), do: object.data["announcements"], else: []
532 with announcements <- [actor | announcements] |> Enum.uniq() do
533 update_element_in_object("announcement", announcements, object)
537 def add_announce_to_object(_, object), do: {:ok, object}
539 def remove_announce_from_object(%Activity{data: %{"actor" => actor}}, object) do
541 if is_list(object.data["announcements"]), do: object.data["announcements"], else: []
543 with announcements <- announcements |> List.delete(actor) do
544 update_element_in_object("announcement", announcements, object)
548 #### Unfollow-related helpers
550 def make_unfollow_data(follower, followed, follow_activity, activity_id) do
553 "actor" => follower.ap_id,
554 "to" => [followed.ap_id],
555 "object" => follow_activity.data
558 if activity_id, do: Map.put(data, "id", activity_id), else: data
561 #### Block-related helpers
562 def fetch_latest_block(%User{ap_id: blocker_id}, %User{ap_id: blocked_id}) do
565 activity in Activity,
568 "? ->> 'type' = 'Block'",
571 where: activity.actor == ^blocker_id,
572 # this is to use the index
575 "coalesce((?)->'object'->>'id', (?)->>'object') = ?",
580 order_by: [fragment("? desc nulls last", activity.id)],
587 def make_block_data(blocker, blocked, activity_id) do
590 "actor" => blocker.ap_id,
591 "to" => [blocked.ap_id],
592 "object" => blocked.ap_id
595 if activity_id, do: Map.put(data, "id", activity_id), else: data
598 def make_unblock_data(blocker, blocked, block_activity, activity_id) do
601 "actor" => blocker.ap_id,
602 "to" => [blocked.ap_id],
603 "object" => block_activity.data
606 if activity_id, do: Map.put(data, "id", activity_id), else: data
609 #### Create-related helpers
611 def make_create_data(params, additional) do
612 published = params.published || make_date()
616 "to" => params.to |> Enum.uniq(),
617 "actor" => params.actor.ap_id,
618 "object" => params.object,
619 "published" => published,
620 "context" => params.context
622 |> Map.merge(additional)
625 #### Flag-related helpers
627 def make_flag_data(params, additional) do
629 Enum.map(params.statuses || [], fn
630 %Activity{} = act -> act.data["id"]
631 act when is_map(act) -> act["id"]
632 act when is_binary(act) -> act
635 object = [params.account.ap_id] ++ status_ap_ids
639 "actor" => params.actor.ap_id,
640 "content" => params.content,
642 "context" => params.context
644 |> Map.merge(additional)
648 Fetches the OrderedCollection/OrderedCollectionPage from `from`, limiting the amount of pages fetched after
649 the first one to `pages_left` pages.
650 If the amount of pages is higher than the collection has, it returns whatever was there.
652 def fetch_ordered_collection(from, pages_left, acc \\ []) do
653 with {:ok, response} <- Tesla.get(from),
654 {:ok, collection} <- Poison.decode(response.body) do
655 case collection["type"] do
656 "OrderedCollection" ->
657 # If we've encountered the OrderedCollection and not the page,
658 # just call the same function on the page address
659 fetch_ordered_collection(collection["first"], pages_left)
661 "OrderedCollectionPage" ->
663 # There are still more pages
664 if Map.has_key?(collection, "next") do
665 # There are still more pages, go deeper saving what we have into the accumulator
666 fetch_ordered_collection(
669 acc ++ collection["orderedItems"]
672 # No more pages left, just return whatever we already have
673 acc ++ collection["orderedItems"]
676 # Got the amount of pages needed, add them all to the accumulator
677 acc ++ collection["orderedItems"]
681 {:error, "Not an OrderedCollection or OrderedCollectionPage"}