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
9 alias Pleroma.FollowingRelationship
10 alias Pleroma.Notification
12 alias Pleroma.Pagination
14 alias Pleroma.ThreadMute
16 alias Pleroma.Web.CommonAPI.Utils
17 alias Pleroma.Web.Push
18 alias Pleroma.Web.Streamer
25 @type t :: %__MODULE__{}
27 @include_muted_option :with_muted
29 schema "notifications" do
30 field(:seen, :boolean, default: false)
31 belongs_to(:user, User, type: FlakeId.Ecto.CompatType)
32 belongs_to(:activity, Activity, type: FlakeId.Ecto.CompatType)
37 def changeset(%Notification{} = notification, attrs) do
39 |> cast(attrs, [:seen])
42 defp for_user_query_ap_id_opts(user, opts) do
45 if opts[@include_muted_option], do: [], else: [:notification_mute]
47 preloaded_ap_ids = User.outgoing_relationships_ap_ids(user, ap_id_relationships)
49 exclude_blocked_opts = Map.merge(%{blocked_users_ap_ids: preloaded_ap_ids[:block]}, opts)
51 exclude_notification_muted_opts =
52 Map.merge(%{notification_muted_users_ap_ids: preloaded_ap_ids[:notification_mute]}, opts)
54 {exclude_blocked_opts, exclude_notification_muted_opts}
57 def for_user_query(user, opts \\ %{}) do
58 {exclude_blocked_opts, exclude_notification_muted_opts} =
59 for_user_query_ap_id_opts(user, opts)
62 |> where(user_id: ^user.id)
66 "? not in (SELECT ap_id FROM users WHERE deactivated = 'true')",
70 |> join(:inner, [n], activity in assoc(n, :activity))
71 |> join(:left, [n, a], object in Object,
74 "(?->>'id') = COALESCE((? -> 'object'::text) ->> 'id'::text)",
79 |> preload([n, a, o], activity: {a, object: o})
80 |> exclude_notification_muted(user, exclude_notification_muted_opts)
81 |> exclude_blocked(user, exclude_blocked_opts)
82 |> exclude_visibility(opts)
85 # Excludes blocked users and non-followed domain-blocked users
86 defp exclude_blocked(query, user, opts) do
87 blocked_ap_ids = opts[:blocked_users_ap_ids] || User.blocked_users_ap_ids(user)
90 |> where([n, a], a.actor not in ^blocked_ap_ids)
91 |> FollowingRelationship.keep_following_or_not_domain_blocked(user)
94 defp exclude_notification_muted(query, _, %{@include_muted_option => true}) do
98 defp exclude_notification_muted(query, user, opts) do
99 notification_muted_ap_ids =
100 opts[:notification_muted_users_ap_ids] || User.notification_muted_users_ap_ids(user)
103 |> where([n, a], a.actor not in ^notification_muted_ap_ids)
104 |> join(:left, [n, a], tm in ThreadMute,
105 on: tm.user_id == ^user.id and tm.context == fragment("?->>'context'", a.data)
107 |> where([n, a, o, tm], is_nil(tm.user_id))
110 @valid_visibilities ~w[direct unlisted public private]
112 defp exclude_visibility(query, %{exclude_visibilities: visibility})
113 when is_list(visibility) do
114 if Enum.all?(visibility, &(&1 in @valid_visibilities)) do
116 |> join(:left, [n, a], mutated_activity in Pleroma.Activity,
118 fragment("?->>'context'", a.data) ==
119 fragment("?->>'context'", mutated_activity.data) and
120 fragment("(?->>'type' = 'Like' or ?->>'type' = 'Announce')", a.data, a.data) and
121 fragment("?->>'type'", mutated_activity.data) == "Create",
122 as: :mutated_activity
125 [n, a, mutated_activity: mutated_activity],
128 CASE WHEN (?->>'type') = 'Like' or (?->>'type') = 'Announce'
129 THEN (activity_visibility(?, ?, ?) = ANY (?))
130 ELSE (activity_visibility(?, ?, ?) = ANY (?)) END
134 mutated_activity.actor,
135 mutated_activity.recipients,
136 mutated_activity.data,
145 Logger.error("Could not exclude visibility to #{visibility}")
150 defp exclude_visibility(query, %{exclude_visibilities: visibility})
151 when visibility in @valid_visibilities do
152 exclude_visibility(query, [visibility])
155 defp exclude_visibility(query, %{exclude_visibilities: visibility})
156 when visibility not in @valid_visibilities do
157 Logger.error("Could not exclude visibility to #{visibility}")
161 defp exclude_visibility(query, _visibility), do: query
163 def for_user(user, opts \\ %{}) do
165 |> for_user_query(opts)
166 |> Pagination.fetch_paginated(opts)
170 Returns notifications for user received since given date.
174 iex> Pleroma.Notification.for_user_since(%Pleroma.User{}, ~N[2019-04-13 11:22:33])
175 [%Pleroma.Notification{}, %Pleroma.Notification{}]
177 iex> Pleroma.Notification.for_user_since(%Pleroma.User{}, ~N[2019-04-15 11:22:33])
180 @spec for_user_since(Pleroma.User.t(), NaiveDateTime.t()) :: [t()]
181 def for_user_since(user, date) do
182 from(n in for_user_query(user),
183 where: n.updated_at > ^date
188 def set_read_up_to(%{id: user_id} = _user, id) do
192 where: n.user_id == ^user_id,
194 where: n.seen == false,
198 updated_at: ^NaiveDateTime.utc_now()
201 # Ideally we would preload object and activities here
202 # but Ecto does not support preloads in update_all
206 {_, notification_ids} = Repo.update_all(query, [])
209 |> where([n], n.id in ^notification_ids)
210 |> join(:inner, [n], activity in assoc(n, :activity))
211 |> join(:left, [n, a], object in Object,
214 "(?->>'id') = COALESCE((? -> 'object'::text) ->> 'id'::text)",
219 |> preload([n, a, o], activity: {a, object: o})
223 def read_one(%User{} = user, notification_id) do
224 with {:ok, %Notification{} = notification} <- get(user, notification_id) do
226 |> changeset(%{seen: true})
231 def get(%{id: user_id} = _user, id) do
236 join: activity in assoc(n, :activity),
237 preload: [activity: activity]
240 notification = Repo.one(query)
243 %{user_id: ^user_id} ->
247 {:error, "Cannot get notification"}
252 from(n in Notification, where: n.user_id == ^user.id)
256 def destroy_multiple(%{id: user_id} = _user, ids) do
257 from(n in Notification,
259 where: n.user_id == ^user_id
264 def dismiss(%Pleroma.Activity{} = activity) do
266 |> where([n], n.activity_id == ^activity.id)
269 {_, notifications} -> {:ok, notifications}
270 _ -> {:error, "Cannot dismiss notification"}
274 def dismiss(%{id: user_id} = _user, id) do
275 notification = Repo.get(Notification, id)
278 %{user_id: ^user_id} ->
279 Repo.delete(notification)
282 {:error, "Cannot dismiss notification"}
286 def create_notifications(%Activity{data: %{"to" => _, "type" => "Create"}} = activity) do
287 object = Object.normalize(activity, false)
289 if object && object.data["type"] == "Answer" do
292 do_create_notifications(activity)
296 def create_notifications(%Activity{data: %{"type" => type}} = activity)
297 when type in ["Follow", "Like", "Announce", "Move", "EmojiReact"] do
298 do_create_notifications(activity)
301 def create_notifications(_), do: {:ok, []}
303 defp do_create_notifications(%Activity{} = activity) do
304 {enabled_receivers, disabled_receivers} = get_notified_from_activity(activity)
305 potential_receivers = enabled_receivers ++ disabled_receivers
308 Enum.map(potential_receivers, fn user ->
309 do_send = user in enabled_receivers
310 create_notification(activity, user, do_send)
316 # TODO move to sql, too.
317 def create_notification(%Activity{} = activity, %User{} = user, do_send \\ true) do
318 unless skip?(activity, user) do
319 notification = %Notification{user_id: user.id, activity: activity}
320 {:ok, notification} = Repo.insert(notification)
323 Streamer.stream(["user", "user:notification"], notification)
324 Push.send(notification)
332 Returns a tuple with 2 elements:
333 {notification-enabled receivers, currently disabled receivers (blocking / [thread] muting)}
335 NOTE: might be called for FAKE Activities, see ActivityPub.Utils.get_notified_from_object/1
337 @spec get_notified_from_activity(Activity.t(), boolean()) :: {list(User.t()), list(User.t())}
338 def get_notified_from_activity(activity, local_only \\ true)
340 def get_notified_from_activity(%Activity{data: %{"type" => type}} = activity, local_only)
341 when type in ["Create", "Like", "Announce", "Follow", "Move", "EmojiReact"] do
342 potential_receiver_ap_ids =
344 |> Utils.maybe_notify_to_recipients(activity)
345 |> Utils.maybe_notify_mentioned_recipients(activity)
346 |> Utils.maybe_notify_subscribers(activity)
347 |> Utils.maybe_notify_followers(activity)
350 potential_receivers = User.get_users_from_set(potential_receiver_ap_ids, local_only)
352 notification_enabled_ap_ids =
353 potential_receiver_ap_ids
354 |> exclude_domain_blocker_ap_ids(activity, potential_receivers)
355 |> exclude_relationship_restricted_ap_ids(activity)
356 |> exclude_thread_muter_ap_ids(activity)
358 notification_enabled_users =
359 Enum.filter(potential_receivers, fn u -> u.ap_id in notification_enabled_ap_ids end)
361 {notification_enabled_users, potential_receivers -- notification_enabled_users}
364 def get_notified_from_activity(_, _local_only), do: {[], []}
366 @doc "Filters out AP IDs domain-blocking and not following the activity's actor"
367 def exclude_domain_blocker_ap_ids(ap_ids, activity, preloaded_users \\ [])
369 def exclude_domain_blocker_ap_ids([], _activity, _preloaded_users), do: []
371 def exclude_domain_blocker_ap_ids(ap_ids, %Activity{} = activity, preloaded_users) do
372 activity_actor_domain = activity.actor && URI.parse(activity.actor).host
376 |> Enum.map(fn ap_id ->
377 Enum.find(preloaded_users, &(&1.ap_id == ap_id)) ||
378 User.get_cached_by_ap_id(ap_id)
382 domain_blocker_ap_ids = for u <- users, activity_actor_domain in u.domain_blocks, do: u.ap_id
384 domain_blocker_follower_ap_ids =
385 if Enum.any?(domain_blocker_ap_ids) do
387 |> Activity.user_actor()
388 |> FollowingRelationship.followers_ap_ids(domain_blocker_ap_ids)
394 |> Kernel.--(domain_blocker_ap_ids)
395 |> Kernel.++(domain_blocker_follower_ap_ids)
398 @doc "Filters out AP IDs of users basing on their relationships with activity actor user"
399 def exclude_relationship_restricted_ap_ids([], _activity), do: []
401 def exclude_relationship_restricted_ap_ids(ap_ids, %Activity{} = activity) do
402 relationship_restricted_ap_ids =
404 |> Activity.user_actor()
405 |> User.incoming_relationships_ungrouped_ap_ids([
410 Enum.uniq(ap_ids) -- relationship_restricted_ap_ids
413 @doc "Filters out AP IDs of users who mute activity thread"
414 def exclude_thread_muter_ap_ids([], _activity), do: []
416 def exclude_thread_muter_ap_ids(ap_ids, %Activity{} = activity) do
417 thread_muter_ap_ids = ThreadMute.muter_ap_ids(activity.data["context"])
419 Enum.uniq(ap_ids) -- thread_muter_ap_ids
422 @spec skip?(Activity.t(), User.t()) :: boolean()
423 def skip?(%Activity{} = activity, %User{} = user) do
432 |> Enum.find(&skip?(&1, activity, user))
435 def skip?(_, _), do: false
437 @spec skip?(atom(), Activity.t(), User.t()) :: boolean()
438 def skip?(:self, %Activity{} = activity, %User{} = user) do
439 activity.data["actor"] == user.ap_id
444 %Activity{} = activity,
445 %User{notification_settings: %{followers: false}} = user
447 actor = activity.data["actor"]
448 follower = User.get_cached_by_ap_id(actor)
449 User.following?(follower, user)
454 %Activity{} = activity,
455 %User{notification_settings: %{non_followers: false}} = user
457 actor = activity.data["actor"]
458 follower = User.get_cached_by_ap_id(actor)
459 !User.following?(follower, user)
464 %Activity{} = activity,
465 %User{notification_settings: %{follows: false}} = user
467 actor = activity.data["actor"]
468 followed = User.get_cached_by_ap_id(actor)
469 User.following?(user, followed)
474 %Activity{} = activity,
475 %User{notification_settings: %{non_follows: false}} = user
477 actor = activity.data["actor"]
478 followed = User.get_cached_by_ap_id(actor)
479 !User.following?(user, followed)
482 # To do: consider defining recency in hours and checking FollowingRelationship with a single SQL
483 def skip?(:recently_followed, %Activity{data: %{"type" => "Follow"}} = activity, %User{} = user) do
484 actor = activity.data["actor"]
486 Notification.for_user(user)
488 %{activity: %{data: %{"type" => "Follow", "actor" => ^actor}}} -> true
493 def skip?(_, _, _), do: false