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
6 alias Pleroma.{Repo, Web, Object, Activity, User, Notification}
7 alias Pleroma.Web.Router.Helpers
8 alias Pleroma.Web.Endpoint
9 alias Ecto.{Changeset, UUID}
13 @supported_object_types ["Article", "Note", "Video", "Page"]
15 # Some implementations send the actor URI as the actor field, others send the entire actor object,
16 # so figure out what the actor's URI is based on what we have.
17 def get_ap_id(object) do
24 def normalize_params(params) do
25 Map.put(params, "actor", get_ap_id(params["actor"]))
28 def determine_explicit_mentions(%{"tag" => tag} = _object) when is_list(tag) do
30 |> Enum.filter(fn x -> is_map(x) end)
31 |> Enum.filter(fn x -> x["type"] == "Mention" end)
32 |> Enum.map(fn x -> x["href"] end)
35 def determine_explicit_mentions(%{"tag" => tag} = object) when is_map(tag) do
36 Map.put(object, "tag", [tag])
37 |> determine_explicit_mentions()
40 def determine_explicit_mentions(_), do: []
42 defp recipient_in_collection(ap_id, coll) when is_binary(coll), do: ap_id == coll
43 defp recipient_in_collection(ap_id, coll) when is_list(coll), do: ap_id in coll
44 defp recipient_in_collection(_, _), do: false
46 def recipient_in_message(ap_id, params) do
48 recipient_in_collection(ap_id, params["to"]) ->
51 recipient_in_collection(ap_id, params["cc"]) ->
54 recipient_in_collection(ap_id, params["bto"]) ->
57 recipient_in_collection(ap_id, params["bcc"]) ->
60 # if the message is unaddressed at all, then assume it is directly addressed
62 !params["to"] && !params["cc"] && !params["bto"] && !params["bcc"] ->
70 defp extract_list(target) when is_binary(target), do: [target]
71 defp extract_list(lst) when is_list(lst), do: lst
72 defp extract_list(_), do: []
74 def maybe_splice_recipient(ap_id, params) do
76 !recipient_in_collection(ap_id, params["to"]) &&
77 !recipient_in_collection(ap_id, params["cc"])
79 cc_list = extract_list(params["cc"])
83 |> Map.put("cc", [ap_id | cc_list])
89 def make_json_ld_header do
92 "https://www.w3.org/ns/activitystreams",
93 "#{Web.base_url()}/schemas/litepub-0.1.jsonld"
99 DateTime.utc_now() |> DateTime.to_iso8601()
102 def generate_activity_id do
103 generate_id("activities")
106 def generate_context_id do
107 generate_id("contexts")
110 def generate_object_id do
111 Helpers.o_status_url(Endpoint, :object, UUID.generate())
114 def generate_id(type) do
115 "#{Web.base_url()}/#{type}/#{UUID.generate()}"
118 def get_notified_from_object(%{"type" => type} = object) when type in @supported_object_types do
119 fake_create_activity = %{
120 "to" => object["to"],
121 "cc" => object["cc"],
126 Notification.get_notified_from_activity(%Activity{data: fake_create_activity}, false)
129 def get_notified_from_object(object) do
130 Notification.get_notified_from_activity(%Activity{data: object}, false)
133 def create_context(context) do
134 context = context || generate_id("contexts")
135 changeset = Object.context_mapping(context)
137 case Repo.insert(changeset) do
141 # This should be solved by an upsert, but it seems ecto
142 # has problems accessing the constraint inside the jsonb.
144 Object.get_cached_by_ap_id(context)
149 Enqueues an activity for federation if it's local
151 def maybe_federate(%Activity{local: true} = activity) do
153 case activity.data["type"] do
159 Pleroma.Web.Federator.enqueue(:publish, activity, priority)
163 def maybe_federate(_), do: :ok
166 Adds an id and a published data if they aren't there,
167 also adds it to an included object
169 def lazy_put_activity_defaults(map) do
170 %{data: %{"id" => context}, id: context_id} = create_context(map["context"])
174 |> Map.put_new_lazy("id", &generate_activity_id/0)
175 |> Map.put_new_lazy("published", &make_date/0)
176 |> Map.put_new("context", context)
177 |> Map.put_new("context_id", context_id)
179 if is_map(map["object"]) do
180 object = lazy_put_object_defaults(map["object"], map)
181 %{map | "object" => object}
188 Adds an id and published date if they aren't there.
190 def lazy_put_object_defaults(map, activity \\ %{}) do
192 |> Map.put_new_lazy("id", &generate_object_id/0)
193 |> Map.put_new_lazy("published", &make_date/0)
194 |> Map.put_new("context", activity["context"])
195 |> Map.put_new("context_id", activity["context_id"])
199 Inserts a full object if it is contained in an activity.
201 def insert_full_object(%{"object" => %{"type" => type} = object_data})
202 when is_map(object_data) and type in @supported_object_types do
203 with {:ok, _} <- Object.create(object_data) do
208 def insert_full_object(_), do: :ok
210 def update_object_in_activities(%{data: %{"id" => id}} = object) do
212 # Update activities that already had this. Could be done in a seperate process.
213 # Alternatively, just don't do this and fetch the current object each time. Most
214 # could probably be taken from cache.
215 relevant_activities = Activity.get_all_create_by_object_ap_id(id)
217 Enum.map(relevant_activities, fn activity ->
218 new_activity_data = activity.data |> Map.put("object", object.data)
219 changeset = Changeset.change(activity, data: new_activity_data)
220 Repo.update(changeset)
224 #### Like-related helpers
227 Returns an existing like if a user already liked an object
229 def get_existing_like(actor, %{data: %{"id" => id}}) do
232 activity in Activity,
233 where: fragment("(?)->>'actor' = ?", activity.data, ^actor),
234 # this is to use the index
237 "coalesce((?)->'object'->>'id', (?)->>'object') = ?",
242 where: fragment("(?)->>'type' = 'Like'", activity.data)
249 Returns like activities targeting an object
251 def get_object_likes(%{data: %{"id" => id}}) do
254 activity in Activity,
255 # this is to use the index
258 "coalesce((?)->'object'->>'id', (?)->>'object') = ?",
263 where: fragment("(?)->>'type' = 'Like'", activity.data)
269 def make_like_data(%User{ap_id: ap_id} = actor, %{data: %{"id" => id}} = object, activity_id) do
274 "to" => [actor.follower_address, object.data["actor"]],
275 "cc" => ["https://www.w3.org/ns/activitystreams#Public"],
276 "context" => object.data["context"]
279 if activity_id, do: Map.put(data, "id", activity_id), else: data
282 def update_element_in_object(property, element, object) do
285 |> Map.put("#{property}_count", length(element))
286 |> Map.put("#{property}s", element),
287 changeset <- Changeset.change(object, data: new_data),
288 {:ok, object} <- Repo.update(changeset),
289 _ <- update_object_in_activities(object) do
294 def update_likes_in_object(likes, object) do
295 update_element_in_object("like", likes, object)
298 def add_like_to_object(%Activity{data: %{"actor" => actor}}, object) do
299 likes = if is_list(object.data["likes"]), do: object.data["likes"], else: []
301 with likes <- [actor | likes] |> Enum.uniq() do
302 update_likes_in_object(likes, object)
306 def remove_like_from_object(%Activity{data: %{"actor" => actor}}, object) do
307 likes = if is_list(object.data["likes"]), do: object.data["likes"], else: []
309 with likes <- likes |> List.delete(actor) do
310 update_likes_in_object(likes, object)
314 #### Follow-related helpers
317 Updates a follow activity's state (for locked accounts).
319 def update_follow_state(
320 %Activity{data: %{"actor" => actor, "object" => object, "state" => "pending"}} = activity,
324 Ecto.Adapters.SQL.query!(
326 "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'",
327 [state, actor, object]
330 activity = Repo.get(Activity, activity.id)
338 def update_follow_state(%Activity{} = activity, state) do
341 |> Map.put("state", state),
342 changeset <- Changeset.change(activity, data: new_data),
343 {:ok, activity} <- Repo.update(changeset) do
349 Makes a follow activity data for the given follower and followed
351 def make_follow_data(
352 %User{ap_id: follower_id},
353 %User{ap_id: followed_id} = _followed,
358 "actor" => follower_id,
359 "to" => [followed_id],
360 "cc" => ["https://www.w3.org/ns/activitystreams#Public"],
361 "object" => followed_id,
365 data = if activity_id, do: Map.put(data, "id", activity_id), else: data
370 def fetch_latest_follow(%User{ap_id: follower_id}, %User{ap_id: followed_id}) do
373 activity in Activity,
376 "? ->> 'type' = 'Follow'",
379 where: activity.actor == ^follower_id,
384 ^%{object: followed_id}
386 order_by: [desc: :id],
393 #### Announce-related helpers
396 Retruns an existing announce activity if the notice has already been announced
398 def get_existing_announce(actor, %{data: %{"id" => id}}) do
401 activity in Activity,
402 where: activity.actor == ^actor,
403 # this is to use the index
406 "coalesce((?)->'object'->>'id', (?)->>'object') = ?",
411 where: fragment("(?)->>'type' = 'Announce'", activity.data)
418 Make announce activity data for the given actor and object
420 # for relayed messages, we only want to send to subscribers
421 def make_announce_data(
422 %User{ap_id: ap_id} = user,
423 %Object{data: %{"id" => id}} = object,
428 "type" => "Announce",
431 "to" => [user.follower_address],
433 "context" => object.data["context"]
436 if activity_id, do: Map.put(data, "id", activity_id), else: data
439 def make_announce_data(
440 %User{ap_id: ap_id} = user,
441 %Object{data: %{"id" => id}} = object,
446 "type" => "Announce",
449 "to" => [user.follower_address, object.data["actor"]],
450 "cc" => ["https://www.w3.org/ns/activitystreams#Public"],
451 "context" => object.data["context"]
454 if activity_id, do: Map.put(data, "id", activity_id), else: data
458 Make unannounce activity data for the given actor and object
460 def make_unannounce_data(
461 %User{ap_id: ap_id} = user,
462 %Activity{data: %{"context" => context}} = activity,
468 "object" => activity.data,
469 "to" => [user.follower_address, activity.data["actor"]],
470 "cc" => ["https://www.w3.org/ns/activitystreams#Public"],
474 if activity_id, do: Map.put(data, "id", activity_id), else: data
477 def make_unlike_data(
478 %User{ap_id: ap_id} = user,
479 %Activity{data: %{"context" => context}} = activity,
485 "object" => activity.data,
486 "to" => [user.follower_address, activity.data["actor"]],
487 "cc" => ["https://www.w3.org/ns/activitystreams#Public"],
491 if activity_id, do: Map.put(data, "id", activity_id), else: data
494 def add_announce_to_object(
496 data: %{"actor" => actor, "cc" => ["https://www.w3.org/ns/activitystreams#Public"]}
501 if is_list(object.data["announcements"]), do: object.data["announcements"], else: []
503 with announcements <- [actor | announcements] |> Enum.uniq() do
504 update_element_in_object("announcement", announcements, object)
508 def add_announce_to_object(_, object), do: {:ok, object}
510 def remove_announce_from_object(%Activity{data: %{"actor" => actor}}, object) do
512 if is_list(object.data["announcements"]), do: object.data["announcements"], else: []
514 with announcements <- announcements |> List.delete(actor) do
515 update_element_in_object("announcement", announcements, object)
519 #### Unfollow-related helpers
521 def make_unfollow_data(follower, followed, follow_activity, activity_id) do
524 "actor" => follower.ap_id,
525 "to" => [followed.ap_id],
526 "object" => follow_activity.data
529 if activity_id, do: Map.put(data, "id", activity_id), else: data
532 #### Block-related helpers
533 def fetch_latest_block(%User{ap_id: blocker_id}, %User{ap_id: blocked_id}) do
536 activity in Activity,
539 "? ->> 'type' = 'Block'",
542 where: activity.actor == ^blocker_id,
547 ^%{object: blocked_id}
549 order_by: [desc: :id],
556 def make_block_data(blocker, blocked, activity_id) do
559 "actor" => blocker.ap_id,
560 "to" => [blocked.ap_id],
561 "object" => blocked.ap_id
564 if activity_id, do: Map.put(data, "id", activity_id), else: data
567 def make_unblock_data(blocker, blocked, block_activity, activity_id) do
570 "actor" => blocker.ap_id,
571 "to" => [blocked.ap_id],
572 "object" => block_activity.data
575 if activity_id, do: Map.put(data, "id", activity_id), else: data
578 #### Create-related helpers
580 def make_create_data(params, additional) do
581 published = params.published || make_date()
585 "to" => params.to |> Enum.uniq(),
586 "actor" => params.actor.ap_id,
587 "object" => params.object,
588 "published" => published,
589 "context" => params.context
591 |> Map.merge(additional)