1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
5 defmodule Pleroma.Web.ActivityPub.ActivityPub do
7 alias Pleroma.Activity.Ir.Topics
9 alias Pleroma.Constants
10 alias Pleroma.Conversation
11 alias Pleroma.Conversation.Participation
12 alias Pleroma.Notification
14 alias Pleroma.Object.Containment
15 alias Pleroma.Object.Fetcher
16 alias Pleroma.Pagination
20 alias Pleroma.Web.ActivityPub.MRF
21 alias Pleroma.Web.ActivityPub.Transmogrifier
22 alias Pleroma.Web.ActivityPub.Utils
23 alias Pleroma.Web.Streamer
24 alias Pleroma.Web.WebFinger
25 alias Pleroma.Workers.BackgroundWorker
28 import Pleroma.Web.ActivityPub.Utils
29 import Pleroma.Web.ActivityPub.Visibility
32 require Pleroma.Constants
34 # For Announce activities, we filter the recipients based on following status for any actors
35 # that match actual users. See issue #164 for more information about why this is necessary.
36 defp get_recipients(%{"type" => "Announce"} = data) do
37 to = Map.get(data, "to", [])
38 cc = Map.get(data, "cc", [])
39 bcc = Map.get(data, "bcc", [])
40 actor = User.get_cached_by_ap_id(data["actor"])
43 Enum.filter(Enum.concat([to, cc, bcc]), fn recipient ->
44 case User.get_cached_by_ap_id(recipient) do
46 user -> User.following?(user, actor)
53 defp get_recipients(%{"type" => "Create"} = data) do
54 to = Map.get(data, "to", [])
55 cc = Map.get(data, "cc", [])
56 bcc = Map.get(data, "bcc", [])
57 actor = Map.get(data, "actor", [])
58 recipients = [to, cc, bcc, [actor]] |> Enum.concat() |> Enum.uniq()
62 defp get_recipients(data) do
63 to = Map.get(data, "to", [])
64 cc = Map.get(data, "cc", [])
65 bcc = Map.get(data, "bcc", [])
66 recipients = Enum.concat([to, cc, bcc])
70 defp check_actor_is_active(actor) do
71 if not is_nil(actor) do
72 with user <- User.get_cached_by_ap_id(actor),
73 false <- user.deactivated do
83 defp check_remote_limit(%{"object" => %{"content" => content}}) when not is_nil(content) do
84 limit = Config.get([:instance, :remote_limit])
85 String.length(content) <= limit
88 defp check_remote_limit(_), do: true
90 def increase_note_count_if_public(actor, object) do
91 if is_public?(object), do: User.increase_note_count(actor), else: {:ok, actor}
94 def decrease_note_count_if_public(actor, object) do
95 if is_public?(object), do: User.decrease_note_count(actor), else: {:ok, actor}
98 def increase_replies_count_if_reply(%{
99 "object" => %{"inReplyTo" => reply_ap_id} = object,
102 if is_public?(object) do
103 Object.increase_replies_count(reply_ap_id)
107 def increase_replies_count_if_reply(_create_data), do: :noop
109 def decrease_replies_count_if_reply(%Object{
110 data: %{"inReplyTo" => reply_ap_id} = object
112 if is_public?(object) do
113 Object.decrease_replies_count(reply_ap_id)
117 def decrease_replies_count_if_reply(_object), do: :noop
119 def increase_poll_votes_if_vote(%{
120 "object" => %{"inReplyTo" => reply_ap_id, "name" => name},
124 Object.increase_vote_count(reply_ap_id, name, actor)
127 def increase_poll_votes_if_vote(_create_data), do: :noop
129 @object_types ["ChatMessage"]
130 @spec persist(map(), keyword()) :: {:ok, Activity.t() | Object.t()}
131 def persist(%{"type" => type} = object, meta) when type in @object_types do
132 with {:ok, object} <- Object.create(object) do
137 def persist(object, meta) do
138 with local <- Keyword.fetch!(meta, :local),
139 {recipients, _, _} <- get_recipients(object),
141 Repo.insert(%Activity{
144 recipients: recipients,
145 actor: object["actor"]
147 {:ok, activity, meta}
151 @spec insert(map(), boolean(), boolean(), boolean()) :: {:ok, Activity.t()} | {:error, any()}
152 def insert(map, local \\ true, fake \\ false, bypass_actor_check \\ false) when is_map(map) do
153 with nil <- Activity.normalize(map),
154 map <- lazy_put_activity_defaults(map, fake),
155 true <- bypass_actor_check || check_actor_is_active(map["actor"]),
156 {_, true} <- {:remote_limit_error, check_remote_limit(map)},
157 {:ok, map} <- MRF.filter(map),
158 {recipients, _, _} = get_recipients(map),
159 {:fake, false, map, recipients} <- {:fake, fake, map, recipients},
160 {:containment, :ok} <- {:containment, Containment.contain_child(map)},
161 {:ok, map, object} <- insert_full_object(map) do
163 Repo.insert(%Activity{
167 recipients: recipients
170 # Splice in the child object if we have one.
172 if not is_nil(object) do
173 Map.put(activity, :object, object)
178 BackgroundWorker.enqueue("fetch_data_for_activity", %{"activity_id" => activity.id})
182 %Activity{} = activity ->
185 {:fake, true, map, recipients} ->
186 activity = %Activity{
190 recipients: recipients,
194 Pleroma.Web.RichMedia.Helpers.fetch_data_for_activity(activity)
202 def notify_and_stream(activity) do
203 Notification.create_notifications(activity)
205 conversation = create_or_bump_conversation(activity, activity.actor)
206 participations = get_participations(conversation)
208 stream_out_participations(participations)
211 defp create_or_bump_conversation(activity, actor) do
212 with {:ok, conversation} <- Conversation.create_or_bump_for(activity),
213 %User{} = user <- User.get_cached_by_ap_id(actor),
214 Participation.mark_as_read(user, conversation) do
219 defp get_participations({:ok, conversation}) do
221 |> Repo.preload(:participations, force: true)
222 |> Map.get(:participations)
225 defp get_participations(_), do: []
227 def stream_out_participations(participations) do
230 |> Repo.preload(:user)
232 Streamer.stream("participation", participations)
235 def stream_out_participations(%Object{data: %{"context" => context}}, user) do
236 with %Conversation{} = conversation <- Conversation.get_for_ap_id(context),
237 conversation = Repo.preload(conversation, :participations),
239 fetch_latest_activity_id_for_context(conversation.ap_id, %{
241 "blocking_user" => user
243 if last_activity_id do
244 stream_out_participations(conversation.participations)
249 def stream_out_participations(_, _), do: :noop
251 def stream_out(%Activity{data: %{"type" => data_type}} = activity)
252 when data_type in ["Create", "Announce", "Delete"] do
254 |> Topics.get_activity_topics()
255 |> Streamer.stream(activity)
258 def stream_out(_activity) do
262 @spec create(map(), boolean()) :: {:ok, Activity.t()} | {:error, any()}
263 def create(params, fake \\ false) do
264 with {:ok, result} <- Repo.transaction(fn -> do_create(params, fake) end) do
269 defp do_create(%{to: to, actor: actor, context: context, object: object} = params, fake) do
270 additional = params[:additional] || %{}
271 # only accept false as false value
272 local = !(params[:local] == false)
273 published = params[:published]
274 quick_insert? = Config.get([:env]) == :benchmark
278 %{to: to, actor: actor, published: published, context: context, object: object},
281 {:ok, activity} <- insert(create_data, local, fake),
282 {:fake, false, activity} <- {:fake, fake, activity},
283 _ <- increase_replies_count_if_reply(create_data),
284 _ <- increase_poll_votes_if_vote(create_data),
285 {:quick_insert, false, activity} <- {:quick_insert, quick_insert?, activity},
286 {:ok, _actor} <- increase_note_count_if_public(actor, activity),
287 _ <- notify_and_stream(activity),
288 :ok <- maybe_federate(activity) do
291 {:quick_insert, true, activity} ->
294 {:fake, true, activity} ->
298 Repo.rollback(message)
302 @spec listen(map()) :: {:ok, Activity.t()} | {:error, any()}
303 def listen(%{to: to, actor: actor, context: context, object: object} = params) do
304 additional = params[:additional] || %{}
305 # only accept false as false value
306 local = !(params[:local] == false)
307 published = params[:published]
311 %{to: to, actor: actor, published: published, context: context, object: object},
314 {:ok, activity} <- insert(listen_data, local),
315 _ <- notify_and_stream(activity),
316 :ok <- maybe_federate(activity) do
321 @spec accept(map()) :: {:ok, Activity.t()} | {:error, any()}
322 def accept(params) do
323 accept_or_reject("Accept", params)
326 @spec reject(map()) :: {:ok, Activity.t()} | {:error, any()}
327 def reject(params) do
328 accept_or_reject("Reject", params)
331 @spec accept_or_reject(String.t(), map()) :: {:ok, Activity.t()} | {:error, any()}
332 def accept_or_reject(type, %{to: to, actor: actor, object: object} = params) do
333 local = Map.get(params, :local, true)
334 activity_id = Map.get(params, :activity_id, nil)
337 %{"to" => to, "type" => type, "actor" => actor.ap_id, "object" => object}
338 |> Utils.maybe_put("id", activity_id),
339 {:ok, activity} <- insert(data, local),
340 _ <- notify_and_stream(activity),
341 :ok <- maybe_federate(activity) do
346 @spec update(map()) :: {:ok, Activity.t()} | {:error, any()}
347 def update(%{to: to, cc: cc, actor: actor, object: object} = params) do
348 local = !(params[:local] == false)
349 activity_id = params[:activity_id]
358 data <- Utils.maybe_put(data, "id", activity_id),
359 {:ok, activity} <- insert(data, local),
360 _ <- notify_and_stream(activity),
361 :ok <- maybe_federate(activity) do
366 @spec announce(User.t(), Object.t(), String.t() | nil, boolean(), boolean()) ::
367 {:ok, Activity.t(), Object.t()} | {:error, any()}
369 %User{ap_id: _} = user,
370 %Object{data: %{"id" => _}} = object,
375 with {:ok, result} <-
376 Repo.transaction(fn -> do_announce(user, object, activity_id, local, public) end) do
381 defp do_announce(user, object, activity_id, local, public) do
382 with true <- is_announceable?(object, user, public),
383 object <- Object.get_by_id(object.id),
384 announce_data <- make_announce_data(user, object, activity_id, public),
385 {:ok, activity} <- insert(announce_data, local),
386 {:ok, object} <- add_announce_to_object(activity, object),
387 _ <- notify_and_stream(activity),
388 :ok <- maybe_federate(activity) do
389 {:ok, activity, object}
391 false -> {:error, false}
392 {:error, error} -> Repo.rollback(error)
396 @spec follow(User.t(), User.t(), String.t() | nil, boolean()) ::
397 {:ok, Activity.t()} | {:error, any()}
398 def follow(follower, followed, activity_id \\ nil, local \\ true) do
399 with {:ok, result} <-
400 Repo.transaction(fn -> do_follow(follower, followed, activity_id, local) end) do
405 defp do_follow(follower, followed, activity_id, local) do
406 with data <- make_follow_data(follower, followed, activity_id),
407 {:ok, activity} <- insert(data, local),
408 _ <- notify_and_stream(activity),
409 :ok <- maybe_federate(activity) do
412 {:error, error} -> Repo.rollback(error)
416 @spec unfollow(User.t(), User.t(), String.t() | nil, boolean()) ::
417 {:ok, Activity.t()} | nil | {:error, any()}
418 def unfollow(follower, followed, activity_id \\ nil, local \\ true) do
419 with {:ok, result} <-
420 Repo.transaction(fn -> do_unfollow(follower, followed, activity_id, local) end) do
425 defp do_unfollow(follower, followed, activity_id, local) do
426 with %Activity{} = follow_activity <- fetch_latest_follow(follower, followed),
427 {:ok, follow_activity} <- update_follow_state(follow_activity, "cancelled"),
428 unfollow_data <- make_unfollow_data(follower, followed, follow_activity, activity_id),
429 {:ok, activity} <- insert(unfollow_data, local),
430 _ <- notify_and_stream(activity),
431 :ok <- maybe_federate(activity) do
435 {:error, error} -> Repo.rollback(error)
439 @spec block(User.t(), User.t(), String.t() | nil, boolean()) ::
440 {:ok, Activity.t()} | {:error, any()}
441 def block(blocker, blocked, activity_id \\ nil, local \\ true) do
442 with {:ok, result} <-
443 Repo.transaction(fn -> do_block(blocker, blocked, activity_id, local) end) do
448 defp do_block(blocker, blocked, activity_id, local) do
449 outgoing_blocks = Config.get([:activitypub, :outgoing_blocks])
450 unfollow_blocked = Config.get([:activitypub, :unfollow_blocked])
452 if unfollow_blocked do
453 follow_activity = fetch_latest_follow(blocker, blocked)
454 if follow_activity, do: unfollow(blocker, blocked, nil, local)
457 with true <- outgoing_blocks,
458 block_data <- make_block_data(blocker, blocked, activity_id),
459 {:ok, activity} <- insert(block_data, local),
460 _ <- notify_and_stream(activity),
461 :ok <- maybe_federate(activity) do
464 {:error, error} -> Repo.rollback(error)
468 @spec flag(map()) :: {:ok, Activity.t()} | {:error, any()}
478 # only accept false as false value
479 local = !(params[:local] == false)
480 forward = !(params[:forward] == false)
482 additional = params[:additional] || %{}
486 Map.merge(additional, %{"to" => [], "cc" => [account.ap_id]})
488 Map.merge(additional, %{"to" => [], "cc" => []})
491 with flag_data <- make_flag_data(params, additional),
492 {:ok, activity} <- insert(flag_data, local),
493 {:ok, stripped_activity} <- strip_report_status_data(activity),
494 _ <- notify_and_stream(activity),
495 :ok <- maybe_federate(stripped_activity) do
496 User.all_superusers()
497 |> Enum.filter(fn user -> not is_nil(user.email) end)
498 |> Enum.each(fn superuser ->
500 |> Pleroma.Emails.AdminEmail.report(actor, account, statuses, content)
501 |> Pleroma.Emails.Mailer.deliver_async()
508 @spec move(User.t(), User.t(), boolean()) :: {:ok, Activity.t()} | {:error, any()}
509 def move(%User{} = origin, %User{} = target, local \\ true) do
512 "actor" => origin.ap_id,
513 "object" => origin.ap_id,
514 "target" => target.ap_id
517 with true <- origin.ap_id in target.also_known_as,
518 {:ok, activity} <- insert(params, local),
519 _ <- notify_and_stream(activity) do
520 maybe_federate(activity)
522 BackgroundWorker.enqueue("move_following", %{
523 "origin_id" => origin.id,
524 "target_id" => target.id
529 false -> {:error, "Target account must have the origin in `alsoKnownAs`"}
534 def fetch_activities_for_context_query(context, opts) do
535 public = [Constants.as_public()]
539 do: [opts["user"].ap_id | User.following(opts["user"])] ++ public,
542 from(activity in Activity)
543 |> maybe_preload_objects(opts)
544 |> maybe_preload_bookmarks(opts)
545 |> maybe_set_thread_muted_field(opts)
546 |> restrict_blocked(opts)
547 |> restrict_recipients(recipients, opts["user"])
551 "?->>'type' = ? and ?->>'context' = ?",
558 |> exclude_poll_votes(opts)
560 |> order_by([activity], desc: activity.id)
563 @spec fetch_activities_for_context(String.t(), keyword() | map()) :: [Activity.t()]
564 def fetch_activities_for_context(context, opts \\ %{}) do
566 |> fetch_activities_for_context_query(opts)
570 @spec fetch_latest_activity_id_for_context(String.t(), keyword() | map()) ::
571 FlakeId.Ecto.CompatType.t() | nil
572 def fetch_latest_activity_id_for_context(context, opts \\ %{}) do
574 |> fetch_activities_for_context_query(Map.merge(%{"skip_preload" => true}, opts))
580 @spec fetch_public_activities(map(), Pagination.type()) :: [Activity.t()]
581 def fetch_public_activities(opts \\ %{}, pagination \\ :keyset) do
582 opts = Map.drop(opts, ["user"])
584 [Constants.as_public()]
585 |> fetch_activities_query(opts)
586 |> restrict_unlisted()
587 |> Pagination.fetch_paginated(opts, pagination)
590 @valid_visibilities ~w[direct unlisted public private]
592 defp restrict_visibility(query, %{visibility: visibility})
593 when is_list(visibility) do
594 if Enum.all?(visibility, &(&1 in @valid_visibilities)) do
600 "activity_visibility(?, ?, ?) = ANY (?)",
610 Logger.error("Could not restrict visibility to #{visibility}")
614 defp restrict_visibility(query, %{visibility: visibility})
615 when visibility in @valid_visibilities do
619 fragment("activity_visibility(?, ?, ?) = ?", a.actor, a.recipients, a.data, ^visibility)
623 defp restrict_visibility(_query, %{visibility: visibility})
624 when visibility not in @valid_visibilities do
625 Logger.error("Could not restrict visibility to #{visibility}")
628 defp restrict_visibility(query, _visibility), do: query
630 defp exclude_visibility(query, %{"exclude_visibilities" => visibility})
631 when is_list(visibility) do
632 if Enum.all?(visibility, &(&1 in @valid_visibilities)) do
637 "activity_visibility(?, ?, ?) = ANY (?)",
645 Logger.error("Could not exclude visibility to #{visibility}")
650 defp exclude_visibility(query, %{"exclude_visibilities" => visibility})
651 when visibility in @valid_visibilities do
656 "activity_visibility(?, ?, ?) = ?",
665 defp exclude_visibility(query, %{"exclude_visibilities" => visibility})
666 when visibility not in [nil | @valid_visibilities] do
667 Logger.error("Could not exclude visibility to #{visibility}")
671 defp exclude_visibility(query, _visibility), do: query
673 defp restrict_thread_visibility(query, _, %{skip_thread_containment: true} = _),
676 defp restrict_thread_visibility(
678 %{"user" => %User{skip_thread_containment: true}},
683 defp restrict_thread_visibility(query, %{"user" => %User{ap_id: ap_id}}, _) do
686 where: fragment("thread_visibility(?, (?)->>'id') = true", ^ap_id, a.data)
690 defp restrict_thread_visibility(query, _, _), do: query
692 def fetch_user_abstract_activities(user, reading_user, params \\ %{}) do
695 |> Map.put("user", reading_user)
696 |> Map.put("actor_id", user.ap_id)
699 user_activities_recipients(%{
700 "godmode" => params["godmode"],
701 "reading_user" => reading_user
704 fetch_activities(recipients, params)
708 def fetch_user_activities(user, reading_user, params \\ %{}) do
711 |> Map.put("type", ["Create", "Announce"])
712 |> Map.put("user", reading_user)
713 |> Map.put("actor_id", user.ap_id)
714 |> Map.put("pinned_activity_ids", user.pinned_activities)
717 if User.blocks?(reading_user, user) do
721 |> Map.put("blocking_user", reading_user)
722 |> Map.put("muting_user", reading_user)
726 user_activities_recipients(%{
727 "godmode" => params["godmode"],
728 "reading_user" => reading_user
731 fetch_activities(recipients, params)
735 def fetch_statuses(reading_user, params) do
738 |> Map.put("type", ["Create", "Announce"])
741 user_activities_recipients(%{
742 "godmode" => params["godmode"],
743 "reading_user" => reading_user
746 fetch_activities(recipients, params, :offset)
750 defp user_activities_recipients(%{"godmode" => true}) do
754 defp user_activities_recipients(%{"reading_user" => reading_user}) do
756 [Constants.as_public()] ++ [reading_user.ap_id | User.following(reading_user)]
758 [Constants.as_public()]
762 defp restrict_since(query, %{"since_id" => ""}), do: query
764 defp restrict_since(query, %{"since_id" => since_id}) do
765 from(activity in query, where: activity.id > ^since_id)
768 defp restrict_since(query, _), do: query
770 defp restrict_tag_reject(_query, %{"tag_reject" => _tag_reject, "skip_preload" => true}) do
771 raise "Can't use the child object without preloading!"
774 defp restrict_tag_reject(query, %{"tag_reject" => tag_reject})
775 when is_list(tag_reject) and tag_reject != [] do
777 [_activity, object] in query,
778 where: fragment("not (?)->'tag' \\?| (?)", object.data, ^tag_reject)
782 defp restrict_tag_reject(query, _), do: query
784 defp restrict_tag_all(_query, %{"tag_all" => _tag_all, "skip_preload" => true}) do
785 raise "Can't use the child object without preloading!"
788 defp restrict_tag_all(query, %{"tag_all" => tag_all})
789 when is_list(tag_all) and tag_all != [] do
791 [_activity, object] in query,
792 where: fragment("(?)->'tag' \\?& (?)", object.data, ^tag_all)
796 defp restrict_tag_all(query, _), do: query
798 defp restrict_tag(_query, %{"tag" => _tag, "skip_preload" => true}) do
799 raise "Can't use the child object without preloading!"
802 defp restrict_tag(query, %{"tag" => tag}) when is_list(tag) do
804 [_activity, object] in query,
805 where: fragment("(?)->'tag' \\?| (?)", object.data, ^tag)
809 defp restrict_tag(query, %{"tag" => tag}) when is_binary(tag) do
811 [_activity, object] in query,
812 where: fragment("(?)->'tag' \\? (?)", object.data, ^tag)
816 defp restrict_tag(query, _), do: query
818 defp restrict_recipients(query, [], _user), do: query
820 defp restrict_recipients(query, recipients, nil) do
821 from(activity in query, where: fragment("? && ?", ^recipients, activity.recipients))
824 defp restrict_recipients(query, recipients, user) do
827 where: fragment("? && ?", ^recipients, activity.recipients),
828 or_where: activity.actor == ^user.ap_id
832 defp restrict_local(query, %{"local_only" => true}) do
833 from(activity in query, where: activity.local == true)
836 defp restrict_local(query, _), do: query
838 defp restrict_actor(query, %{"actor_id" => actor_id}) do
839 from(activity in query, where: activity.actor == ^actor_id)
842 defp restrict_actor(query, _), do: query
844 defp restrict_type(query, %{"type" => type}) when is_binary(type) do
845 from(activity in query, where: fragment("?->>'type' = ?", activity.data, ^type))
848 defp restrict_type(query, %{"type" => type}) do
849 from(activity in query, where: fragment("?->>'type' = ANY(?)", activity.data, ^type))
852 defp restrict_type(query, _), do: query
854 defp restrict_state(query, %{"state" => state}) do
855 from(activity in query, where: fragment("?->>'state' = ?", activity.data, ^state))
858 defp restrict_state(query, _), do: query
860 defp restrict_favorited_by(query, %{"favorited_by" => ap_id}) do
862 [_activity, object] in query,
863 where: fragment("(?)->'likes' \\? (?)", object.data, ^ap_id)
867 defp restrict_favorited_by(query, _), do: query
869 defp restrict_media(_query, %{"only_media" => _val, "skip_preload" => true}) do
870 raise "Can't use the child object without preloading!"
873 defp restrict_media(query, %{"only_media" => val}) when val in [true, "true", "1"] do
875 [_activity, object] in query,
876 where: fragment("not (?)->'attachment' = (?)", object.data, ^[])
880 defp restrict_media(query, _), do: query
882 defp restrict_replies(query, %{"exclude_replies" => val}) when val in [true, "true", "1"] do
884 [_activity, object] in query,
885 where: fragment("?->>'inReplyTo' is null", object.data)
889 defp restrict_replies(query, %{
890 "reply_filtering_user" => user,
891 "reply_visibility" => "self"
894 [activity, object] in query,
897 "?->>'inReplyTo' is null OR ? = ANY(?)",
905 defp restrict_replies(query, %{
906 "reply_filtering_user" => user,
907 "reply_visibility" => "following"
910 [activity, object] in query,
913 "?->>'inReplyTo' is null OR ? && array_remove(?, ?) OR ? = ?",
915 ^[user.ap_id | User.get_cached_user_friends_ap_ids(user)],
924 defp restrict_replies(query, _), do: query
926 defp restrict_reblogs(query, %{"exclude_reblogs" => val}) when val in [true, "true", "1"] do
927 from(activity in query, where: fragment("?->>'type' != 'Announce'", activity.data))
930 defp restrict_reblogs(query, _), do: query
932 defp restrict_muted(query, %{"with_muted" => val}) when val in [true, "true", "1"], do: query
934 defp restrict_muted(query, %{"muting_user" => %User{} = user} = opts) do
935 mutes = opts["muted_users_ap_ids"] || User.muted_users_ap_ids(user)
938 from([activity] in query,
939 where: fragment("not (? = ANY(?))", activity.actor, ^mutes),
940 where: fragment("not (?->'to' \\?| ?)", activity.data, ^mutes)
943 unless opts["skip_preload"] do
944 from([thread_mute: tm] in query, where: is_nil(tm.user_id))
950 defp restrict_muted(query, _), do: query
952 defp restrict_blocked(query, %{"blocking_user" => %User{} = user} = opts) do
953 blocked_ap_ids = opts["blocked_users_ap_ids"] || User.blocked_users_ap_ids(user)
954 domain_blocks = user.domain_blocks || []
956 following_ap_ids = User.get_friends_ap_ids(user)
959 if has_named_binding?(query, :object), do: query, else: Activity.with_joined_object(query)
962 [activity, object: o] in query,
963 where: fragment("not (? = ANY(?))", activity.actor, ^blocked_ap_ids),
964 where: fragment("not (? && ?)", activity.recipients, ^blocked_ap_ids),
967 "not (?->>'type' = 'Announce' and ?->'to' \\?| ?)",
974 "(not (split_part(?, '/', 3) = ANY(?))) or ? = ANY(?)",
982 "(not (split_part(?->>'actor', '/', 3) = ANY(?))) or (?->>'actor') = ANY(?)",
991 defp restrict_blocked(query, _), do: query
993 defp restrict_unlisted(query) do
998 "not (coalesce(?->'cc', '{}'::jsonb) \\?| ?)",
1000 ^[Constants.as_public()]
1005 # TODO: when all endpoints migrated to OpenAPI compare `pinned` with `true` (boolean) only,
1006 # the same for `restrict_media/2`, `restrict_replies/2`, 'restrict_reblogs/2'
1007 # and `restrict_muted/2`
1009 defp restrict_pinned(query, %{"pinned" => pinned, "pinned_activity_ids" => ids})
1010 when pinned in [true, "true", "1"] do
1011 from(activity in query, where: activity.id in ^ids)
1014 defp restrict_pinned(query, _), do: query
1016 defp restrict_muted_reblogs(query, %{"muting_user" => %User{} = user} = opts) do
1017 muted_reblogs = opts["reblog_muted_users_ap_ids"] || User.reblog_muted_users_ap_ids(user)
1023 "not ( ?->>'type' = 'Announce' and ? = ANY(?))",
1031 defp restrict_muted_reblogs(query, _), do: query
1033 defp restrict_instance(query, %{"instance" => instance}) do
1038 where: fragment("? LIKE ?", u.nickname, ^"%@#{instance}")
1042 from(activity in query, where: activity.actor in ^users)
1045 defp restrict_instance(query, _), do: query
1047 defp exclude_poll_votes(query, %{"include_poll_votes" => true}), do: query
1049 defp exclude_poll_votes(query, _) do
1050 if has_named_binding?(query, :object) do
1051 from([activity, object: o] in query,
1052 where: fragment("not(?->>'type' = ?)", o.data, "Answer")
1059 defp exclude_chat_messages(query, %{"include_chat_messages" => true}), do: query
1061 defp exclude_chat_messages(query, _) do
1062 if has_named_binding?(query, :object) do
1063 from([activity, object: o] in query,
1064 where: fragment("not(?->>'type' = ?)", o.data, "ChatMessage")
1071 defp exclude_id(query, %{"exclude_id" => id}) when is_binary(id) do
1072 from(activity in query, where: activity.id != ^id)
1075 defp exclude_id(query, _), do: query
1077 defp maybe_preload_objects(query, %{"skip_preload" => true}), do: query
1079 defp maybe_preload_objects(query, _) do
1081 |> Activity.with_preloaded_object()
1084 defp maybe_preload_bookmarks(query, %{"skip_preload" => true}), do: query
1086 defp maybe_preload_bookmarks(query, opts) do
1088 |> Activity.with_preloaded_bookmark(opts["user"])
1091 defp maybe_preload_report_notes(query, %{"preload_report_notes" => true}) do
1093 |> Activity.with_preloaded_report_notes()
1096 defp maybe_preload_report_notes(query, _), do: query
1098 defp maybe_set_thread_muted_field(query, %{"skip_preload" => true}), do: query
1100 defp maybe_set_thread_muted_field(query, opts) do
1102 |> Activity.with_set_thread_muted_field(opts["muting_user"] || opts["user"])
1105 defp maybe_order(query, %{order: :desc}) do
1107 |> order_by(desc: :id)
1110 defp maybe_order(query, %{order: :asc}) do
1112 |> order_by(asc: :id)
1115 defp maybe_order(query, _), do: query
1117 defp fetch_activities_query_ap_ids_ops(opts) do
1118 source_user = opts["muting_user"]
1119 ap_id_relationships = if source_user, do: [:mute, :reblog_mute], else: []
1121 ap_id_relationships =
1122 ap_id_relationships ++
1123 if opts["blocking_user"] && opts["blocking_user"] == source_user do
1129 preloaded_ap_ids = User.outgoing_relationships_ap_ids(source_user, ap_id_relationships)
1131 restrict_blocked_opts = Map.merge(%{"blocked_users_ap_ids" => preloaded_ap_ids[:block]}, opts)
1132 restrict_muted_opts = Map.merge(%{"muted_users_ap_ids" => preloaded_ap_ids[:mute]}, opts)
1134 restrict_muted_reblogs_opts =
1135 Map.merge(%{"reblog_muted_users_ap_ids" => preloaded_ap_ids[:reblog_mute]}, opts)
1137 {restrict_blocked_opts, restrict_muted_opts, restrict_muted_reblogs_opts}
1140 def fetch_activities_query(recipients, opts \\ %{}) do
1141 {restrict_blocked_opts, restrict_muted_opts, restrict_muted_reblogs_opts} =
1142 fetch_activities_query_ap_ids_ops(opts)
1145 skip_thread_containment: Config.get([:instance, :skip_thread_containment])
1149 |> maybe_preload_objects(opts)
1150 |> maybe_preload_bookmarks(opts)
1151 |> maybe_preload_report_notes(opts)
1152 |> maybe_set_thread_muted_field(opts)
1153 |> maybe_order(opts)
1154 |> restrict_recipients(recipients, opts["user"])
1155 |> restrict_replies(opts)
1156 |> restrict_tag(opts)
1157 |> restrict_tag_reject(opts)
1158 |> restrict_tag_all(opts)
1159 |> restrict_since(opts)
1160 |> restrict_local(opts)
1161 |> restrict_actor(opts)
1162 |> restrict_type(opts)
1163 |> restrict_state(opts)
1164 |> restrict_favorited_by(opts)
1165 |> restrict_blocked(restrict_blocked_opts)
1166 |> restrict_muted(restrict_muted_opts)
1167 |> restrict_media(opts)
1168 |> restrict_visibility(opts)
1169 |> restrict_thread_visibility(opts, config)
1170 |> restrict_reblogs(opts)
1171 |> restrict_pinned(opts)
1172 |> restrict_muted_reblogs(restrict_muted_reblogs_opts)
1173 |> restrict_instance(opts)
1174 |> Activity.restrict_deactivated_users()
1175 |> exclude_poll_votes(opts)
1176 |> exclude_chat_messages(opts)
1177 |> exclude_visibility(opts)
1180 def fetch_activities(recipients, opts \\ %{}, pagination \\ :keyset) do
1181 list_memberships = Pleroma.List.memberships(opts["user"])
1183 fetch_activities_query(recipients ++ list_memberships, opts)
1184 |> Pagination.fetch_paginated(opts, pagination)
1186 |> maybe_update_cc(list_memberships, opts["user"])
1190 Fetch favorites activities of user with order by sort adds to favorites
1192 @spec fetch_favourites(User.t(), map(), Pagination.type()) :: list(Activity.t())
1193 def fetch_favourites(user, params \\ %{}, pagination \\ :keyset) do
1195 |> Activity.Queries.by_actor()
1196 |> Activity.Queries.by_type("Like")
1197 |> Activity.with_joined_object()
1198 |> Object.with_joined_activity()
1199 |> select([_like, object, activity], %{activity | object: object})
1200 |> order_by([like, _, _], desc: like.id)
1201 |> Pagination.fetch_paginated(
1202 Map.merge(params, %{"skip_order" => true}),
1208 defp maybe_update_cc(activities, list_memberships, %User{ap_id: user_ap_id})
1209 when is_list(list_memberships) and length(list_memberships) > 0 do
1210 Enum.map(activities, fn
1211 %{data: %{"bcc" => bcc}} = activity when is_list(bcc) and length(bcc) > 0 ->
1212 if Enum.any?(bcc, &(&1 in list_memberships)) do
1213 update_in(activity.data["cc"], &[user_ap_id | &1])
1223 defp maybe_update_cc(activities, _, _), do: activities
1225 def fetch_activities_bounded_query(query, recipients, recipients_with_public) do
1226 from(activity in query,
1228 fragment("? && ?", activity.recipients, ^recipients) or
1229 (fragment("? && ?", activity.recipients, ^recipients_with_public) and
1230 ^Constants.as_public() in activity.recipients)
1234 def fetch_activities_bounded(
1236 recipients_with_public,
1238 pagination \\ :keyset
1240 fetch_activities_query([], opts)
1241 |> fetch_activities_bounded_query(recipients, recipients_with_public)
1242 |> Pagination.fetch_paginated(opts, pagination)
1246 @spec upload(Upload.source(), keyword()) :: {:ok, Object.t()} | {:error, any()}
1247 def upload(file, opts \\ []) do
1248 with {:ok, data} <- Upload.store(file, opts) do
1251 Map.put(data, "actor", opts[:actor])
1256 Repo.insert(%Object{data: obj_data})
1260 @spec get_actor_url(any()) :: binary() | nil
1261 defp get_actor_url(url) when is_binary(url), do: url
1262 defp get_actor_url(%{"href" => href}) when is_binary(href), do: href
1264 defp get_actor_url(url) when is_list(url) do
1270 defp get_actor_url(_url), do: nil
1272 defp object_to_user_data(data) do
1274 data["icon"]["url"] &&
1277 "url" => [%{"href" => data["icon"]["url"]}]
1281 data["image"]["url"] &&
1284 "url" => [%{"href" => data["image"]["url"]}]
1289 |> Map.get("attachment", [])
1290 |> Enum.filter(fn %{"type" => t} -> t == "PropertyValue" end)
1291 |> Enum.map(fn fields -> Map.take(fields, ["name", "value"]) end)
1295 |> Map.get("tag", [])
1297 %{"type" => "Emoji"} -> true
1300 |> Enum.reduce(%{}, fn %{"icon" => %{"url" => url}, "name" => name}, acc ->
1301 Map.put(acc, String.trim(name, ":"), url)
1304 locked = data["manuallyApprovesFollowers"] || false
1305 data = Transmogrifier.maybe_fix_user_object(data)
1306 discoverable = data["discoverable"] || false
1307 invisible = data["invisible"] || false
1308 actor_type = data["type"] || "Person"
1311 if is_map(data["publicKey"]) && is_binary(data["publicKey"]["publicKeyPem"]) do
1312 data["publicKey"]["publicKeyPem"]
1318 if is_map(data["endpoints"]) && is_binary(data["endpoints"]["sharedInbox"]) do
1319 data["endpoints"]["sharedInbox"]
1326 uri: get_actor_url(data["url"]),
1332 discoverable: discoverable,
1333 invisible: invisible,
1336 follower_address: data["followers"],
1337 following_address: data["following"],
1338 bio: data["summary"],
1339 actor_type: actor_type,
1340 also_known_as: Map.get(data, "alsoKnownAs", []),
1341 public_key: public_key,
1342 inbox: data["inbox"],
1343 shared_inbox: shared_inbox
1346 # nickname can be nil because of virtual actors
1348 if data["preferredUsername"] do
1352 "#{data["preferredUsername"]}@#{URI.parse(data["id"]).host}"
1355 Map.put(user_data, :nickname, nil)
1361 def fetch_follow_information_for_user(user) do
1362 with {:ok, following_data} <-
1363 Fetcher.fetch_and_contain_remote_object_from_id(user.following_address),
1364 {:ok, hide_follows} <- collection_private(following_data),
1365 {:ok, followers_data} <-
1366 Fetcher.fetch_and_contain_remote_object_from_id(user.follower_address),
1367 {:ok, hide_followers} <- collection_private(followers_data) do
1370 hide_follows: hide_follows,
1371 follower_count: normalize_counter(followers_data["totalItems"]),
1372 following_count: normalize_counter(following_data["totalItems"]),
1373 hide_followers: hide_followers
1376 {:error, _} = e -> e
1381 defp normalize_counter(counter) when is_integer(counter), do: counter
1382 defp normalize_counter(_), do: 0
1384 def maybe_update_follow_information(user_data) do
1385 with {:enabled, true} <- {:enabled, Config.get([:instance, :external_user_synchronization])},
1386 {_, true} <- {:user_type_check, user_data[:type] in ["Person", "Service"]},
1388 {:collections_available,
1389 !!(user_data[:following_address] && user_data[:follower_address])},
1391 fetch_follow_information_for_user(user_data) do
1392 info = Map.merge(user_data[:info] || %{}, info)
1395 |> Map.put(:info, info)
1397 {:user_type_check, false} ->
1400 {:collections_available, false} ->
1403 {:enabled, false} ->
1408 "Follower/Following counter update for #{user_data.ap_id} failed.\n" <> inspect(e)
1415 defp collection_private(%{"first" => %{"type" => type}})
1416 when type in ["CollectionPage", "OrderedCollectionPage"],
1419 defp collection_private(%{"first" => first}) do
1420 with {:ok, %{"type" => type}} when type in ["CollectionPage", "OrderedCollectionPage"] <-
1421 Fetcher.fetch_and_contain_remote_object_from_id(first) do
1424 {:error, {:ok, %{status: code}}} when code in [401, 403] -> {:ok, true}
1425 {:error, _} = e -> e
1430 defp collection_private(_data), do: {:ok, true}
1432 def user_data_from_user_object(data) do
1433 with {:ok, data} <- MRF.filter(data),
1434 {:ok, data} <- object_to_user_data(data) do
1441 def fetch_and_prepare_user_from_ap_id(ap_id) do
1442 with {:ok, data} <- Fetcher.fetch_and_contain_remote_object_from_id(ap_id),
1443 {:ok, data} <- user_data_from_user_object(data),
1444 data <- maybe_update_follow_information(data) do
1447 {:error, "Object has been deleted"} = e ->
1448 Logger.debug("Could not decode user at fetch #{ap_id}, #{inspect(e)}")
1452 Logger.error("Could not decode user at fetch #{ap_id}, #{inspect(e)}")
1457 def make_user_from_ap_id(ap_id) do
1458 user = User.get_cached_by_ap_id(ap_id)
1460 if user && !User.ap_enabled?(user) do
1461 Transmogrifier.upgrade_user_from_ap_id(ap_id)
1463 with {:ok, data} <- fetch_and_prepare_user_from_ap_id(ap_id) do
1466 |> User.remote_user_changeset(data)
1467 |> User.update_and_set_cache()
1470 |> User.remote_user_changeset()
1480 def make_user_from_nickname(nickname) do
1481 with {:ok, %{"ap_id" => ap_id}} when not is_nil(ap_id) <- WebFinger.finger(nickname) do
1482 make_user_from_ap_id(ap_id)
1484 _e -> {:error, "No AP id in WebFinger"}
1488 # filter out broken threads
1489 def contain_broken_threads(%Activity{} = activity, %User{} = user) do
1490 entire_thread_visible_for_user?(activity, user)
1493 # do post-processing on a specific activity
1494 def contain_activity(%Activity{} = activity, %User{} = user) do
1495 contain_broken_threads(activity, user)
1498 def fetch_direct_messages_query do
1500 |> restrict_type(%{"type" => "Create"})
1501 |> restrict_visibility(%{visibility: "direct"})
1502 |> order_by([activity], asc: activity.id)