1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2021 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{
71 pleroma:emoji_reaction
77 def changeset(%Notification{} = notification, attrs) do
79 |> cast(attrs, [:seen, :type])
80 |> validate_inclusion(:type, @notification_types)
83 @spec last_read_query(User.t()) :: Ecto.Queryable.t()
84 def last_read_query(user) do
85 from(q in Pleroma.Notification,
86 where: q.user_id == ^user.id,
87 where: q.seen == true,
88 select: type(q.id, :string),
94 defp for_user_query_ap_id_opts(user, opts) do
97 if opts[@include_muted_option], do: [], else: [:notification_mute]
99 preloaded_ap_ids = User.outgoing_relationships_ap_ids(user, ap_id_relationships)
101 exclude_blocked_opts = Map.merge(%{blocked_users_ap_ids: preloaded_ap_ids[:block]}, opts)
103 exclude_notification_muted_opts =
104 Map.merge(%{notification_muted_users_ap_ids: preloaded_ap_ids[:notification_mute]}, opts)
106 {exclude_blocked_opts, exclude_notification_muted_opts}
109 def for_user_query(user, opts \\ %{}) do
110 {exclude_blocked_opts, exclude_notification_muted_opts} =
111 for_user_query_ap_id_opts(user, opts)
114 |> where(user_id: ^user.id)
115 |> join(:inner, [n], activity in assoc(n, :activity))
116 |> join(:left, [n, a], object in Object,
119 "(?->>'id') = COALESCE(?->'object'->>'id', ?->>'object')",
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([n, a], a.actor 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([n, a], a.actor 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([n, a], a.actor 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("?->>'actor' = ?", o.data, ^user.ap_id)
186 @valid_visibilities ~w[direct unlisted public private]
188 defp exclude_visibility(query, %{exclude_visibilities: visibility})
189 when is_list(visibility) do
190 if Enum.all?(visibility, &(&1 in @valid_visibilities)) do
192 |> join(:left, [n, a], mutated_activity in Pleroma.Activity,
195 "COALESCE((?->'object')->>'id', ?->>'object')",
200 "COALESCE((?->'object')->>'id', ?->>'object')",
201 mutated_activity.data,
202 mutated_activity.data
204 fragment("(?->>'type' = 'Like' or ?->>'type' = 'Announce')", a.data, a.data) and
205 fragment("?->>'type'", mutated_activity.data) == "Create",
206 as: :mutated_activity
209 [n, a, mutated_activity: mutated_activity],
212 CASE WHEN (?->>'type') = 'Like' or (?->>'type') = 'Announce'
213 THEN (activity_visibility(?, ?, ?) = ANY (?))
214 ELSE (activity_visibility(?, ?, ?) = ANY (?)) END
218 mutated_activity.actor,
219 mutated_activity.recipients,
220 mutated_activity.data,
229 Logger.error("Could not exclude visibility to #{visibility}")
234 defp exclude_visibility(query, %{exclude_visibilities: visibility})
235 when visibility in @valid_visibilities do
236 exclude_visibility(query, [visibility])
239 defp exclude_visibility(query, %{exclude_visibilities: visibility})
240 when visibility not in @valid_visibilities do
241 Logger.error("Could not exclude visibility to #{visibility}")
245 defp exclude_visibility(query, _visibility), do: query
247 def for_user(user, opts \\ %{}) do
249 |> for_user_query(opts)
250 |> Pagination.fetch_paginated(opts)
254 Returns notifications for user received since given date.
258 iex> Pleroma.Notification.for_user_since(%Pleroma.User{}, ~N[2019-04-13 11:22:33])
259 [%Pleroma.Notification{}, %Pleroma.Notification{}]
261 iex> Pleroma.Notification.for_user_since(%Pleroma.User{}, ~N[2019-04-15 11:22:33])
264 @spec for_user_since(Pleroma.User.t(), NaiveDateTime.t()) :: [t()]
265 def for_user_since(user, date) do
266 from(n in for_user_query(user),
267 where: n.updated_at > ^date
272 def set_read_up_to(%{id: user_id} = user, id) do
276 where: n.user_id == ^user_id,
278 where: n.seen == false,
279 # Ideally we would preload object and activities here
280 # but Ecto does not support preloads in update_all
284 {:ok, %{ids: {_, notification_ids}}} =
286 |> Multi.update_all(:ids, query, set: [seen: true, updated_at: NaiveDateTime.utc_now()])
287 |> Marker.multi_set_last_read_id(user, "notifications")
288 |> Repo.transaction()
291 |> where([n], n.id in ^notification_ids)
295 @spec read_one(User.t(), String.t()) ::
296 {:ok, Notification.t()} | {:error, Ecto.Changeset.t()} | nil
297 def read_one(%User{} = user, notification_id) do
298 with {:ok, %Notification{} = notification} <- get(user, notification_id) do
300 |> Multi.update(:update, changeset(notification, %{seen: true}))
301 |> Marker.multi_set_last_read_id(user, "notifications")
302 |> Repo.transaction()
304 {:ok, %{update: notification}} -> {:ok, notification}
305 {:error, :update, changeset, _} -> {:error, changeset}
310 def get(%{id: user_id} = _user, id) do
315 join: activity in assoc(n, :activity),
316 preload: [activity: activity]
319 notification = Repo.one(query)
322 %{user_id: ^user_id} ->
326 {:error, "Cannot get notification"}
331 from(n in Notification, where: n.user_id == ^user.id)
335 def destroy_multiple(%{id: user_id} = _user, ids) do
336 from(n in Notification,
338 where: n.user_id == ^user_id
343 def destroy_multiple_from_types(%{id: user_id}, types) do
344 from(n in Notification,
345 where: n.user_id == ^user_id,
346 where: n.type in ^types
351 def dismiss(%Pleroma.Activity{} = activity) do
353 |> where([n], n.activity_id == ^activity.id)
356 {_, notifications} -> {:ok, notifications}
357 _ -> {:error, "Cannot dismiss notification"}
361 def dismiss(%{id: user_id} = _user, id) do
362 notification = Repo.get(Notification, id)
365 %{user_id: ^user_id} ->
366 Repo.delete(notification)
369 {:error, "Cannot dismiss notification"}
373 @spec create_notifications(Activity.t(), keyword()) :: {:ok, [Notification.t()] | []}
374 def create_notifications(activity, options \\ [])
376 def create_notifications(%Activity{data: %{"to" => _, "type" => "Create"}} = activity, options) do
377 object = Object.normalize(activity, fetch: false)
379 if object && object.data["type"] == "Answer" do
382 do_create_notifications(activity, options)
386 def create_notifications(%Activity{data: %{"type" => type}} = activity, options)
387 when type in ["Follow", "Like", "Announce", "Move", "EmojiReact", "Flag", "Update"] do
388 do_create_notifications(activity, options)
391 def create_notifications(_, _), do: {:ok, []}
393 defp do_create_notifications(%Activity{} = activity, options) do
394 do_send = Keyword.get(options, :do_send, true)
396 {enabled_receivers, disabled_receivers} = get_notified_from_activity(activity)
397 potential_receivers = enabled_receivers ++ disabled_receivers
400 Enum.map(potential_receivers, fn user ->
401 do_send = do_send && user in enabled_receivers
402 create_notification(activity, user, do_send: do_send)
404 |> Enum.reject(&is_nil/1)
409 defp type_from_activity(%{data: %{"type" => type}} = activity) do
412 if Activity.follow_accepted?(activity) do
428 "pleroma:emoji_reaction"
433 # Compatibility with old reactions
435 "pleroma:emoji_reaction"
439 |> type_from_activity_object()
445 raise "No notification type for activity type #{t}"
449 defp type_from_activity_object(%{data: %{"type" => "Create"}}), do: "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_superusers() |> Enum.map(fn user -> user.ap_id end)) -- [actor]
558 # Update activity: notify all who repeated this
559 def get_potential_receiver_ap_ids(%{data: %{"type" => "Update", "actor" => actor}} = activity) do
560 with %Object{data: %{"id" => object_id}} <- Object.normalize(activity, fetch: false) do
562 Activity.Queries.by_type("Announce")
563 |> Activity.Queries.by_object_id(object_id)
564 |> Activity.with_joined_user_actor()
565 |> where([a, u], u.local)
566 |> select([a, u], u.ap_id)
573 def get_potential_receiver_ap_ids(activity) do
575 |> Utils.maybe_notify_to_recipients(activity)
576 |> Utils.maybe_notify_mentioned_recipients(activity)
577 |> Utils.maybe_notify_subscribers(activity)
578 |> Utils.maybe_notify_followers(activity)
582 @doc "Filters out AP IDs domain-blocking and not following the activity's actor"
583 def exclude_domain_blocker_ap_ids(ap_ids, activity, preloaded_users \\ [])
585 def exclude_domain_blocker_ap_ids([], _activity, _preloaded_users), do: []
587 def exclude_domain_blocker_ap_ids(ap_ids, %Activity{} = activity, preloaded_users) do
588 activity_actor_domain = activity.actor && URI.parse(activity.actor).host
592 |> Enum.map(fn ap_id ->
593 Enum.find(preloaded_users, &(&1.ap_id == ap_id)) ||
594 User.get_cached_by_ap_id(ap_id)
598 domain_blocker_ap_ids = for u <- users, activity_actor_domain in u.domain_blocks, do: u.ap_id
600 domain_blocker_follower_ap_ids =
601 if Enum.any?(domain_blocker_ap_ids) do
603 |> Activity.user_actor()
604 |> FollowingRelationship.followers_ap_ids(domain_blocker_ap_ids)
610 |> Kernel.--(domain_blocker_ap_ids)
611 |> Kernel.++(domain_blocker_follower_ap_ids)
614 @doc "Filters out AP IDs of users basing on their relationships with activity actor user"
615 def exclude_relationship_restricted_ap_ids([], _activity), do: []
617 def exclude_relationship_restricted_ap_ids(ap_ids, %Activity{} = activity) do
618 relationship_restricted_ap_ids =
620 |> Activity.user_actor()
621 |> User.incoming_relationships_ungrouped_ap_ids([
626 Enum.uniq(ap_ids) -- relationship_restricted_ap_ids
629 @doc "Filters out AP IDs of users who mute activity thread"
630 def exclude_thread_muter_ap_ids([], _activity), do: []
632 def exclude_thread_muter_ap_ids(ap_ids, %Activity{} = activity) do
633 thread_muter_ap_ids = ThreadMute.muter_ap_ids(activity.data["context"])
635 Enum.uniq(ap_ids) -- thread_muter_ap_ids
638 def skip?(activity, user, opts \\ [])
640 @spec skip?(Activity.t(), User.t(), Keyword.t()) :: boolean()
641 def skip?(%Activity{} = activity, %User{} = user, opts) do
645 :block_from_strangers,
649 |> Enum.find(&skip?(&1, activity, user, opts))
652 def skip?(_activity, _user, _opts), do: false
654 @spec skip?(atom(), Activity.t(), User.t(), Keyword.t()) :: boolean()
655 def skip?(:self, %Activity{} = activity, %User{} = user, opts) do
657 opts[:type] == "poll" -> false
658 activity.data["actor"] == user.ap_id -> true
663 def skip?(:invisible, %Activity{} = activity, _user, _opts) do
664 actor = activity.data["actor"]
665 user = User.get_cached_by_ap_id(actor)
666 User.invisible?(user)
670 :block_from_strangers,
671 %Activity{} = activity,
672 %User{notification_settings: %{block_from_strangers: true}} = user,
675 actor = activity.data["actor"]
676 follower = User.get_cached_by_ap_id(actor)
679 opts[:type] == "poll" -> false
680 user.ap_id == actor -> false
681 !User.following?(follower, user) -> true
686 # To do: consider defining recency in hours and checking FollowingRelationship with a single SQL
689 %Activity{data: %{"type" => "Follow"}} = activity,
693 actor = activity.data["actor"]
695 Notification.for_user(user)
697 %{activity: %{data: %{"type" => "Follow", "actor" => ^actor}}} -> true
702 def skip?(:filtered, %{data: %{"type" => type}}, _user, _opts) when type in ["Follow", "Move"],
705 def skip?(:filtered, activity, user, _opts) do
706 object = Object.normalize(activity, fetch: false)
712 object.data["actor"] == user.ap_id ->
715 not is_nil(regex = Pleroma.Filter.compose_regex(user, :re)) ->
716 Regex.match?(regex, object.data["content"])
723 def skip?(_type, _activity, _user, _opts), do: false
725 def mark_as_read?(activity, target_user) do
726 user = Activity.user_actor(activity)
727 User.mutes_user?(target_user, user) || CommonAPI.thread_muted?(target_user, activity)
730 def for_user_and_activity(user, activity) do
731 from(n in __MODULE__,
732 where: n.user_id == ^user.id,
733 where: n.activity_id == ^activity.id
738 @spec mark_context_as_read(User.t(), String.t()) :: {integer(), nil | [term()]}
739 def mark_context_as_read(%User{id: id}, context) do
742 join: a in assoc(n, :activity),
743 where: n.user_id == ^id,
744 where: n.seen == false,
745 where: fragment("?->>'context'", a.data) == ^context
747 |> Repo.update_all(set: [seen: true])