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",
111 DateTime.utc_now() |> DateTime.to_iso8601()
114 def generate_activity_id do
115 generate_id("activities")
118 def generate_context_id do
119 generate_id("contexts")
122 def generate_object_id do
123 Helpers.o_status_url(Endpoint, :object, UUID.generate())
126 def generate_id(type) do
127 "#{Web.base_url()}/#{type}/#{UUID.generate()}"
130 def get_notified_from_object(%{"type" => type} = object) when type in @supported_object_types do
131 fake_create_activity = %{
132 "to" => object["to"],
133 "cc" => object["cc"],
138 Notification.get_notified_from_activity(%Activity{data: fake_create_activity}, false)
141 def get_notified_from_object(object) do
142 Notification.get_notified_from_activity(%Activity{data: object}, false)
145 def create_context(context) do
146 context = context || generate_id("contexts")
147 changeset = Object.context_mapping(context)
149 case Repo.insert(changeset) do
153 # This should be solved by an upsert, but it seems ecto
154 # has problems accessing the constraint inside the jsonb.
156 Object.get_cached_by_ap_id(context)
161 Enqueues an activity for federation if it's local
163 def maybe_federate(%Activity{local: true} = activity) do
165 case activity.data["type"] do
171 Pleroma.Web.Federator.publish(activity, priority)
175 def maybe_federate(_), do: :ok
178 Adds an id and a published data if they aren't there,
179 also adds it to an included object
181 def lazy_put_activity_defaults(map, fake \\ false) do
184 %{data: %{"id" => context}, id: context_id} = create_context(map["context"])
187 |> Map.put_new_lazy("id", &generate_activity_id/0)
188 |> Map.put_new_lazy("published", &make_date/0)
189 |> Map.put_new("context", context)
190 |> Map.put_new("context_id", context_id)
193 |> Map.put_new("id", "pleroma:fakeid")
194 |> Map.put_new_lazy("published", &make_date/0)
195 |> Map.put_new("context", "pleroma:fakecontext")
196 |> Map.put_new("context_id", -1)
199 if is_map(map["object"]) do
200 object = lazy_put_object_defaults(map["object"], map, fake)
201 %{map | "object" => object}
208 Adds an id and published date if they aren't there.
210 def lazy_put_object_defaults(map, activity \\ %{}, fake)
212 def lazy_put_object_defaults(map, activity, true = _fake) do
214 |> Map.put_new_lazy("published", &make_date/0)
215 |> Map.put_new("id", "pleroma:fake_object_id")
216 |> Map.put_new("context", activity["context"])
217 |> Map.put_new("fake", true)
218 |> Map.put_new("context_id", activity["context_id"])
221 def lazy_put_object_defaults(map, activity, _fake) do
223 |> Map.put_new_lazy("id", &generate_object_id/0)
224 |> Map.put_new_lazy("published", &make_date/0)
225 |> Map.put_new("context", activity["context"])
226 |> Map.put_new("context_id", activity["context_id"])
230 Inserts a full object if it is contained in an activity.
232 def insert_full_object(%{"object" => %{"type" => type} = object_data})
233 when is_map(object_data) and type in @supported_object_types do
234 with {:ok, object} <- Object.create(object_data) do
239 def insert_full_object(_), do: {:ok, nil}
241 def update_object_in_activities(%{data: %{"id" => id}} = object) do
243 # Update activities that already had this. Could be done in a seperate process.
244 # Alternatively, just don't do this and fetch the current object each time. Most
245 # could probably be taken from cache.
246 relevant_activities = Activity.get_all_create_by_object_ap_id(id)
248 Enum.map(relevant_activities, fn activity ->
249 new_activity_data = activity.data |> Map.put("object", object.data)
250 changeset = Changeset.change(activity, data: new_activity_data)
251 Repo.update(changeset)
255 #### Like-related helpers
258 Returns an existing like if a user already liked an object
260 def get_existing_like(actor, %{data: %{"id" => id}}) do
263 activity in Activity,
264 where: fragment("(?)->>'actor' = ?", activity.data, ^actor),
265 # this is to use the index
268 "coalesce((?)->'object'->>'id', (?)->>'object') = ?",
273 where: fragment("(?)->>'type' = 'Like'", activity.data)
280 Returns like activities targeting an object
282 def get_object_likes(%{data: %{"id" => id}}) do
285 activity in Activity,
286 # this is to use the index
289 "coalesce((?)->'object'->>'id', (?)->>'object') = ?",
294 where: fragment("(?)->>'type' = 'Like'", activity.data)
301 %User{ap_id: ap_id} = actor,
302 %{data: %{"actor" => object_actor_id, "id" => id}} = object,
305 object_actor = User.get_cached_by_ap_id(object_actor_id)
308 if Visibility.is_public?(object) do
309 [actor.follower_address, object.data["actor"]]
311 [object.data["actor"]]
315 (object.data["to"] ++ (object.data["cc"] || []))
316 |> List.delete(actor.ap_id)
317 |> List.delete(object_actor.follower_address)
325 "context" => object.data["context"]
328 if activity_id, do: Map.put(data, "id", activity_id), else: data
331 def update_element_in_object(property, element, object) do
334 |> Map.put("#{property}_count", length(element))
335 |> Map.put("#{property}s", element),
336 changeset <- Changeset.change(object, data: new_data),
337 {:ok, object} <- Object.update_and_set_cache(changeset),
338 _ <- update_object_in_activities(object) do
343 def update_likes_in_object(likes, object) do
344 update_element_in_object("like", likes, object)
347 def add_like_to_object(%Activity{data: %{"actor" => actor}}, object) do
348 likes = if is_list(object.data["likes"]), do: object.data["likes"], else: []
350 with likes <- [actor | likes] |> Enum.uniq() do
351 update_likes_in_object(likes, object)
355 def remove_like_from_object(%Activity{data: %{"actor" => actor}}, object) do
356 likes = if is_list(object.data["likes"]), do: object.data["likes"], else: []
358 with likes <- likes |> List.delete(actor) do
359 update_likes_in_object(likes, object)
363 #### Follow-related helpers
366 Updates a follow activity's state (for locked accounts).
368 def update_follow_state(
369 %Activity{data: %{"actor" => actor, "object" => object, "state" => "pending"}} = activity,
373 Ecto.Adapters.SQL.query!(
375 "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'",
376 [state, actor, object]
379 activity = Activity.get_by_id(activity.id)
387 def update_follow_state(%Activity{} = activity, state) do
390 |> Map.put("state", state),
391 changeset <- Changeset.change(activity, data: new_data),
392 {:ok, activity} <- Repo.update(changeset) do
398 Makes a follow activity data for the given follower and followed
400 def make_follow_data(
401 %User{ap_id: follower_id},
402 %User{ap_id: followed_id} = _followed,
407 "actor" => follower_id,
408 "to" => [followed_id],
409 "cc" => ["https://www.w3.org/ns/activitystreams#Public"],
410 "object" => followed_id,
414 data = if activity_id, do: Map.put(data, "id", activity_id), else: data
419 def fetch_latest_follow(%User{ap_id: follower_id}, %User{ap_id: followed_id}) do
422 activity in Activity,
425 "? ->> 'type' = 'Follow'",
428 where: activity.actor == ^follower_id,
429 # this is to use the index
432 "coalesce((?)->'object'->>'id', (?)->>'object') = ?",
437 order_by: [fragment("? desc nulls last", activity.id)],
444 #### Announce-related helpers
447 Retruns an existing announce activity if the notice has already been announced
449 def get_existing_announce(actor, %{data: %{"id" => id}}) do
452 activity in Activity,
453 where: activity.actor == ^actor,
454 # this is to use the index
457 "coalesce((?)->'object'->>'id', (?)->>'object') = ?",
462 where: fragment("(?)->>'type' = 'Announce'", activity.data)
469 Make announce activity data for the given actor and object
471 # for relayed messages, we only want to send to subscribers
472 def make_announce_data(
473 %User{ap_id: ap_id} = user,
474 %Object{data: %{"id" => id}} = object,
479 "type" => "Announce",
482 "to" => [user.follower_address],
484 "context" => object.data["context"]
487 if activity_id, do: Map.put(data, "id", activity_id), else: data
490 def make_announce_data(
491 %User{ap_id: ap_id} = user,
492 %Object{data: %{"id" => id}} = object,
497 "type" => "Announce",
500 "to" => [user.follower_address, object.data["actor"]],
501 "cc" => ["https://www.w3.org/ns/activitystreams#Public"],
502 "context" => object.data["context"]
505 if activity_id, do: Map.put(data, "id", activity_id), else: data
509 Make unannounce activity data for the given actor and object
511 def make_unannounce_data(
512 %User{ap_id: ap_id} = user,
513 %Activity{data: %{"context" => context}} = activity,
519 "object" => activity.data,
520 "to" => [user.follower_address, activity.data["actor"]],
521 "cc" => ["https://www.w3.org/ns/activitystreams#Public"],
525 if activity_id, do: Map.put(data, "id", activity_id), else: data
528 def make_unlike_data(
529 %User{ap_id: ap_id} = user,
530 %Activity{data: %{"context" => context}} = activity,
536 "object" => activity.data,
537 "to" => [user.follower_address, activity.data["actor"]],
538 "cc" => ["https://www.w3.org/ns/activitystreams#Public"],
542 if activity_id, do: Map.put(data, "id", activity_id), else: data
545 def add_announce_to_object(
547 data: %{"actor" => actor, "cc" => ["https://www.w3.org/ns/activitystreams#Public"]}
552 if is_list(object.data["announcements"]), do: object.data["announcements"], else: []
554 with announcements <- [actor | announcements] |> Enum.uniq() do
555 update_element_in_object("announcement", announcements, object)
559 def add_announce_to_object(_, object), do: {:ok, object}
561 def remove_announce_from_object(%Activity{data: %{"actor" => actor}}, object) do
563 if is_list(object.data["announcements"]), do: object.data["announcements"], else: []
565 with announcements <- announcements |> List.delete(actor) do
566 update_element_in_object("announcement", announcements, object)
570 #### Unfollow-related helpers
572 def make_unfollow_data(follower, followed, follow_activity, activity_id) do
575 "actor" => follower.ap_id,
576 "to" => [followed.ap_id],
577 "object" => follow_activity.data
580 if activity_id, do: Map.put(data, "id", activity_id), else: data
583 #### Block-related helpers
584 def fetch_latest_block(%User{ap_id: blocker_id}, %User{ap_id: blocked_id}) do
587 activity in Activity,
590 "? ->> 'type' = 'Block'",
593 where: activity.actor == ^blocker_id,
594 # this is to use the index
597 "coalesce((?)->'object'->>'id', (?)->>'object') = ?",
602 order_by: [fragment("? desc nulls last", activity.id)],
609 def make_block_data(blocker, blocked, activity_id) do
612 "actor" => blocker.ap_id,
613 "to" => [blocked.ap_id],
614 "object" => blocked.ap_id
617 if activity_id, do: Map.put(data, "id", activity_id), else: data
620 def make_unblock_data(blocker, blocked, block_activity, activity_id) do
623 "actor" => blocker.ap_id,
624 "to" => [blocked.ap_id],
625 "object" => block_activity.data
628 if activity_id, do: Map.put(data, "id", activity_id), else: data
631 #### Create-related helpers
633 def make_create_data(params, additional) do
634 published = params.published || make_date()
638 "to" => params.to |> Enum.uniq(),
639 "actor" => params.actor.ap_id,
640 "object" => params.object,
641 "published" => published,
642 "context" => params.context
644 |> Map.merge(additional)
647 #### Flag-related helpers
649 def make_flag_data(params, additional) do
651 Enum.map(params.statuses || [], fn
652 %Activity{} = act -> act.data["id"]
653 act when is_map(act) -> act["id"]
654 act when is_binary(act) -> act
657 object = [params.account.ap_id] ++ status_ap_ids
661 "actor" => params.actor.ap_id,
662 "content" => params.content,
664 "context" => params.context
666 |> Map.merge(additional)
670 Fetches the OrderedCollection/OrderedCollectionPage from `from`, limiting the amount of pages fetched after
671 the first one to `pages_left` pages.
672 If the amount of pages is higher than the collection has, it returns whatever was there.
674 def fetch_ordered_collection(from, pages_left, acc \\ []) do
675 with {:ok, response} <- Tesla.get(from),
676 {:ok, collection} <- Poison.decode(response.body) do
677 case collection["type"] do
678 "OrderedCollection" ->
679 # If we've encountered the OrderedCollection and not the page,
680 # just call the same function on the page address
681 fetch_ordered_collection(collection["first"], pages_left)
683 "OrderedCollectionPage" ->
685 # There are still more pages
686 if Map.has_key?(collection, "next") do
687 # There are still more pages, go deeper saving what we have into the accumulator
688 fetch_ordered_collection(
691 acc ++ collection["orderedItems"]
694 # No more pages left, just return whatever we already have
695 acc ++ collection["orderedItems"]
698 # Got the amount of pages needed, add them all to the accumulator
699 acc ++ collection["orderedItems"]
703 {:error, "Not an OrderedCollection or OrderedCollectionPage"}