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
11 alias Pleroma.Notification
12 alias Pleroma.Web.Router.Helpers
13 alias Pleroma.Web.Endpoint
21 @supported_object_types ["Article", "Note", "Video", "Page"]
23 # Some implementations send the actor URI as the actor field, others send the entire actor object,
24 # so figure out what the actor's URI is based on what we have.
25 def get_ap_id(object) do
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(ap_id, 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"] ->
78 defp extract_list(target) when is_binary(target), do: [target]
79 defp extract_list(lst) when is_list(lst), do: lst
80 defp extract_list(_), do: []
82 def maybe_splice_recipient(ap_id, params) do
84 !recipient_in_collection(ap_id, params["to"]) &&
85 !recipient_in_collection(ap_id, params["cc"])
87 cc_list = extract_list(params["cc"])
91 |> Map.put("cc", [ap_id | cc_list])
97 def make_json_ld_header do
100 "https://www.w3.org/ns/activitystreams",
101 "#{Web.base_url()}/schemas/litepub-0.1.jsonld"
107 DateTime.utc_now() |> DateTime.to_iso8601()
110 def generate_activity_id do
111 generate_id("activities")
114 def generate_context_id do
115 generate_id("contexts")
118 def generate_object_id do
119 Helpers.o_status_url(Endpoint, :object, UUID.generate())
122 def generate_id(type) do
123 "#{Web.base_url()}/#{type}/#{UUID.generate()}"
126 def get_notified_from_object(%{"type" => type} = object) when type in @supported_object_types do
127 fake_create_activity = %{
128 "to" => object["to"],
129 "cc" => object["cc"],
134 Notification.get_notified_from_activity(%Activity{data: fake_create_activity}, false)
137 def get_notified_from_object(object) do
138 Notification.get_notified_from_activity(%Activity{data: object}, false)
141 def create_context(context) do
142 context = context || generate_id("contexts")
143 changeset = Object.context_mapping(context)
145 case Repo.insert(changeset) do
149 # This should be solved by an upsert, but it seems ecto
150 # has problems accessing the constraint inside the jsonb.
152 Object.get_cached_by_ap_id(context)
157 Enqueues an activity for federation if it's local
159 def maybe_federate(%Activity{local: true} = activity) do
161 case activity.data["type"] do
167 Pleroma.Web.Federator.enqueue(:publish, activity, priority)
171 def maybe_federate(_), do: :ok
174 Adds an id and a published data if they aren't there,
175 also adds it to an included object
177 def lazy_put_activity_defaults(map) do
178 %{data: %{"id" => context}, id: context_id} = create_context(map["context"])
182 |> Map.put_new_lazy("id", &generate_activity_id/0)
183 |> Map.put_new_lazy("published", &make_date/0)
184 |> Map.put_new("context", context)
185 |> Map.put_new("context_id", context_id)
187 if is_map(map["object"]) do
188 object = lazy_put_object_defaults(map["object"], map)
189 %{map | "object" => object}
196 Adds an id and published date if they aren't there.
198 def lazy_put_object_defaults(map, activity \\ %{}) do
200 |> Map.put_new_lazy("id", &generate_object_id/0)
201 |> Map.put_new_lazy("published", &make_date/0)
202 |> Map.put_new("context", activity["context"])
203 |> Map.put_new("context_id", activity["context_id"])
207 Inserts a full object if it is contained in an activity.
209 def insert_full_object(%{"object" => %{"type" => type} = object_data})
210 when is_map(object_data) and type in @supported_object_types do
211 with {:ok, _} <- Object.create(object_data) do
216 def insert_full_object(_), do: :ok
218 def update_object_in_activities(%{data: %{"id" => id}} = object) do
220 # Update activities that already had this. Could be done in a seperate process.
221 # Alternatively, just don't do this and fetch the current object each time. Most
222 # could probably be taken from cache.
223 relevant_activities = Activity.get_all_create_by_object_ap_id(id)
225 Enum.map(relevant_activities, fn activity ->
226 new_activity_data = activity.data |> Map.put("object", object.data)
227 changeset = Changeset.change(activity, data: new_activity_data)
228 Repo.update(changeset)
232 #### Like-related helpers
235 Returns an existing like if a user already liked an object
237 def get_existing_like(actor, %{data: %{"id" => id}}) do
240 activity in Activity,
241 where: fragment("(?)->>'actor' = ?", activity.data, ^actor),
242 # this is to use the index
245 "coalesce((?)->'object'->>'id', (?)->>'object') = ?",
250 where: fragment("(?)->>'type' = 'Like'", activity.data)
257 Returns like activities targeting an object
259 def get_object_likes(%{data: %{"id" => id}}) do
262 activity in Activity,
263 # this is to use the index
266 "coalesce((?)->'object'->>'id', (?)->>'object') = ?",
271 where: fragment("(?)->>'type' = 'Like'", activity.data)
277 def make_like_data(%User{ap_id: ap_id} = actor, %{data: %{"id" => id}} = object, activity_id) do
282 "to" => [actor.follower_address, object.data["actor"]],
283 "cc" => ["https://www.w3.org/ns/activitystreams#Public"],
284 "context" => object.data["context"]
287 if activity_id, do: Map.put(data, "id", activity_id), else: data
290 def update_element_in_object(property, element, object) do
293 |> Map.put("#{property}_count", length(element))
294 |> Map.put("#{property}s", element),
295 changeset <- Changeset.change(object, data: new_data),
296 {:ok, object} <- Object.update_and_set_cache(changeset),
297 _ <- update_object_in_activities(object) do
302 def update_likes_in_object(likes, object) do
303 update_element_in_object("like", likes, object)
306 def add_like_to_object(%Activity{data: %{"actor" => actor}}, object) do
307 likes = if is_list(object.data["likes"]), do: object.data["likes"], else: []
309 with likes <- [actor | likes] |> Enum.uniq() do
310 update_likes_in_object(likes, object)
314 def remove_like_from_object(%Activity{data: %{"actor" => actor}}, object) do
315 likes = if is_list(object.data["likes"]), do: object.data["likes"], else: []
317 with likes <- likes |> List.delete(actor) do
318 update_likes_in_object(likes, object)
322 #### Follow-related helpers
325 Updates a follow activity's state (for locked accounts).
327 def update_follow_state(
328 %Activity{data: %{"actor" => actor, "object" => object, "state" => "pending"}} = activity,
332 Ecto.Adapters.SQL.query!(
334 "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'",
335 [state, actor, object]
338 activity = Repo.get(Activity, activity.id)
346 def update_follow_state(%Activity{} = activity, state) do
349 |> Map.put("state", state),
350 changeset <- Changeset.change(activity, data: new_data),
351 {:ok, activity} <- Repo.update(changeset) do
357 Makes a follow activity data for the given follower and followed
359 def make_follow_data(
360 %User{ap_id: follower_id},
361 %User{ap_id: followed_id} = _followed,
366 "actor" => follower_id,
367 "to" => [followed_id],
368 "cc" => ["https://www.w3.org/ns/activitystreams#Public"],
369 "object" => followed_id,
373 data = if activity_id, do: Map.put(data, "id", activity_id), else: data
378 def fetch_latest_follow(%User{ap_id: follower_id}, %User{ap_id: followed_id}) do
381 activity in Activity,
384 "? ->> 'type' = 'Follow'",
387 where: activity.actor == ^follower_id,
392 ^%{object: followed_id}
394 order_by: [desc: :id],
401 #### Announce-related helpers
404 Retruns an existing announce activity if the notice has already been announced
406 def get_existing_announce(actor, %{data: %{"id" => id}}) do
409 activity in Activity,
410 where: activity.actor == ^actor,
411 # this is to use the index
414 "coalesce((?)->'object'->>'id', (?)->>'object') = ?",
419 where: fragment("(?)->>'type' = 'Announce'", activity.data)
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"]
444 if activity_id, do: Map.put(data, "id", activity_id), else: data
447 def make_announce_data(
448 %User{ap_id: ap_id} = user,
449 %Object{data: %{"id" => id}} = object,
454 "type" => "Announce",
457 "to" => [user.follower_address, object.data["actor"]],
458 "cc" => ["https://www.w3.org/ns/activitystreams#Public"],
459 "context" => object.data["context"]
462 if activity_id, do: Map.put(data, "id", activity_id), else: data
466 Make unannounce activity data for the given actor and object
468 def make_unannounce_data(
469 %User{ap_id: ap_id} = user,
470 %Activity{data: %{"context" => context}} = activity,
476 "object" => activity.data,
477 "to" => [user.follower_address, activity.data["actor"]],
478 "cc" => ["https://www.w3.org/ns/activitystreams#Public"],
482 if activity_id, do: Map.put(data, "id", activity_id), else: data
485 def make_unlike_data(
486 %User{ap_id: ap_id} = user,
487 %Activity{data: %{"context" => context}} = activity,
493 "object" => activity.data,
494 "to" => [user.follower_address, activity.data["actor"]],
495 "cc" => ["https://www.w3.org/ns/activitystreams#Public"],
499 if activity_id, do: Map.put(data, "id", activity_id), else: data
502 def add_announce_to_object(
504 data: %{"actor" => actor, "cc" => ["https://www.w3.org/ns/activitystreams#Public"]}
509 if is_list(object.data["announcements"]), do: object.data["announcements"], else: []
511 with announcements <- [actor | announcements] |> Enum.uniq() do
512 update_element_in_object("announcement", announcements, object)
516 def add_announce_to_object(_, object), do: {:ok, object}
518 def remove_announce_from_object(%Activity{data: %{"actor" => actor}}, object) do
520 if is_list(object.data["announcements"]), do: object.data["announcements"], else: []
522 with announcements <- announcements |> List.delete(actor) do
523 update_element_in_object("announcement", announcements, object)
527 #### Unfollow-related helpers
529 def make_unfollow_data(follower, followed, follow_activity, activity_id) do
532 "actor" => follower.ap_id,
533 "to" => [followed.ap_id],
534 "object" => follow_activity.data
537 if activity_id, do: Map.put(data, "id", activity_id), else: data
540 #### Block-related helpers
541 def fetch_latest_block(%User{ap_id: blocker_id}, %User{ap_id: blocked_id}) do
544 activity in Activity,
547 "? ->> 'type' = 'Block'",
550 where: activity.actor == ^blocker_id,
555 ^%{object: blocked_id}
557 order_by: [desc: :id],
564 def make_block_data(blocker, blocked, activity_id) do
567 "actor" => blocker.ap_id,
568 "to" => [blocked.ap_id],
569 "object" => blocked.ap_id
572 if activity_id, do: Map.put(data, "id", activity_id), else: data
575 def make_unblock_data(blocker, blocked, block_activity, activity_id) do
578 "actor" => blocker.ap_id,
579 "to" => [blocked.ap_id],
580 "object" => block_activity.data
583 if activity_id, do: Map.put(data, "id", activity_id), else: data
586 #### Create-related helpers
588 def make_create_data(params, additional) do
589 published = params.published || make_date()
593 "to" => params.to |> Enum.uniq(),
594 "actor" => params.actor.ap_id,
595 "object" => params.object,
596 "published" => published,
597 "context" => params.context
599 |> Map.merge(additional)