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{
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),
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') = COALESCE(?->'object'->>'id', ?->>'object')",
126 |> join(:inner, [_n, a], u in User, on: u.ap_id == a.actor, as: :user_actor)
127 |> preload([n, a, o], activity: {a, object: o})
128 |> where([user_actor: user_actor], user_actor.is_active)
129 |> exclude_notification_muted(user, exclude_notification_muted_opts)
130 |> exclude_blocked(user, exclude_blocked_opts)
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_notification_muted(query, _, %{@include_muted_option => true}) do
148 defp exclude_notification_muted(query, user, opts) do
149 notification_muted_ap_ids =
150 opts[:notification_muted_users_ap_ids] || User.notification_muted_users_ap_ids(user)
153 |> where([n, a], a.actor not in ^notification_muted_ap_ids)
154 |> join(:left, [n, a], tm in ThreadMute,
155 on: tm.user_id == ^user.id and tm.context == fragment("?->>'context'", a.data),
158 |> where([thread_mute: thread_mute], is_nil(thread_mute.user_id))
161 defp exclude_filtered(query, user) do
162 case Pleroma.Filter.compose_regex(user) do
167 from([_n, a, o] in query,
169 fragment("not(?->>'content' ~* ?)", o.data, ^regex) or
170 fragment("?->>'actor' = ?", o.data, ^user.ap_id)
175 @valid_visibilities ~w[direct unlisted public private]
177 defp exclude_visibility(query, %{exclude_visibilities: visibility})
178 when is_list(visibility) do
179 if Enum.all?(visibility, &(&1 in @valid_visibilities)) do
181 |> join(:left, [n, a], mutated_activity in Pleroma.Activity,
184 "COALESCE((?->'object')->>'id', ?->>'object')",
189 "COALESCE((?->'object')->>'id', ?->>'object')",
190 mutated_activity.data,
191 mutated_activity.data
193 fragment("(?->>'type' = 'Like' or ?->>'type' = 'Announce')", a.data, a.data) and
194 fragment("?->>'type'", mutated_activity.data) == "Create",
195 as: :mutated_activity
198 [n, a, mutated_activity: mutated_activity],
201 CASE WHEN (?->>'type') = 'Like' or (?->>'type') = 'Announce'
202 THEN (activity_visibility(?, ?, ?) = ANY (?))
203 ELSE (activity_visibility(?, ?, ?) = ANY (?)) END
207 mutated_activity.actor,
208 mutated_activity.recipients,
209 mutated_activity.data,
218 Logger.error("Could not exclude visibility to #{visibility}")
223 defp exclude_visibility(query, %{exclude_visibilities: visibility})
224 when visibility in @valid_visibilities do
225 exclude_visibility(query, [visibility])
228 defp exclude_visibility(query, %{exclude_visibilities: visibility})
229 when visibility not in @valid_visibilities do
230 Logger.error("Could not exclude visibility to #{visibility}")
234 defp exclude_visibility(query, _visibility), do: query
236 def for_user(user, opts \\ %{}) do
238 |> for_user_query(opts)
239 |> Pagination.fetch_paginated(opts)
243 Returns notifications for user received since given date.
247 iex> Pleroma.Notification.for_user_since(%Pleroma.User{}, ~N[2019-04-13 11:22:33])
248 [%Pleroma.Notification{}, %Pleroma.Notification{}]
250 iex> Pleroma.Notification.for_user_since(%Pleroma.User{}, ~N[2019-04-15 11:22:33])
253 @spec for_user_since(Pleroma.User.t(), NaiveDateTime.t()) :: [t()]
254 def for_user_since(user, date) do
255 from(n in for_user_query(user),
256 where: n.updated_at > ^date
261 def set_read_up_to(%{id: user_id} = user, id) do
265 where: n.user_id == ^user_id,
267 where: n.seen == false,
268 # Ideally we would preload object and activities here
269 # but Ecto does not support preloads in update_all
273 {:ok, %{ids: {_, notification_ids}}} =
275 |> Multi.update_all(:ids, query, set: [seen: true, updated_at: NaiveDateTime.utc_now()])
276 |> Marker.multi_set_last_read_id(user, "notifications")
277 |> Repo.transaction()
280 |> where([n], n.id in ^notification_ids)
284 @spec read_one(User.t(), String.t()) ::
285 {:ok, Notification.t()} | {:error, Ecto.Changeset.t()} | nil
286 def read_one(%User{} = user, notification_id) do
287 with {:ok, %Notification{} = notification} <- get(user, notification_id) do
289 |> Multi.update(:update, changeset(notification, %{seen: true}))
290 |> Marker.multi_set_last_read_id(user, "notifications")
291 |> Repo.transaction()
293 {:ok, %{update: notification}} -> {:ok, notification}
294 {:error, :update, changeset, _} -> {:error, changeset}
299 def get(%{id: user_id} = _user, id) do
304 join: activity in assoc(n, :activity),
305 preload: [activity: activity]
308 notification = Repo.one(query)
311 %{user_id: ^user_id} ->
315 {:error, "Cannot get notification"}
320 from(n in Notification, where: n.user_id == ^user.id)
324 def destroy_multiple(%{id: user_id} = _user, ids) do
325 from(n in Notification,
327 where: n.user_id == ^user_id
332 def dismiss(%Pleroma.Activity{} = activity) do
334 |> where([n], n.activity_id == ^activity.id)
337 {_, notifications} -> {:ok, notifications}
338 _ -> {:error, "Cannot dismiss notification"}
342 def dismiss(%{id: user_id} = _user, id) do
343 notification = Repo.get(Notification, id)
346 %{user_id: ^user_id} ->
347 Repo.delete(notification)
350 {:error, "Cannot dismiss notification"}
354 @spec create_notifications(Activity.t(), keyword()) :: {:ok, [Notification.t()] | []}
355 def create_notifications(activity, options \\ [])
357 def create_notifications(%Activity{data: %{"to" => _, "type" => "Create"}} = activity, options) do
358 object = Object.normalize(activity, fetch: false)
360 if object && object.data["type"] == "Answer" do
363 do_create_notifications(activity, options)
367 def create_notifications(%Activity{data: %{"type" => type}} = activity, options)
368 when type in ["Follow", "Like", "Announce", "Move", "EmojiReact", "Flag"] do
369 do_create_notifications(activity, options)
372 def create_notifications(_, _), do: {:ok, []}
374 defp do_create_notifications(%Activity{} = activity, options) do
375 do_send = Keyword.get(options, :do_send, true)
377 {enabled_receivers, disabled_receivers} = get_notified_from_activity(activity)
378 potential_receivers = enabled_receivers ++ disabled_receivers
381 Enum.map(potential_receivers, fn user ->
382 do_send = do_send && user in enabled_receivers
383 create_notification(activity, user, do_send: do_send)
385 |> Enum.reject(&is_nil/1)
390 defp type_from_activity(%{data: %{"type" => type}} = activity) do
393 if Activity.follow_accepted?(activity) do
409 "pleroma:emoji_reaction"
414 # Compatibility with old reactions
416 "pleroma:emoji_reaction"
420 |> type_from_activity_object()
423 raise "No notification type for activity type #{t}"
427 defp type_from_activity_object(%{data: %{"type" => "Create", "object" => %{}}}), do: "mention"
429 defp type_from_activity_object(%{data: %{"type" => "Create"}} = activity) do
430 object = Object.get_by_ap_id(activity.data["object"])
432 case object && object.data["type"] do
433 "ChatMessage" -> "pleroma:chat_mention"
438 # TODO move to sql, too.
439 def create_notification(%Activity{} = activity, %User{} = user, opts \\ []) do
440 do_send = Keyword.get(opts, :do_send, true)
441 type = Keyword.get(opts, :type, type_from_activity(activity))
443 unless skip?(activity, user, opts) do
444 {:ok, %{notification: notification}} =
446 |> Multi.insert(:notification, %Notification{
449 seen: mark_as_read?(activity, user),
452 |> Marker.multi_set_last_read_id(user, "notifications")
453 |> Repo.transaction()
456 Streamer.stream(["user", "user:notification"], notification)
457 Push.send(notification)
464 def create_poll_notifications(%Activity{} = activity) do
465 with %Object{data: %{"type" => "Question", "actor" => actor} = data} <-
466 Object.normalize(activity) do
469 %{"voters" => voters} when is_list(voters) -> voters
474 Enum.map([actor | voters], fn ap_id ->
475 with %User{} = user <- User.get_by_ap_id(ap_id) do
476 create_notification(activity, user, type: "poll")
485 Returns a tuple with 2 elements:
486 {notification-enabled receivers, currently disabled receivers (blocking / [thread] muting)}
488 NOTE: might be called for FAKE Activities, see ActivityPub.Utils.get_notified_from_object/1
490 @spec get_notified_from_activity(Activity.t(), boolean()) :: {list(User.t()), list(User.t())}
491 def get_notified_from_activity(activity, local_only \\ true)
493 def get_notified_from_activity(%Activity{data: %{"type" => type}} = activity, local_only)
494 when type in ["Create", "Like", "Announce", "Follow", "Move", "EmojiReact", "Flag"] do
495 potential_receiver_ap_ids = get_potential_receiver_ap_ids(activity)
497 potential_receivers =
498 User.get_users_from_set(potential_receiver_ap_ids, local_only: local_only)
500 notification_enabled_ap_ids =
501 potential_receiver_ap_ids
502 |> exclude_domain_blocker_ap_ids(activity, potential_receivers)
503 |> exclude_relationship_restricted_ap_ids(activity)
504 |> exclude_thread_muter_ap_ids(activity)
506 notification_enabled_users =
507 Enum.filter(potential_receivers, fn u -> u.ap_id in notification_enabled_ap_ids end)
509 {notification_enabled_users, potential_receivers -- notification_enabled_users}
512 def get_notified_from_activity(_, _local_only), do: {[], []}
514 # For some activities, only notify the author of the object
515 def get_potential_receiver_ap_ids(%{data: %{"type" => type, "object" => object_id}})
516 when type in ~w{Like Announce EmojiReact} do
517 case Object.get_cached_by_ap_id(object_id) do
518 %Object{data: %{"actor" => actor}} ->
526 def get_potential_receiver_ap_ids(%{data: %{"type" => "Follow", "object" => object_id}}) do
530 def get_potential_receiver_ap_ids(%{data: %{"type" => "Flag", "actor" => actor}}) do
531 (User.all_superusers() |> Enum.map(fn user -> user.ap_id end)) -- [actor]
534 def get_potential_receiver_ap_ids(activity) do
536 |> Utils.maybe_notify_to_recipients(activity)
537 |> Utils.maybe_notify_mentioned_recipients(activity)
538 |> Utils.maybe_notify_subscribers(activity)
539 |> Utils.maybe_notify_followers(activity)
543 @doc "Filters out AP IDs domain-blocking and not following the activity's actor"
544 def exclude_domain_blocker_ap_ids(ap_ids, activity, preloaded_users \\ [])
546 def exclude_domain_blocker_ap_ids([], _activity, _preloaded_users), do: []
548 def exclude_domain_blocker_ap_ids(ap_ids, %Activity{} = activity, preloaded_users) do
549 activity_actor_domain = activity.actor && URI.parse(activity.actor).host
553 |> Enum.map(fn ap_id ->
554 Enum.find(preloaded_users, &(&1.ap_id == ap_id)) ||
555 User.get_cached_by_ap_id(ap_id)
559 domain_blocker_ap_ids = for u <- users, activity_actor_domain in u.domain_blocks, do: u.ap_id
561 domain_blocker_follower_ap_ids =
562 if Enum.any?(domain_blocker_ap_ids) do
564 |> Activity.user_actor()
565 |> FollowingRelationship.followers_ap_ids(domain_blocker_ap_ids)
571 |> Kernel.--(domain_blocker_ap_ids)
572 |> Kernel.++(domain_blocker_follower_ap_ids)
575 @doc "Filters out AP IDs of users basing on their relationships with activity actor user"
576 def exclude_relationship_restricted_ap_ids([], _activity), do: []
578 def exclude_relationship_restricted_ap_ids(ap_ids, %Activity{} = activity) do
579 relationship_restricted_ap_ids =
581 |> Activity.user_actor()
582 |> User.incoming_relationships_ungrouped_ap_ids([
587 Enum.uniq(ap_ids) -- relationship_restricted_ap_ids
590 @doc "Filters out AP IDs of users who mute activity thread"
591 def exclude_thread_muter_ap_ids([], _activity), do: []
593 def exclude_thread_muter_ap_ids(ap_ids, %Activity{} = activity) do
594 thread_muter_ap_ids = ThreadMute.muter_ap_ids(activity.data["context"])
596 Enum.uniq(ap_ids) -- thread_muter_ap_ids
599 def skip?(activity, user, opts \\ [])
601 @spec skip?(Activity.t(), User.t(), Keyword.t()) :: boolean()
602 def skip?(%Activity{} = activity, %User{} = user, opts) do
606 :block_from_strangers,
610 |> Enum.find(&skip?(&1, activity, user, opts))
613 def skip?(_activity, _user, _opts), do: false
615 @spec skip?(atom(), Activity.t(), User.t(), Keyword.t()) :: boolean()
616 def skip?(:self, %Activity{} = activity, %User{} = user, opts) do
618 opts[:type] == "poll" -> false
619 activity.data["actor"] == user.ap_id -> true
624 def skip?(:invisible, %Activity{} = activity, _user, _opts) do
625 actor = activity.data["actor"]
626 user = User.get_cached_by_ap_id(actor)
627 User.invisible?(user)
631 :block_from_strangers,
632 %Activity{} = activity,
633 %User{notification_settings: %{block_from_strangers: true}} = user,
636 actor = activity.data["actor"]
637 follower = User.get_cached_by_ap_id(actor)
638 !User.following?(follower, user)
641 # To do: consider defining recency in hours and checking FollowingRelationship with a single SQL
644 %Activity{data: %{"type" => "Follow"}} = activity,
648 actor = activity.data["actor"]
650 Notification.for_user(user)
652 %{activity: %{data: %{"type" => "Follow", "actor" => ^actor}}} -> true
657 def skip?(:filtered, %{data: %{"type" => type}}, _user, _opts) when type in ["Follow", "Move"],
660 def skip?(:filtered, activity, user, _opts) do
661 object = Object.normalize(activity, fetch: false)
667 object.data["actor"] == user.ap_id ->
670 not is_nil(regex = Pleroma.Filter.compose_regex(user, :re)) ->
671 Regex.match?(regex, object.data["content"])
678 def skip?(_type, _activity, _user, _opts), do: false
680 def mark_as_read?(activity, target_user) do
681 user = Activity.user_actor(activity)
682 User.mutes_user?(target_user, user) || CommonAPI.thread_muted?(target_user, activity)
685 def for_user_and_activity(user, activity) do
686 from(n in __MODULE__,
687 where: n.user_id == ^user.id,
688 where: n.activity_id == ^activity.id
693 @spec mark_context_as_read(User.t(), String.t()) :: {integer(), nil | [term()]}
694 def mark_context_as_read(%User{id: id}, context) do
697 join: a in assoc(n, :activity),
698 where: n.user_id == ^id,
699 where: n.seen == false,
700 where: fragment("?->>'context'", a.data) == ^context
702 |> Repo.update_all(set: [seen: true])