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.Notification do
10 alias Pleroma.FollowingRelationship
12 alias Pleroma.Notification
14 alias Pleroma.Pagination
16 alias Pleroma.ThreadMute
18 alias Pleroma.Web.CommonAPI.Utils
19 alias Pleroma.Web.Push
20 alias Pleroma.Web.Streamer
27 @type t :: %__MODULE__{}
29 @include_muted_option :with_muted
31 schema "notifications" do
32 field(:seen, :boolean, default: false)
34 belongs_to(:user, User, type: FlakeId.Ecto.CompatType)
35 belongs_to(:activity, Activity, type: FlakeId.Ecto.CompatType)
40 def fill_in_notification_types do
43 where: is_nil(n.type),
49 |> Enum.each(fn notification ->
52 |> type_from_activity(no_cachex: true)
55 |> changeset(%{type: type})
60 def update_notification_type(user, activity) do
61 with %__MODULE__{} = notification <-
62 Repo.get_by(__MODULE__, user_id: user.id, activity_id: activity.id) do
65 |> type_from_activity()
68 |> changeset(%{type: type})
73 @spec unread_notifications_count(User.t()) :: integer()
74 def unread_notifications_count(%User{id: user_id}) do
76 where: q.user_id == ^user_id and q.seen == false
78 |> Repo.aggregate(:count, :id)
81 def changeset(%Notification{} = notification, attrs) do
83 |> cast(attrs, [:seen, :type])
86 @spec last_read_query(User.t()) :: Ecto.Queryable.t()
87 def last_read_query(user) do
88 from(q in Pleroma.Notification,
89 where: q.user_id == ^user.id,
90 where: q.seen == true,
91 select: type(q.id, :string),
97 defp for_user_query_ap_id_opts(user, opts) do
100 if opts[@include_muted_option], do: [], else: [:notification_mute]
102 preloaded_ap_ids = User.outgoing_relationships_ap_ids(user, ap_id_relationships)
104 exclude_blocked_opts = Map.merge(%{blocked_users_ap_ids: preloaded_ap_ids[:block]}, opts)
106 exclude_notification_muted_opts =
107 Map.merge(%{notification_muted_users_ap_ids: preloaded_ap_ids[:notification_mute]}, opts)
109 {exclude_blocked_opts, exclude_notification_muted_opts}
112 def for_user_query(user, opts \\ %{}) do
113 {exclude_blocked_opts, exclude_notification_muted_opts} =
114 for_user_query_ap_id_opts(user, opts)
117 |> where(user_id: ^user.id)
121 "? not in (SELECT ap_id FROM users WHERE deactivated = 'true')",
125 |> join(:inner, [n], activity in assoc(n, :activity))
126 |> join(:left, [n, a], object in Object,
129 "(?->>'id') = COALESCE(?->'object'->>'id', ?->>'object')",
135 |> preload([n, a, o], activity: {a, object: o})
136 |> exclude_notification_muted(user, exclude_notification_muted_opts)
137 |> exclude_blocked(user, exclude_blocked_opts)
138 |> exclude_visibility(opts)
141 # Excludes blocked users and non-followed domain-blocked users
142 defp exclude_blocked(query, user, opts) do
143 blocked_ap_ids = opts[:blocked_users_ap_ids] || User.blocked_users_ap_ids(user)
146 |> where([n, a], a.actor not in ^blocked_ap_ids)
147 |> FollowingRelationship.keep_following_or_not_domain_blocked(user)
150 defp exclude_notification_muted(query, _, %{@include_muted_option => true}) do
154 defp exclude_notification_muted(query, user, opts) do
155 notification_muted_ap_ids =
156 opts[:notification_muted_users_ap_ids] || User.notification_muted_users_ap_ids(user)
159 |> where([n, a], a.actor not in ^notification_muted_ap_ids)
160 |> join(:left, [n, a], tm in ThreadMute,
161 on: tm.user_id == ^user.id and tm.context == fragment("?->>'context'", a.data)
163 |> where([n, a, o, tm], is_nil(tm.user_id))
166 @valid_visibilities ~w[direct unlisted public private]
168 defp exclude_visibility(query, %{exclude_visibilities: visibility})
169 when is_list(visibility) do
170 if Enum.all?(visibility, &(&1 in @valid_visibilities)) do
172 |> join(:left, [n, a], mutated_activity in Pleroma.Activity,
174 fragment("?->>'context'", a.data) ==
175 fragment("?->>'context'", mutated_activity.data) and
176 fragment("(?->>'type' = 'Like' or ?->>'type' = 'Announce')", a.data, a.data) and
177 fragment("?->>'type'", mutated_activity.data) == "Create",
178 as: :mutated_activity
181 [n, a, mutated_activity: mutated_activity],
184 CASE WHEN (?->>'type') = 'Like' or (?->>'type') = 'Announce'
185 THEN (activity_visibility(?, ?, ?) = ANY (?))
186 ELSE (activity_visibility(?, ?, ?) = ANY (?)) END
190 mutated_activity.actor,
191 mutated_activity.recipients,
192 mutated_activity.data,
201 Logger.error("Could not exclude visibility to #{visibility}")
206 defp exclude_visibility(query, %{exclude_visibilities: visibility})
207 when visibility in @valid_visibilities do
208 exclude_visibility(query, [visibility])
211 defp exclude_visibility(query, %{exclude_visibilities: visibility})
212 when visibility not in @valid_visibilities do
213 Logger.error("Could not exclude visibility to #{visibility}")
217 defp exclude_visibility(query, _visibility), do: query
219 def for_user(user, opts \\ %{}) do
221 |> for_user_query(opts)
222 |> Pagination.fetch_paginated(opts)
226 Returns notifications for user received since given date.
230 iex> Pleroma.Notification.for_user_since(%Pleroma.User{}, ~N[2019-04-13 11:22:33])
231 [%Pleroma.Notification{}, %Pleroma.Notification{}]
233 iex> Pleroma.Notification.for_user_since(%Pleroma.User{}, ~N[2019-04-15 11:22:33])
236 @spec for_user_since(Pleroma.User.t(), NaiveDateTime.t()) :: [t()]
237 def for_user_since(user, date) do
238 from(n in for_user_query(user),
239 where: n.updated_at > ^date
244 def set_read_up_to(%{id: user_id} = user, id) do
248 where: n.user_id == ^user_id,
250 where: n.seen == false,
251 # Ideally we would preload object and activities here
252 # but Ecto does not support preloads in update_all
256 {:ok, %{ids: {_, notification_ids}}} =
258 |> Multi.update_all(:ids, query, set: [seen: true, updated_at: NaiveDateTime.utc_now()])
259 |> Marker.multi_set_last_read_id(user, "notifications")
260 |> Repo.transaction()
263 |> where([n], n.id in ^notification_ids)
267 @spec read_one(User.t(), String.t()) ::
268 {:ok, Notification.t()} | {:error, Ecto.Changeset.t()} | nil
269 def read_one(%User{} = user, notification_id) do
270 with {:ok, %Notification{} = notification} <- get(user, notification_id) do
272 |> Multi.update(:update, changeset(notification, %{seen: true}))
273 |> Marker.multi_set_last_read_id(user, "notifications")
274 |> Repo.transaction()
276 {:ok, %{update: notification}} -> {:ok, notification}
277 {:error, :update, changeset, _} -> {:error, changeset}
282 def get(%{id: user_id} = _user, id) do
287 join: activity in assoc(n, :activity),
288 preload: [activity: activity]
291 notification = Repo.one(query)
294 %{user_id: ^user_id} ->
298 {:error, "Cannot get notification"}
303 from(n in Notification, where: n.user_id == ^user.id)
307 def destroy_multiple(%{id: user_id} = _user, ids) do
308 from(n in Notification,
310 where: n.user_id == ^user_id
315 def dismiss(%Pleroma.Activity{} = activity) do
317 |> where([n], n.activity_id == ^activity.id)
320 {_, notifications} -> {:ok, notifications}
321 _ -> {:error, "Cannot dismiss notification"}
325 def dismiss(%{id: user_id} = _user, id) do
326 notification = Repo.get(Notification, id)
329 %{user_id: ^user_id} ->
330 Repo.delete(notification)
333 {:error, "Cannot dismiss notification"}
337 def create_notifications(%Activity{data: %{"to" => _, "type" => "Create"}} = activity) do
338 object = Object.normalize(activity, false)
340 if object && object.data["type"] == "Answer" do
343 do_create_notifications(activity)
347 def create_notifications(%Activity{data: %{"type" => type}} = activity)
348 when type in ["Follow", "Like", "Announce", "Move", "EmojiReact"] do
349 do_create_notifications(activity)
352 def create_notifications(_), do: {:ok, []}
354 defp do_create_notifications(%Activity{} = activity) do
355 {enabled_receivers, disabled_receivers} = get_notified_from_activity(activity)
356 potential_receivers = enabled_receivers ++ disabled_receivers
359 Enum.map(potential_receivers, fn user ->
360 do_send = user in enabled_receivers
361 create_notification(activity, user, do_send)
367 defp type_from_activity(%{data: %{"type" => type}} = activity, opts \\ []) do
371 if Keyword.get(opts, :no_cachex, false) do
372 # A special function to make this usable in a migration.
374 with %User{} = follower <- User.get_by_ap_id(activity.data["actor"]),
375 %User{} = followed <- User.get_by_ap_id(activity.data["object"]) do
376 Pleroma.FollowingRelationship.following?(follower, followed)
380 &Activity.follow_accepted?/1
383 if accepted_function.(activity) do
399 "pleroma:emoji_reaction"
401 # Compatibility with old reactions
403 "pleroma:emoji_reaction"
407 |> type_from_activity_object()
410 raise "No notification type for activity type #{t}"
414 defp type_from_activity_object(%{data: %{"type" => "Create", "object" => %{}}}), do: "mention"
416 defp type_from_activity_object(%{data: %{"type" => "Create"}} = activity) do
417 object = Object.get_by_ap_id(activity.data["object"])
419 case object && object.data["type"] do
420 "ChatMessage" -> "pleroma:chat_mention"
425 # TODO move to sql, too.
426 def create_notification(%Activity{} = activity, %User{} = user, do_send \\ true) do
427 unless skip?(activity, user) do
428 {:ok, %{notification: notification}} =
430 |> Multi.insert(:notification, %Notification{
433 type: type_from_activity(activity)
435 |> Marker.multi_set_last_read_id(user, "notifications")
436 |> Repo.transaction()
439 Streamer.stream(["user", "user:notification"], notification)
440 Push.send(notification)
448 Returns a tuple with 2 elements:
449 {notification-enabled receivers, currently disabled receivers (blocking / [thread] muting)}
451 NOTE: might be called for FAKE Activities, see ActivityPub.Utils.get_notified_from_object/1
453 @spec get_notified_from_activity(Activity.t(), boolean()) :: {list(User.t()), list(User.t())}
454 def get_notified_from_activity(activity, local_only \\ true)
456 def get_notified_from_activity(%Activity{data: %{"type" => type}} = activity, local_only)
457 when type in ["Create", "Like", "Announce", "Follow", "Move", "EmojiReact"] do
458 potential_receiver_ap_ids = get_potential_receiver_ap_ids(activity)
460 potential_receivers =
461 User.get_users_from_set(potential_receiver_ap_ids, local_only: local_only)
463 notification_enabled_ap_ids =
464 potential_receiver_ap_ids
465 |> exclude_domain_blocker_ap_ids(activity, potential_receivers)
466 |> exclude_relationship_restricted_ap_ids(activity)
467 |> exclude_thread_muter_ap_ids(activity)
469 notification_enabled_users =
470 Enum.filter(potential_receivers, fn u -> u.ap_id in notification_enabled_ap_ids end)
472 {notification_enabled_users, potential_receivers -- notification_enabled_users}
475 def get_notified_from_activity(_, _local_only), do: {[], []}
477 # For some activities, only notify the author of the object
478 def get_potential_receiver_ap_ids(%{data: %{"type" => type, "object" => object_id}})
479 when type in ~w{Like Announce EmojiReact} do
480 case Object.get_cached_by_ap_id(object_id) do
481 %Object{data: %{"actor" => actor}} ->
489 def get_potential_receiver_ap_ids(activity) do
491 |> Utils.maybe_notify_to_recipients(activity)
492 |> Utils.maybe_notify_mentioned_recipients(activity)
493 |> Utils.maybe_notify_subscribers(activity)
494 |> Utils.maybe_notify_followers(activity)
498 @doc "Filters out AP IDs domain-blocking and not following the activity's actor"
499 def exclude_domain_blocker_ap_ids(ap_ids, activity, preloaded_users \\ [])
501 def exclude_domain_blocker_ap_ids([], _activity, _preloaded_users), do: []
503 def exclude_domain_blocker_ap_ids(ap_ids, %Activity{} = activity, preloaded_users) do
504 activity_actor_domain = activity.actor && URI.parse(activity.actor).host
508 |> Enum.map(fn ap_id ->
509 Enum.find(preloaded_users, &(&1.ap_id == ap_id)) ||
510 User.get_cached_by_ap_id(ap_id)
514 domain_blocker_ap_ids = for u <- users, activity_actor_domain in u.domain_blocks, do: u.ap_id
516 domain_blocker_follower_ap_ids =
517 if Enum.any?(domain_blocker_ap_ids) do
519 |> Activity.user_actor()
520 |> FollowingRelationship.followers_ap_ids(domain_blocker_ap_ids)
526 |> Kernel.--(domain_blocker_ap_ids)
527 |> Kernel.++(domain_blocker_follower_ap_ids)
530 @doc "Filters out AP IDs of users basing on their relationships with activity actor user"
531 def exclude_relationship_restricted_ap_ids([], _activity), do: []
533 def exclude_relationship_restricted_ap_ids(ap_ids, %Activity{} = activity) do
534 relationship_restricted_ap_ids =
536 |> Activity.user_actor()
537 |> User.incoming_relationships_ungrouped_ap_ids([
542 Enum.uniq(ap_ids) -- relationship_restricted_ap_ids
545 @doc "Filters out AP IDs of users who mute activity thread"
546 def exclude_thread_muter_ap_ids([], _activity), do: []
548 def exclude_thread_muter_ap_ids(ap_ids, %Activity{} = activity) do
549 thread_muter_ap_ids = ThreadMute.muter_ap_ids(activity.data["context"])
551 Enum.uniq(ap_ids) -- thread_muter_ap_ids
554 @spec skip?(Activity.t(), User.t()) :: boolean()
555 def skip?(%Activity{} = activity, %User{} = user) do
564 |> Enum.find(&skip?(&1, activity, user))
567 def skip?(_, _), do: false
569 @spec skip?(atom(), Activity.t(), User.t()) :: boolean()
570 def skip?(:self, %Activity{} = activity, %User{} = user) do
571 activity.data["actor"] == user.ap_id
576 %Activity{} = activity,
577 %User{notification_settings: %{followers: false}} = user
579 actor = activity.data["actor"]
580 follower = User.get_cached_by_ap_id(actor)
581 User.following?(follower, user)
586 %Activity{} = activity,
587 %User{notification_settings: %{non_followers: false}} = user
589 actor = activity.data["actor"]
590 follower = User.get_cached_by_ap_id(actor)
591 !User.following?(follower, user)
596 %Activity{} = activity,
597 %User{notification_settings: %{follows: false}} = user
599 actor = activity.data["actor"]
600 followed = User.get_cached_by_ap_id(actor)
601 User.following?(user, followed)
606 %Activity{} = activity,
607 %User{notification_settings: %{non_follows: false}} = user
609 actor = activity.data["actor"]
610 followed = User.get_cached_by_ap_id(actor)
611 !User.following?(user, followed)
614 # To do: consider defining recency in hours and checking FollowingRelationship with a single SQL
615 def skip?(:recently_followed, %Activity{data: %{"type" => "Follow"}} = activity, %User{} = user) do
616 actor = activity.data["actor"]
618 Notification.for_user(user)
620 %{activity: %{data: %{"type" => "Follow", "actor" => ^actor}}} -> true
625 def skip?(_, _, _), do: false