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"])
93 cc_list = extract_list(params["cc"])
94 Map.put(params, "cc", [ap_id | cc_list])
100 def make_json_ld_header do
103 "https://www.w3.org/ns/activitystreams",
104 "#{Web.base_url()}/schemas/litepub-0.1.jsonld",
113 DateTime.utc_now() |> DateTime.to_iso8601()
116 def generate_activity_id do
117 generate_id("activities")
120 def generate_context_id do
121 generate_id("contexts")
124 def generate_object_id do
125 Helpers.o_status_url(Endpoint, :object, UUID.generate())
128 def generate_id(type) do
129 "#{Web.base_url()}/#{type}/#{UUID.generate()}"
132 def get_notified_from_object(%{"type" => type} = object) when type in @supported_object_types do
133 fake_create_activity = %{
134 "to" => object["to"],
135 "cc" => object["cc"],
140 get_notified_from_object(fake_create_activity)
143 def get_notified_from_object(object) do
144 Notification.get_notified_from_activity(%Activity{data: object}, false)
147 def create_context(context) do
148 context = context || generate_id("contexts")
150 # Ecto has problems accessing the constraint inside the jsonb,
151 # so we explicitly check for the existed object before insert
152 object = Object.get_cached_by_ap_id(context)
154 with true <- is_nil(object),
155 changeset <- Object.context_mapping(context),
156 {:ok, inserted_object} <- Repo.insert(changeset) do
165 Enqueues an activity for federation if it's local
167 @spec maybe_federate(any()) :: :ok
168 def maybe_federate(%Activity{local: true} = activity) do
169 if Pleroma.Config.get!([:instance, :federating]) do
170 Pleroma.Web.Federator.publish(activity)
176 def maybe_federate(_), do: :ok
179 Adds an id and a published data if they aren't there,
180 also adds it to an included object
182 def lazy_put_activity_defaults(map, fake? \\ false) do
185 %{data: %{"id" => context}, id: context_id} = create_context(map["context"])
188 |> Map.put_new_lazy("id", &generate_activity_id/0)
189 |> Map.put_new_lazy("published", &make_date/0)
190 |> Map.put_new("context", context)
191 |> Map.put_new("context_id", context_id)
194 |> Map.put_new("id", "pleroma:fakeid")
195 |> Map.put_new_lazy("published", &make_date/0)
196 |> Map.put_new("context", "pleroma:fakecontext")
197 |> Map.put_new("context_id", -1)
200 if is_map(map["object"]) do
201 object = lazy_put_object_defaults(map["object"], map, fake?)
202 %{map | "object" => object}
209 Adds an id and published date if they aren't there.
211 def lazy_put_object_defaults(map, activity \\ %{}, fake?)
213 def lazy_put_object_defaults(map, activity, true = _fake?) do
215 |> Map.put_new_lazy("published", &make_date/0)
216 |> Map.put_new("id", "pleroma:fake_object_id")
217 |> Map.put_new("context", activity["context"])
218 |> Map.put_new("fake", true)
219 |> Map.put_new("context_id", activity["context_id"])
222 def lazy_put_object_defaults(map, activity, _fake?) do
224 |> Map.put_new_lazy("id", &generate_object_id/0)
225 |> Map.put_new_lazy("published", &make_date/0)
226 |> Map.put_new("context", activity["context"])
227 |> Map.put_new("context_id", activity["context_id"])
231 Inserts a full object if it is contained in an activity.
233 def insert_full_object(%{"object" => %{"type" => type} = object_data} = map)
234 when is_map(object_data) and type in @supported_object_types do
235 with {:ok, object} <- Object.create(object_data) do
236 map = Map.put(map, "object", object.data["id"])
242 def insert_full_object(map), do: {:ok, map, nil}
244 #### Like-related helpers
247 Returns an existing like if a user already liked an object
249 @spec get_existing_like(String.t(), map()) :: Activity.t() | nil
250 def get_existing_like(actor, %{data: %{"id" => id}}) do
252 |> Activity.Queries.by_actor()
253 |> Activity.Queries.by_object_id(id)
254 |> Activity.Queries.by_type("Like")
260 Returns like activities targeting an object
262 def get_object_likes(%{data: %{"id" => id}}) do
264 |> Activity.Queries.by_object_id()
265 |> Activity.Queries.by_type("Like")
269 @spec make_like_data(User.t(), map(), String.t()) :: map()
271 %User{ap_id: ap_id} = actor,
272 %{data: %{"actor" => object_actor_id, "id" => id}} = object,
275 object_actor = User.get_cached_by_ap_id(object_actor_id)
278 if Visibility.is_public?(object) do
279 [actor.follower_address, object.data["actor"]]
281 [object.data["actor"]]
285 (object.data["to"] ++ (object.data["cc"] || []))
286 |> List.delete(actor.ap_id)
287 |> List.delete(object_actor.follower_address)
295 "context" => object.data["context"]
297 |> maybe_put("id", activity_id)
300 @spec update_element_in_object(String.t(), list(any), Object.t()) ::
301 {:ok, Object.t()} | {:error, Ecto.Changeset.t()}
302 def update_element_in_object(property, element, object) do
306 %{"#{property}_count" => length(element), "#{property}s" => element}
310 |> Changeset.change(data: data)
311 |> Object.update_and_set_cache()
314 @spec add_like_to_object(Activity.t(), Object.t()) ::
315 {:ok, Object.t()} | {:error, Ecto.Changeset.t()}
316 def add_like_to_object(%Activity{data: %{"actor" => actor}}, object) do
317 [actor | fetch_likes(object)]
319 |> update_likes_in_object(object)
322 @spec remove_like_from_object(Activity.t(), Object.t()) ::
323 {:ok, Object.t()} | {:error, Ecto.Changeset.t()}
324 def remove_like_from_object(%Activity{data: %{"actor" => actor}}, object) do
327 |> List.delete(actor)
328 |> update_likes_in_object(object)
331 defp update_likes_in_object(likes, object) do
332 update_element_in_object("like", likes, object)
335 defp fetch_likes(object) do
336 if is_list(object.data["likes"]) do
343 #### Follow-related helpers
346 Updates a follow activity's state (for locked accounts).
348 def update_follow_state_for_all(
349 %Activity{data: %{"actor" => actor, "object" => object}} = activity,
353 Ecto.Adapters.SQL.query!(
355 "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'",
356 [state, actor, object]
359 User.set_follow_state_cache(actor, object, state)
360 activity = Activity.get_by_id(activity.id)
368 def update_follow_state(
369 %Activity{data: %{"actor" => actor, "object" => object}} = activity,
372 new_data = Map.put(activity.data, "state", state)
373 changeset = Changeset.change(activity, data: new_data)
375 with {:ok, activity} <- Repo.update(changeset) do
376 User.set_follow_state_cache(actor, object, state)
382 Makes a follow activity data for the given follower and followed
384 def make_follow_data(
385 %User{ap_id: follower_id},
386 %User{ap_id: followed_id} = _followed,
391 "actor" => follower_id,
392 "to" => [followed_id],
393 "cc" => [Pleroma.Constants.as_public()],
394 "object" => followed_id,
397 |> maybe_put("id", activity_id)
400 def fetch_latest_follow(%User{ap_id: follower_id}, %User{ap_id: followed_id}) do
402 |> Activity.Queries.by_type()
403 |> where(actor: ^follower_id)
404 # this is to use the index
405 |> Activity.Queries.by_object_id(followed_id)
406 |> order_by([activity], fragment("? desc nulls last", activity.id))
411 #### Announce-related helpers
414 Retruns an existing announce activity if the notice has already been announced
416 def get_existing_announce(actor, %{data: %{"id" => ap_id}}) do
418 |> Activity.Queries.by_type()
419 |> where(actor: ^actor)
420 # this is to use the index
421 |> Activity.Queries.by_object_id(ap_id)
426 Make announce activity data for the given actor and object
428 # for relayed messages, we only want to send to subscribers
429 def make_announce_data(
430 %User{ap_id: ap_id} = user,
431 %Object{data: %{"id" => id}} = object,
436 "type" => "Announce",
439 "to" => [user.follower_address],
441 "context" => object.data["context"]
443 |> maybe_put("id", activity_id)
446 def make_announce_data(
447 %User{ap_id: ap_id} = user,
448 %Object{data: %{"id" => id}} = object,
453 "type" => "Announce",
456 "to" => [user.follower_address, object.data["actor"]],
457 "cc" => [Pleroma.Constants.as_public()],
458 "context" => object.data["context"]
460 |> maybe_put("id", activity_id)
464 Make unannounce activity data for the given actor and object
466 def make_unannounce_data(
467 %User{ap_id: ap_id} = user,
468 %Activity{data: %{"context" => context}} = activity,
474 "object" => activity.data,
475 "to" => [user.follower_address, activity.data["actor"]],
476 "cc" => [Pleroma.Constants.as_public()],
479 |> maybe_put("id", activity_id)
482 def make_unlike_data(
483 %User{ap_id: ap_id} = user,
484 %Activity{data: %{"context" => context}} = activity,
490 "object" => activity.data,
491 "to" => [user.follower_address, activity.data["actor"]],
492 "cc" => [Pleroma.Constants.as_public()],
495 |> maybe_put("id", activity_id)
498 def add_announce_to_object(
500 data: %{"actor" => actor, "cc" => [Pleroma.Constants.as_public()]}
505 if is_list(object.data["announcements"]) do
506 Enum.uniq([actor | object.data["announcements"]])
511 update_element_in_object("announcement", announcements, object)
514 def add_announce_to_object(_, object), do: {:ok, object}
516 def remove_announce_from_object(%Activity{data: %{"actor" => actor}}, object) do
518 if is_list(object.data["announcements"]), do: object.data["announcements"], else: []
520 with announcements <- announcements |> List.delete(actor) do
521 update_element_in_object("announcement", announcements, object)
525 #### Unfollow-related helpers
527 def make_unfollow_data(follower, followed, follow_activity, activity_id) do
530 "actor" => follower.ap_id,
531 "to" => [followed.ap_id],
532 "object" => follow_activity.data
534 |> maybe_put("id", activity_id)
537 #### Block-related helpers
538 def fetch_latest_block(%User{ap_id: blocker_id}, %User{ap_id: blocked_id}) do
540 |> Activity.Queries.by_type()
541 |> where(actor: ^blocker_id)
542 # this is to use the index
543 |> Activity.Queries.by_object_id(blocked_id)
544 |> order_by([activity], fragment("? desc nulls last", activity.id))
549 def make_block_data(blocker, blocked, activity_id) do
552 "actor" => blocker.ap_id,
553 "to" => [blocked.ap_id],
554 "object" => blocked.ap_id
556 |> maybe_put("id", activity_id)
559 def make_unblock_data(blocker, blocked, block_activity, activity_id) do
562 "actor" => blocker.ap_id,
563 "to" => [blocked.ap_id],
564 "object" => block_activity.data
566 |> maybe_put("id", activity_id)
569 #### Create-related helpers
571 def make_create_data(params, additional) do
572 published = params.published || make_date()
576 "to" => params.to |> Enum.uniq(),
577 "actor" => params.actor.ap_id,
578 "object" => params.object,
579 "published" => published,
580 "context" => params.context
582 |> Map.merge(additional)
585 #### Flag-related helpers
587 def make_flag_data(params, additional) do
589 Enum.map(params.statuses || [], fn
590 %Activity{} = act -> act.data["id"]
591 act when is_map(act) -> act["id"]
592 act when is_binary(act) -> act
595 object = [params.account.ap_id] ++ status_ap_ids
599 "actor" => params.actor.ap_id,
600 "content" => params.content,
602 "context" => params.context,
605 |> Map.merge(additional)
609 Fetches the OrderedCollection/OrderedCollectionPage from `from`, limiting the amount of pages fetched after
610 the first one to `pages_left` pages.
611 If the amount of pages is higher than the collection has, it returns whatever was there.
613 def fetch_ordered_collection(from, pages_left, acc \\ []) do
614 with {:ok, response} <- Tesla.get(from),
615 {:ok, collection} <- Jason.decode(response.body) do
616 case collection["type"] do
617 "OrderedCollection" ->
618 # If we've encountered the OrderedCollection and not the page,
619 # just call the same function on the page address
620 fetch_ordered_collection(collection["first"], pages_left)
622 "OrderedCollectionPage" ->
624 # There are still more pages
625 if Map.has_key?(collection, "next") do
626 # There are still more pages, go deeper saving what we have into the accumulator
627 fetch_ordered_collection(
630 acc ++ collection["orderedItems"]
633 # No more pages left, just return whatever we already have
634 acc ++ collection["orderedItems"]
637 # Got the amount of pages needed, add them all to the accumulator
638 acc ++ collection["orderedItems"]
642 {:error, "Not an OrderedCollection or OrderedCollectionPage"}
647 #### Report-related helpers
649 def update_report_state(%Activity{} = activity, state) when state in @supported_report_states do
650 new_data = Map.put(activity.data, "state", state)
653 |> Changeset.change(data: new_data)
657 def update_report_state(_, _), do: {:error, "Unsupported state"}
659 def update_activity_visibility(activity, visibility) when visibility in @valid_visibilities do
660 [to, cc, recipients] =
662 |> get_updated_targets(visibility)
663 |> Enum.map(&Enum.uniq/1)
672 |> Object.change(%{data: object_data})
673 |> Object.update_and_set_cache()
681 |> Map.put(:object, object)
682 |> Activity.change(%{data: activity_data, recipients: recipients})
686 def update_activity_visibility(_, _), do: {:error, "Unsupported visibility"}
688 defp get_updated_targets(
689 %Activity{data: %{"to" => to} = data, recipients: recipients},
692 cc = Map.get(data, "cc", [])
693 follower_address = User.get_cached_by_ap_id(data["actor"]).follower_address
694 public = Pleroma.Constants.as_public()
698 to = [public | List.delete(to, follower_address)]
699 cc = [follower_address | List.delete(cc, public)]
700 recipients = [public | recipients]
704 to = [follower_address | List.delete(to, public)]
705 cc = List.delete(cc, public)
706 recipients = List.delete(recipients, public)
710 to = [follower_address | List.delete(to, public)]
711 cc = [public | List.delete(cc, follower_address)]
712 recipients = recipients ++ [follower_address, public]
720 def get_existing_votes(actor, %{data: %{"id" => id}}) do
722 |> Activity.Queries.by_actor()
723 |> Activity.Queries.by_type("Create")
724 |> Activity.with_preloaded_object()
725 |> where([a, object: o], fragment("(?)->>'inReplyTo' = ?", o.data, ^to_string(id)))
726 |> where([a, object: o], fragment("(?)->>'type' = 'Answer'", o.data))
730 defp maybe_put(map, _key, nil), do: map
731 defp maybe_put(map, key, value), do: Map.put(map, key, value)