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)
33 belongs_to(:user, User, type: FlakeId.Ecto.CompatType)
34 belongs_to(:activity, Activity, type: FlakeId.Ecto.CompatType)
39 def changeset(%Notification{} = notification, attrs) do
41 |> cast(attrs, [:seen])
44 @spec last_read_query(User.t()) :: Ecto.Queryable.t()
45 def last_read_query(user) do
46 from(q in Pleroma.Notification,
47 where: q.user_id == ^user.id,
48 where: q.seen == true,
49 select: type(q.id, :string),
55 defp for_user_query_ap_id_opts(user, opts) do
58 if opts[@include_muted_option], do: [], else: [:notification_mute]
60 preloaded_ap_ids = User.outgoing_relationships_ap_ids(user, ap_id_relationships)
62 exclude_blocked_opts = Map.merge(%{blocked_users_ap_ids: preloaded_ap_ids[:block]}, opts)
64 exclude_notification_muted_opts =
65 Map.merge(%{notification_muted_users_ap_ids: preloaded_ap_ids[:notification_mute]}, opts)
67 {exclude_blocked_opts, exclude_notification_muted_opts}
70 def for_user_query(user, opts \\ %{}) do
71 {exclude_blocked_opts, exclude_notification_muted_opts} =
72 for_user_query_ap_id_opts(user, opts)
75 |> where(user_id: ^user.id)
79 "? not in (SELECT ap_id FROM users WHERE deactivated = 'true')",
83 |> join(:inner, [n], activity in assoc(n, :activity))
84 |> join(:left, [n, a], object in Object,
87 "(?->>'id') = COALESCE((? -> 'object'::text) ->> 'id'::text)",
92 |> preload([n, a, o], activity: {a, object: o})
93 |> exclude_notification_muted(user, exclude_notification_muted_opts)
94 |> exclude_blocked(user, exclude_blocked_opts)
95 |> exclude_visibility(opts)
98 # Excludes blocked users and non-followed domain-blocked users
99 defp exclude_blocked(query, user, opts) do
100 blocked_ap_ids = opts[:blocked_users_ap_ids] || User.blocked_users_ap_ids(user)
103 |> where([n, a], a.actor not in ^blocked_ap_ids)
104 |> FollowingRelationship.keep_following_or_not_domain_blocked(user)
107 defp exclude_notification_muted(query, _, %{@include_muted_option => true}) do
111 defp exclude_notification_muted(query, user, opts) do
112 notification_muted_ap_ids =
113 opts[:notification_muted_users_ap_ids] || User.notification_muted_users_ap_ids(user)
116 |> where([n, a], a.actor not in ^notification_muted_ap_ids)
117 |> join(:left, [n, a], tm in ThreadMute,
118 on: tm.user_id == ^user.id and tm.context == fragment("?->>'context'", a.data)
120 |> where([n, a, o, tm], is_nil(tm.user_id))
123 @valid_visibilities ~w[direct unlisted public private]
125 defp exclude_visibility(query, %{exclude_visibilities: visibility})
126 when is_list(visibility) do
127 if Enum.all?(visibility, &(&1 in @valid_visibilities)) do
129 |> join(:left, [n, a], mutated_activity in Pleroma.Activity,
131 fragment("?->>'context'", a.data) ==
132 fragment("?->>'context'", mutated_activity.data) and
133 fragment("(?->>'type' = 'Like' or ?->>'type' = 'Announce')", a.data, a.data) and
134 fragment("?->>'type'", mutated_activity.data) == "Create",
135 as: :mutated_activity
138 [n, a, mutated_activity: mutated_activity],
141 CASE WHEN (?->>'type') = 'Like' or (?->>'type') = 'Announce'
142 THEN (activity_visibility(?, ?, ?) = ANY (?))
143 ELSE (activity_visibility(?, ?, ?) = ANY (?)) END
147 mutated_activity.actor,
148 mutated_activity.recipients,
149 mutated_activity.data,
158 Logger.error("Could not exclude visibility to #{visibility}")
163 defp exclude_visibility(query, %{exclude_visibilities: visibility})
164 when visibility in @valid_visibilities do
165 exclude_visibility(query, [visibility])
168 defp exclude_visibility(query, %{exclude_visibilities: visibility})
169 when visibility not in @valid_visibilities do
170 Logger.error("Could not exclude visibility to #{visibility}")
174 defp exclude_visibility(query, _visibility), do: query
176 def for_user(user, opts \\ %{}) do
178 |> for_user_query(opts)
179 |> Pagination.fetch_paginated(opts)
183 Returns notifications for user received since given date.
187 iex> Pleroma.Notification.for_user_since(%Pleroma.User{}, ~N[2019-04-13 11:22:33])
188 [%Pleroma.Notification{}, %Pleroma.Notification{}]
190 iex> Pleroma.Notification.for_user_since(%Pleroma.User{}, ~N[2019-04-15 11:22:33])
193 @spec for_user_since(Pleroma.User.t(), NaiveDateTime.t()) :: [t()]
194 def for_user_since(user, date) do
195 from(n in for_user_query(user),
196 where: n.updated_at > ^date
201 def set_read_up_to(%{id: user_id} = user, id) do
205 where: n.user_id == ^user_id,
207 where: n.seen == false,
208 # Ideally we would preload object and activities here
209 # but Ecto does not support preloads in update_all
213 {:ok, %{ids: {_, notification_ids}}} =
215 |> Multi.update_all(:ids, query, set: [seen: true, updated_at: NaiveDateTime.utc_now()])
216 |> Marker.multi_set_last_read_id(user, "notifications")
217 |> Repo.transaction()
220 |> where([n], n.id in ^notification_ids)
221 |> join(:inner, [n], activity in assoc(n, :activity))
222 |> join(:left, [n, a], object in Object,
225 "(?->>'id') = COALESCE((? -> 'object'::text) ->> 'id'::text)",
230 |> preload([n, a, o], activity: {a, object: o})
234 @spec read_one(User.t(), String.t()) ::
235 {:ok, Notification.t()} | {:error, Ecto.Changeset.t()} | nil
236 def read_one(%User{} = user, notification_id) do
237 with {:ok, %Notification{} = notification} <- get(user, notification_id) do
239 |> Multi.update(:update, changeset(notification, %{seen: true}))
240 |> Marker.multi_set_last_read_id(user, "notifications")
241 |> Repo.transaction()
243 {:ok, %{update: notification}} -> {:ok, notification}
244 {:error, :update, changeset, _} -> {:error, changeset}
249 def get(%{id: user_id} = _user, id) do
254 join: activity in assoc(n, :activity),
255 preload: [activity: activity]
258 notification = Repo.one(query)
261 %{user_id: ^user_id} ->
265 {:error, "Cannot get notification"}
270 from(n in Notification, where: n.user_id == ^user.id)
274 def destroy_multiple(%{id: user_id} = _user, ids) do
275 from(n in Notification,
277 where: n.user_id == ^user_id
282 def dismiss(%Pleroma.Activity{} = activity) do
284 |> where([n], n.activity_id == ^activity.id)
287 {_, notifications} -> {:ok, notifications}
288 _ -> {:error, "Cannot dismiss notification"}
292 def dismiss(%{id: user_id} = _user, id) do
293 notification = Repo.get(Notification, id)
296 %{user_id: ^user_id} ->
297 Repo.delete(notification)
300 {:error, "Cannot dismiss notification"}
304 def create_notifications(%Activity{data: %{"to" => _, "type" => "Create"}} = activity) do
305 object = Object.normalize(activity)
307 if object && object.data["type"] == "Answer" do
310 do_create_notifications(activity)
314 def create_notifications(%Activity{data: %{"type" => type}} = activity)
315 when type in ["Follow", "Like", "Announce", "Move", "EmojiReact"] do
316 do_create_notifications(activity)
319 def create_notifications(_), do: {:ok, []}
321 defp do_create_notifications(%Activity{} = activity) do
322 {enabled_receivers, disabled_receivers} = get_notified_from_activity(activity)
323 potential_receivers = enabled_receivers ++ disabled_receivers
326 Enum.map(potential_receivers, fn user ->
327 do_send = user in enabled_receivers
328 create_notification(activity, user, do_send)
334 # TODO move to sql, too.
335 def create_notification(%Activity{} = activity, %User{} = user, do_send \\ true) do
336 unless skip?(activity, user) do
337 {:ok, %{notification: notification}} =
339 |> Multi.insert(:notification, %Notification{user_id: user.id, activity: activity})
340 |> Marker.multi_set_last_read_id(user, "notifications")
341 |> Repo.transaction()
344 Streamer.stream(["user", "user:notification"], notification)
345 Push.send(notification)
353 Returns a tuple with 2 elements:
354 {notification-enabled receivers, currently disabled receivers (blocking / [thread] muting)}
356 NOTE: might be called for FAKE Activities, see ActivityPub.Utils.get_notified_from_object/1
358 @spec get_notified_from_activity(Activity.t(), boolean()) :: {list(User.t()), list(User.t())}
359 def get_notified_from_activity(activity, local_only \\ true)
361 def get_notified_from_activity(%Activity{data: %{"type" => type}} = activity, local_only)
362 when type in ["Create", "Like", "Announce", "Follow", "Move", "EmojiReact"] do
363 potential_receiver_ap_ids =
365 |> Utils.maybe_notify_to_recipients(activity)
366 |> Utils.maybe_notify_mentioned_recipients(activity)
367 |> Utils.maybe_notify_subscribers(activity)
368 |> Utils.maybe_notify_followers(activity)
371 potential_receivers = User.get_users_from_set(potential_receiver_ap_ids, local_only)
373 notification_enabled_ap_ids =
374 potential_receiver_ap_ids
375 |> exclude_domain_blocker_ap_ids(activity, potential_receivers)
376 |> exclude_relationship_restricted_ap_ids(activity)
377 |> exclude_thread_muter_ap_ids(activity)
379 notification_enabled_users =
380 Enum.filter(potential_receivers, fn u -> u.ap_id in notification_enabled_ap_ids end)
382 {notification_enabled_users, potential_receivers -- notification_enabled_users}
385 def get_notified_from_activity(_, _local_only), do: {[], []}
387 @doc "Filters out AP IDs domain-blocking and not following the activity's actor"
388 def exclude_domain_blocker_ap_ids(ap_ids, activity, preloaded_users \\ [])
390 def exclude_domain_blocker_ap_ids([], _activity, _preloaded_users), do: []
392 def exclude_domain_blocker_ap_ids(ap_ids, %Activity{} = activity, preloaded_users) do
393 activity_actor_domain = activity.actor && URI.parse(activity.actor).host
397 |> Enum.map(fn ap_id ->
398 Enum.find(preloaded_users, &(&1.ap_id == ap_id)) ||
399 User.get_cached_by_ap_id(ap_id)
403 domain_blocker_ap_ids = for u <- users, activity_actor_domain in u.domain_blocks, do: u.ap_id
405 domain_blocker_follower_ap_ids =
406 if Enum.any?(domain_blocker_ap_ids) do
408 |> Activity.user_actor()
409 |> FollowingRelationship.followers_ap_ids(domain_blocker_ap_ids)
415 |> Kernel.--(domain_blocker_ap_ids)
416 |> Kernel.++(domain_blocker_follower_ap_ids)
419 @doc "Filters out AP IDs of users basing on their relationships with activity actor user"
420 def exclude_relationship_restricted_ap_ids([], _activity), do: []
422 def exclude_relationship_restricted_ap_ids(ap_ids, %Activity{} = activity) do
423 relationship_restricted_ap_ids =
425 |> Activity.user_actor()
426 |> User.incoming_relationships_ungrouped_ap_ids([
431 Enum.uniq(ap_ids) -- relationship_restricted_ap_ids
434 @doc "Filters out AP IDs of users who mute activity thread"
435 def exclude_thread_muter_ap_ids([], _activity), do: []
437 def exclude_thread_muter_ap_ids(ap_ids, %Activity{} = activity) do
438 thread_muter_ap_ids = ThreadMute.muter_ap_ids(activity.data["context"])
440 Enum.uniq(ap_ids) -- thread_muter_ap_ids
443 @spec skip?(Activity.t(), User.t()) :: boolean()
444 def skip?(%Activity{} = activity, %User{} = user) do
453 |> Enum.find(&skip?(&1, activity, user))
456 def skip?(_, _), do: false
458 @spec skip?(atom(), Activity.t(), User.t()) :: boolean()
459 def skip?(:self, %Activity{} = activity, %User{} = user) do
460 activity.data["actor"] == user.ap_id
465 %Activity{} = activity,
466 %User{notification_settings: %{followers: false}} = user
468 actor = activity.data["actor"]
469 follower = User.get_cached_by_ap_id(actor)
470 User.following?(follower, user)
475 %Activity{} = activity,
476 %User{notification_settings: %{non_followers: false}} = user
478 actor = activity.data["actor"]
479 follower = User.get_cached_by_ap_id(actor)
480 !User.following?(follower, user)
485 %Activity{} = activity,
486 %User{notification_settings: %{follows: false}} = user
488 actor = activity.data["actor"]
489 followed = User.get_cached_by_ap_id(actor)
490 User.following?(user, followed)
495 %Activity{} = activity,
496 %User{notification_settings: %{non_follows: false}} = user
498 actor = activity.data["actor"]
499 followed = User.get_cached_by_ap_id(actor)
500 !User.following?(user, followed)
503 # To do: consider defining recency in hours and checking FollowingRelationship with a single SQL
504 def skip?(:recently_followed, %Activity{data: %{"type" => "Follow"}} = activity, %User{} = user) do
505 actor = activity.data["actor"]
507 Notification.for_user(user)
509 %{activity: %{data: %{"type" => "Follow", "actor" => ^actor}}} -> true
514 def skip?(_, _, _), do: false