1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2022 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
5 defmodule Pleroma.Notification do
10 alias Pleroma.FollowingRelationship
12 alias Pleroma.Notification
14 alias Pleroma.Pagination
16 alias Pleroma.ThreadMute
18 alias Pleroma.Web.CommonAPI
19 alias Pleroma.Web.CommonAPI.Utils
20 alias Pleroma.Web.Push
21 alias Pleroma.Web.Streamer
28 @type t :: %__MODULE__{}
30 @include_muted_option :with_muted
32 schema "notifications" do
33 field(:seen, :boolean, default: false)
34 # This is an enum type in the database. If you add a new notification type,
35 # remember to add a migration to add it to the `notifications_type` enum
38 belongs_to(:user, User, type: FlakeId.Ecto.CompatType)
39 belongs_to(:activity, Activity, type: FlakeId.Ecto.CompatType)
44 def update_notification_type(user, activity) do
45 with %__MODULE__{} = notification <-
46 Repo.get_by(__MODULE__, user_id: user.id, activity_id: activity.id) do
49 |> type_from_activity()
52 |> changeset(%{type: type})
57 @spec unread_notifications_count(User.t()) :: integer()
58 def unread_notifications_count(%User{id: user_id}) do
60 where: q.user_id == ^user_id and q.seen == false
62 |> Repo.aggregate(:count, :id)
65 @notification_types ~w{
72 pleroma:emoji_reaction
78 def changeset(%Notification{} = notification, attrs) do
80 |> cast(attrs, [:seen, :type])
81 |> validate_inclusion(:type, @notification_types)
84 @spec last_read_query(User.t()) :: Ecto.Queryable.t()
85 def last_read_query(user) do
86 from(q in Pleroma.Notification,
87 where: q.user_id == ^user.id,
88 where: q.seen == true,
89 select: type(q.id, :string),
91 order_by: fragment("? desc nulls last", q.id)
95 defp for_user_query_ap_id_opts(user, opts) do
98 if opts[@include_muted_option], do: [], else: [:notification_mute]
100 preloaded_ap_ids = User.outgoing_relationships_ap_ids(user, ap_id_relationships)
102 exclude_blocked_opts = Map.merge(%{blocked_users_ap_ids: preloaded_ap_ids[:block]}, opts)
104 exclude_notification_muted_opts =
105 Map.merge(%{notification_muted_users_ap_ids: preloaded_ap_ids[:notification_mute]}, opts)
107 {exclude_blocked_opts, exclude_notification_muted_opts}
110 def for_user_query(user, opts \\ %{}) do
111 {exclude_blocked_opts, exclude_notification_muted_opts} =
112 for_user_query_ap_id_opts(user, opts)
115 |> where(user_id: ^user.id)
116 |> join(:inner, [n], activity in assoc(n, :activity))
117 |> join(:left, [n, a], object in Object,
120 "(?->>'id') = associated_object_id(?)",
125 |> join(:inner, [_n, a], u in User, on: u.ap_id == a.actor, as: :user_actor)
126 |> preload([n, a, o], activity: {a, object: o})
127 |> where([user_actor: user_actor], user_actor.is_active)
128 |> exclude_notification_muted(user, exclude_notification_muted_opts)
129 |> exclude_blocked(user, exclude_blocked_opts)
130 |> exclude_blockers(user)
131 |> exclude_filtered(user)
132 |> exclude_visibility(opts)
135 # Excludes blocked users and non-followed domain-blocked users
136 defp exclude_blocked(query, user, opts) do
137 blocked_ap_ids = opts[:blocked_users_ap_ids] || User.blocked_users_ap_ids(user)
140 |> where([..., user_actor: user_actor], user_actor.ap_id not in ^blocked_ap_ids)
141 |> FollowingRelationship.keep_following_or_not_domain_blocked(user)
144 defp exclude_blockers(query, user) do
145 if Pleroma.Config.get([:activitypub, :blockers_visible]) == true do
148 blocker_ap_ids = User.incoming_relationships_ungrouped_ap_ids(user, [:block])
151 |> where([..., user_actor: user_actor], user_actor.ap_id not in ^blocker_ap_ids)
155 defp exclude_notification_muted(query, _, %{@include_muted_option => true}) do
159 defp exclude_notification_muted(query, user, opts) do
160 notification_muted_ap_ids =
161 opts[:notification_muted_users_ap_ids] || User.notification_muted_users_ap_ids(user)
164 |> where([..., user_actor: user_actor], user_actor.ap_id not in ^notification_muted_ap_ids)
165 |> join(:left, [n, a], tm in ThreadMute,
166 on: tm.user_id == ^user.id and tm.context == fragment("?->>'context'", a.data),
169 |> where([thread_mute: thread_mute], is_nil(thread_mute.user_id))
172 defp exclude_filtered(query, user) do
173 case Pleroma.Filter.compose_regex(user) do
178 from([_n, a, o] in query,
180 fragment("not(?->>'content' ~* ?)", o.data, ^regex) or
181 fragment("?->>'content' is null", o.data) or
182 fragment("?->>'actor' = ?", o.data, ^user.ap_id)
187 @valid_visibilities ~w[direct unlisted public private]
189 defp exclude_visibility(query, %{exclude_visibilities: visibility})
190 when is_list(visibility) do
191 if Enum.all?(visibility, &(&1 in @valid_visibilities)) do
193 |> join(:left, [n, a], mutated_activity in Pleroma.Activity,
196 "associated_object_id(?)",
200 "associated_object_id(?)",
201 mutated_activity.data
203 fragment("(?->>'type' = 'Like' or ?->>'type' = 'Announce')", a.data, a.data) and
204 fragment("?->>'type'", mutated_activity.data) == "Create",
205 as: :mutated_activity
208 [n, a, mutated_activity: mutated_activity],
211 CASE WHEN (?->>'type') = 'Like' or (?->>'type') = 'Announce'
212 THEN (activity_visibility(?, ?, ?) = ANY (?))
213 ELSE (activity_visibility(?, ?, ?) = ANY (?)) END
217 mutated_activity.actor,
218 mutated_activity.recipients,
219 mutated_activity.data,
228 Logger.error("Could not exclude visibility to #{visibility}")
233 defp exclude_visibility(query, %{exclude_visibilities: visibility})
234 when visibility in @valid_visibilities do
235 exclude_visibility(query, [visibility])
238 defp exclude_visibility(query, %{exclude_visibilities: visibility})
239 when visibility not in @valid_visibilities do
240 Logger.error("Could not exclude visibility to #{visibility}")
244 defp exclude_visibility(query, _visibility), do: query
246 def for_user(user, opts \\ %{}) do
248 |> for_user_query(opts)
249 |> Pagination.fetch_paginated(opts)
253 Returns notifications for user received since given date.
257 iex> Pleroma.Notification.for_user_since(%Pleroma.User{}, ~N[2019-04-13 11:22:33])
258 [%Pleroma.Notification{}, %Pleroma.Notification{}]
260 iex> Pleroma.Notification.for_user_since(%Pleroma.User{}, ~N[2019-04-15 11:22:33])
263 @spec for_user_since(Pleroma.User.t(), NaiveDateTime.t()) :: [t()]
264 def for_user_since(user, date) do
265 from(n in for_user_query(user),
266 where: n.updated_at > ^date
271 def set_read_up_to(%{id: user_id} = user, id) do
275 where: n.user_id == ^user_id,
277 where: n.seen == false,
278 # Ideally we would preload object and activities here
279 # but Ecto does not support preloads in update_all
283 {:ok, %{ids: {_, notification_ids}}} =
285 |> Multi.update_all(:ids, query, set: [seen: true, updated_at: NaiveDateTime.utc_now()])
286 |> Marker.multi_set_last_read_id(user, "notifications")
287 |> Repo.transaction()
290 |> where([n], n.id in ^notification_ids)
294 @spec read_one(User.t(), String.t()) ::
295 {:ok, Notification.t()} | {:error, Ecto.Changeset.t()} | nil
296 def read_one(%User{} = user, notification_id) do
297 with {:ok, %Notification{} = notification} <- get(user, notification_id) do
299 |> Multi.update(:update, changeset(notification, %{seen: true}))
300 |> Marker.multi_set_last_read_id(user, "notifications")
301 |> Repo.transaction()
303 {:ok, %{update: notification}} -> {:ok, notification}
304 {:error, :update, changeset, _} -> {:error, changeset}
309 def get(%{id: user_id} = _user, id) do
314 join: activity in assoc(n, :activity),
315 preload: [activity: activity]
318 notification = Repo.one(query)
321 %{user_id: ^user_id} ->
325 {:error, "Cannot get notification"}
330 from(n in Notification, where: n.user_id == ^user.id)
334 def destroy_multiple(%{id: user_id} = _user, ids) do
335 from(n in Notification,
337 where: n.user_id == ^user_id
342 def dismiss(%Pleroma.Activity{} = activity) do
344 |> where([n], n.activity_id == ^activity.id)
347 {_, notifications} -> {:ok, notifications}
348 _ -> {:error, "Cannot dismiss notification"}
352 def dismiss(%{id: user_id} = _user, id) do
353 notification = Repo.get(Notification, id)
356 %{user_id: ^user_id} ->
357 Repo.delete(notification)
360 {:error, "Cannot dismiss notification"}
364 @spec create_notifications(Activity.t(), keyword()) :: {:ok, [Notification.t()] | []}
365 def create_notifications(activity, options \\ [])
367 def create_notifications(%Activity{data: %{"to" => _, "type" => "Create"}} = activity, options) do
368 object = Object.normalize(activity, fetch: false)
370 if object && object.data["type"] == "Answer" do
373 do_create_notifications(activity, options)
377 def create_notifications(%Activity{data: %{"type" => type}} = activity, options)
378 when type in ["Follow", "Like", "Announce", "Move", "EmojiReact", "Flag", "Update"] do
379 do_create_notifications(activity, options)
382 def create_notifications(_, _), do: {:ok, []}
384 defp do_create_notifications(%Activity{} = activity, options) do
385 do_send = Keyword.get(options, :do_send, true)
387 {enabled_receivers, disabled_receivers} = get_notified_from_activity(activity)
388 potential_receivers = enabled_receivers ++ disabled_receivers
391 Enum.map(potential_receivers, fn user ->
392 do_send = do_send && user in enabled_receivers
393 create_notification(activity, user, do_send: do_send)
395 |> Enum.reject(&is_nil/1)
400 defp type_from_activity(%{data: %{"type" => type}} = activity) do
403 if Activity.follow_accepted?(activity) do
419 "pleroma:emoji_reaction"
424 # Compatibility with old reactions
426 "pleroma:emoji_reaction"
430 |> type_from_activity_object()
436 raise "No notification type for activity type #{t}"
440 defp type_from_activity_object(%{data: %{"type" => "Create", "object" => %{}}}), do: "mention"
442 defp type_from_activity_object(%{data: %{"type" => "Create"}} = activity) do
443 object = Object.get_by_ap_id(activity.data["object"])
445 case object && object.data["type"] do
446 "ChatMessage" -> "pleroma:chat_mention"
451 # TODO move to sql, too.
452 def create_notification(%Activity{} = activity, %User{} = user, opts \\ []) do
453 do_send = Keyword.get(opts, :do_send, true)
454 type = Keyword.get(opts, :type, type_from_activity(activity))
456 unless skip?(activity, user, opts) do
457 {:ok, %{notification: notification}} =
459 |> Multi.insert(:notification, %Notification{
462 seen: mark_as_read?(activity, user),
465 |> Marker.multi_set_last_read_id(user, "notifications")
466 |> Repo.transaction()
469 Streamer.stream(["user", "user:notification"], notification)
470 Push.send(notification)
477 def create_poll_notifications(%Activity{} = activity) do
478 with %Object{data: %{"type" => "Question", "actor" => actor} = data} <-
479 Object.normalize(activity) do
482 %{"voters" => voters} when is_list(voters) -> voters
487 Enum.reduce([actor | voters], [], fn ap_id, acc ->
488 with %User{local: true} = user <- User.get_by_ap_id(ap_id) do
489 [create_notification(activity, user, type: "poll") | acc]
500 Returns a tuple with 2 elements:
501 {notification-enabled receivers, currently disabled receivers (blocking / [thread] muting)}
503 NOTE: might be called for FAKE Activities, see ActivityPub.Utils.get_notified_from_object/1
505 @spec get_notified_from_activity(Activity.t(), boolean()) :: {list(User.t()), list(User.t())}
506 def get_notified_from_activity(activity, local_only \\ true)
508 def get_notified_from_activity(%Activity{data: %{"type" => type}} = activity, local_only)
519 potential_receiver_ap_ids = get_potential_receiver_ap_ids(activity)
521 potential_receivers =
522 User.get_users_from_set(potential_receiver_ap_ids, local_only: local_only)
524 notification_enabled_ap_ids =
525 potential_receiver_ap_ids
526 |> exclude_domain_blocker_ap_ids(activity, potential_receivers)
527 |> exclude_relationship_restricted_ap_ids(activity)
528 |> exclude_thread_muter_ap_ids(activity)
530 notification_enabled_users =
531 Enum.filter(potential_receivers, fn u -> u.ap_id in notification_enabled_ap_ids end)
533 {notification_enabled_users, potential_receivers -- notification_enabled_users}
536 def get_notified_from_activity(_, _local_only), do: {[], []}
538 # For some activities, only notify the author of the object
539 def get_potential_receiver_ap_ids(%{data: %{"type" => type, "object" => object_id}})
540 when type in ~w{Like Announce EmojiReact} do
541 case Object.get_cached_by_ap_id(object_id) do
542 %Object{data: %{"actor" => actor}} ->
550 def get_potential_receiver_ap_ids(%{data: %{"type" => "Follow", "object" => object_id}}) do
554 def get_potential_receiver_ap_ids(%{data: %{"type" => "Flag", "actor" => actor}}) do
555 (User.all_users_with_privilege(:reports_manage_reports)
556 |> Enum.map(fn user -> user.ap_id end)) --
560 # Update activity: notify all who repeated this
561 def get_potential_receiver_ap_ids(%{data: %{"type" => "Update", "actor" => actor}} = activity) do
562 with %Object{data: %{"id" => object_id}} <- Object.normalize(activity, fetch: false) do
564 Activity.Queries.by_type("Announce")
565 |> Activity.Queries.by_object_id(object_id)
566 |> Activity.with_joined_user_actor()
567 |> where([a, u], u.local)
568 |> select([a, u], u.ap_id)
575 def get_potential_receiver_ap_ids(activity) do
577 |> Utils.maybe_notify_to_recipients(activity)
578 |> Utils.maybe_notify_mentioned_recipients(activity)
579 |> Utils.maybe_notify_subscribers(activity)
580 |> Utils.maybe_notify_followers(activity)
584 @doc "Filters out AP IDs domain-blocking and not following the activity's actor"
585 def exclude_domain_blocker_ap_ids(ap_ids, activity, preloaded_users \\ [])
587 def exclude_domain_blocker_ap_ids([], _activity, _preloaded_users), do: []
589 def exclude_domain_blocker_ap_ids(ap_ids, %Activity{} = activity, preloaded_users) do
590 activity_actor_domain = activity.actor && URI.parse(activity.actor).host
594 |> Enum.map(fn ap_id ->
595 Enum.find(preloaded_users, &(&1.ap_id == ap_id)) ||
596 User.get_cached_by_ap_id(ap_id)
600 domain_blocker_ap_ids = for u <- users, activity_actor_domain in u.domain_blocks, do: u.ap_id
602 domain_blocker_follower_ap_ids =
603 if Enum.any?(domain_blocker_ap_ids) do
605 |> Activity.user_actor()
606 |> FollowingRelationship.followers_ap_ids(domain_blocker_ap_ids)
612 |> Kernel.--(domain_blocker_ap_ids)
613 |> Kernel.++(domain_blocker_follower_ap_ids)
616 @doc "Filters out AP IDs of users basing on their relationships with activity actor user"
617 def exclude_relationship_restricted_ap_ids([], _activity), do: []
619 def exclude_relationship_restricted_ap_ids(ap_ids, %Activity{} = activity) do
620 relationship_restricted_ap_ids =
622 |> Activity.user_actor()
623 |> User.incoming_relationships_ungrouped_ap_ids([
628 Enum.uniq(ap_ids) -- relationship_restricted_ap_ids
631 @doc "Filters out AP IDs of users who mute activity thread"
632 def exclude_thread_muter_ap_ids([], _activity), do: []
634 def exclude_thread_muter_ap_ids(ap_ids, %Activity{} = activity) do
635 thread_muter_ap_ids = ThreadMute.muter_ap_ids(activity.data["context"])
637 Enum.uniq(ap_ids) -- thread_muter_ap_ids
640 def skip?(activity, user, opts \\ [])
642 @spec skip?(Activity.t(), User.t(), Keyword.t()) :: boolean()
643 def skip?(%Activity{} = activity, %User{} = user, opts) do
647 :block_from_strangers,
651 |> Enum.find(&skip?(&1, activity, user, opts))
654 def skip?(_activity, _user, _opts), do: false
656 @spec skip?(atom(), Activity.t(), User.t(), Keyword.t()) :: boolean()
657 def skip?(:self, %Activity{} = activity, %User{} = user, opts) do
659 opts[:type] == "poll" -> false
660 activity.data["actor"] == user.ap_id -> true
665 def skip?(:invisible, %Activity{} = activity, _user, _opts) do
666 actor = activity.data["actor"]
667 user = User.get_cached_by_ap_id(actor)
668 User.invisible?(user)
672 :block_from_strangers,
673 %Activity{} = activity,
674 %User{notification_settings: %{block_from_strangers: true}} = user,
677 actor = activity.data["actor"]
678 follower = User.get_cached_by_ap_id(actor)
681 opts[:type] == "poll" -> false
682 user.ap_id == actor -> false
683 !User.following?(user, follower) -> true
688 # To do: consider defining recency in hours and checking FollowingRelationship with a single SQL
691 %Activity{data: %{"type" => "Follow"}} = activity,
695 actor = activity.data["actor"]
697 Notification.for_user(user)
699 %{activity: %{data: %{"type" => "Follow", "actor" => ^actor}}} -> true
704 def skip?(:filtered, %{data: %{"type" => type}}, _user, _opts) when type in ["Follow", "Move"],
707 def skip?(:filtered, activity, user, _opts) do
708 object = Object.normalize(activity, fetch: false)
714 object.data["actor"] == user.ap_id ->
717 not is_nil(regex = Pleroma.Filter.compose_regex(user, :re)) ->
718 Regex.match?(regex, object.data["content"])
725 def skip?(_type, _activity, _user, _opts), do: false
727 def mark_as_read?(activity, target_user) do
728 user = Activity.user_actor(activity)
729 User.mutes_user?(target_user, user) || CommonAPI.thread_muted?(target_user, activity)
732 def for_user_and_activity(user, activity) do
733 from(n in __MODULE__,
734 where: n.user_id == ^user.id,
735 where: n.activity_id == ^activity.id
740 @spec mark_context_as_read(User.t(), String.t()) :: {integer(), nil | [term()]}
741 def mark_context_as_read(%User{id: id}, context) do
744 join: a in assoc(n, :activity),
745 where: n.user_id == ^id,
746 where: n.seen == false,
747 where: fragment("?->>'context'", a.data) == ^context
749 |> Repo.update_all(set: [seen: true])