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 # This is an enum type in the database. If you add a new notification type,
34 # remember to add a migration to add it to the `notifications_type` enum
37 belongs_to(:user, User, type: FlakeId.Ecto.CompatType)
38 belongs_to(:activity, Activity, type: FlakeId.Ecto.CompatType)
43 def update_notification_type(user, activity) do
44 with %__MODULE__{} = notification <-
45 Repo.get_by(__MODULE__, user_id: user.id, activity_id: activity.id) do
48 |> type_from_activity()
51 |> changeset(%{type: type})
56 @spec unread_notifications_count(User.t()) :: integer()
57 def unread_notifications_count(%User{id: user_id}) do
59 where: q.user_id == ^user_id and q.seen == false
61 |> Repo.aggregate(:count, :id)
64 @notification_types ~w{
71 pleroma:emoji_reaction
75 def changeset(%Notification{} = notification, attrs) do
77 |> cast(attrs, [:seen, :type])
78 |> validate_inclusion(:type, @notification_types)
81 @spec last_read_query(User.t()) :: Ecto.Queryable.t()
82 def last_read_query(user) do
83 from(q in Pleroma.Notification,
84 where: q.user_id == ^user.id,
85 where: q.seen == true,
86 select: type(q.id, :string),
92 defp for_user_query_ap_id_opts(user, opts) do
95 if opts[@include_muted_option], do: [], else: [:notification_mute]
97 preloaded_ap_ids = User.outgoing_relationships_ap_ids(user, ap_id_relationships)
99 exclude_blocked_opts = Map.merge(%{blocked_users_ap_ids: preloaded_ap_ids[:block]}, opts)
101 exclude_notification_muted_opts =
102 Map.merge(%{notification_muted_users_ap_ids: preloaded_ap_ids[:notification_mute]}, opts)
104 {exclude_blocked_opts, exclude_notification_muted_opts}
107 def for_user_query(user, opts \\ %{}) do
108 {exclude_blocked_opts, exclude_notification_muted_opts} =
109 for_user_query_ap_id_opts(user, opts)
112 |> where(user_id: ^user.id)
116 "? not in (SELECT ap_id FROM users WHERE deactivated = 'true')",
120 |> join(:inner, [n], activity in assoc(n, :activity))
121 |> join(:left, [n, a], object in Object,
124 "(?->>'id') = COALESCE(?->'object'->>'id', ?->>'object')",
130 |> preload([n, a, o], activity: {a, object: o})
131 |> exclude_notification_muted(user, exclude_notification_muted_opts)
132 |> exclude_blocked(user, exclude_blocked_opts)
133 |> exclude_filtered(user)
134 |> exclude_visibility(opts)
137 # Excludes blocked users and non-followed domain-blocked users
138 defp exclude_blocked(query, user, opts) do
139 blocked_ap_ids = opts[:blocked_users_ap_ids] || User.blocked_users_ap_ids(user)
142 |> where([n, a], a.actor not in ^blocked_ap_ids)
143 |> FollowingRelationship.keep_following_or_not_domain_blocked(user)
146 defp exclude_notification_muted(query, _, %{@include_muted_option => true}) do
150 defp exclude_notification_muted(query, user, opts) do
151 notification_muted_ap_ids =
152 opts[:notification_muted_users_ap_ids] || User.notification_muted_users_ap_ids(user)
155 |> where([n, a], a.actor not in ^notification_muted_ap_ids)
156 |> join(:left, [n, a], tm in ThreadMute,
157 on: tm.user_id == ^user.id and tm.context == fragment("?->>'context'", a.data)
159 |> where([n, a, o, tm], is_nil(tm.user_id))
162 defp exclude_filtered(query, user) do
163 case Pleroma.Filter.compose_regex(user) do
168 from([_n, a, o] in query,
170 fragment("not(?->>'content' ~* ?)", o.data, ^regex) or
171 fragment("?->>'actor' = ?", o.data, ^user.ap_id)
176 @valid_visibilities ~w[direct unlisted public private]
178 defp exclude_visibility(query, %{exclude_visibilities: visibility})
179 when is_list(visibility) do
180 if Enum.all?(visibility, &(&1 in @valid_visibilities)) do
182 |> join(:left, [n, a], mutated_activity in Pleroma.Activity,
185 "COALESCE((?->'object')->>'id', ?->>'object')",
190 "COALESCE((?->'object')->>'id', ?->>'object')",
191 mutated_activity.data,
192 mutated_activity.data
194 fragment("(?->>'type' = 'Like' or ?->>'type' = 'Announce')", a.data, a.data) and
195 fragment("?->>'type'", mutated_activity.data) == "Create",
196 as: :mutated_activity
199 [n, a, mutated_activity: mutated_activity],
202 CASE WHEN (?->>'type') = 'Like' or (?->>'type') = 'Announce'
203 THEN (activity_visibility(?, ?, ?) = ANY (?))
204 ELSE (activity_visibility(?, ?, ?) = ANY (?)) END
208 mutated_activity.actor,
209 mutated_activity.recipients,
210 mutated_activity.data,
219 Logger.error("Could not exclude visibility to #{visibility}")
224 defp exclude_visibility(query, %{exclude_visibilities: visibility})
225 when visibility in @valid_visibilities do
226 exclude_visibility(query, [visibility])
229 defp exclude_visibility(query, %{exclude_visibilities: visibility})
230 when visibility not in @valid_visibilities do
231 Logger.error("Could not exclude visibility to #{visibility}")
235 defp exclude_visibility(query, _visibility), do: query
237 def for_user(user, opts \\ %{}) do
239 |> for_user_query(opts)
240 |> Pagination.fetch_paginated(opts)
244 Returns notifications for user received since given date.
248 iex> Pleroma.Notification.for_user_since(%Pleroma.User{}, ~N[2019-04-13 11:22:33])
249 [%Pleroma.Notification{}, %Pleroma.Notification{}]
251 iex> Pleroma.Notification.for_user_since(%Pleroma.User{}, ~N[2019-04-15 11:22:33])
254 @spec for_user_since(Pleroma.User.t(), NaiveDateTime.t()) :: [t()]
255 def for_user_since(user, date) do
256 from(n in for_user_query(user),
257 where: n.updated_at > ^date
262 def set_read_up_to(%{id: user_id} = user, id) do
266 where: n.user_id == ^user_id,
268 where: n.seen == false,
269 # Ideally we would preload object and activities here
270 # but Ecto does not support preloads in update_all
274 {:ok, %{ids: {_, notification_ids}}} =
276 |> Multi.update_all(:ids, query, set: [seen: true, updated_at: NaiveDateTime.utc_now()])
277 |> Marker.multi_set_last_read_id(user, "notifications")
278 |> Repo.transaction()
281 |> where([n], n.id in ^notification_ids)
285 @spec read_one(User.t(), String.t()) ::
286 {:ok, Notification.t()} | {:error, Ecto.Changeset.t()} | nil
287 def read_one(%User{} = user, notification_id) do
288 with {:ok, %Notification{} = notification} <- get(user, notification_id) do
290 |> Multi.update(:update, changeset(notification, %{seen: true}))
291 |> Marker.multi_set_last_read_id(user, "notifications")
292 |> Repo.transaction()
294 {:ok, %{update: notification}} -> {:ok, notification}
295 {:error, :update, changeset, _} -> {:error, changeset}
300 def get(%{id: user_id} = _user, id) do
305 join: activity in assoc(n, :activity),
306 preload: [activity: activity]
309 notification = Repo.one(query)
312 %{user_id: ^user_id} ->
316 {:error, "Cannot get notification"}
321 from(n in Notification, where: n.user_id == ^user.id)
325 def destroy_multiple(%{id: user_id} = _user, ids) do
326 from(n in Notification,
328 where: n.user_id == ^user_id
333 def dismiss(%Pleroma.Activity{} = activity) do
335 |> where([n], n.activity_id == ^activity.id)
338 {_, notifications} -> {:ok, notifications}
339 _ -> {:error, "Cannot dismiss notification"}
343 def dismiss(%{id: user_id} = _user, id) do
344 notification = Repo.get(Notification, id)
347 %{user_id: ^user_id} ->
348 Repo.delete(notification)
351 {:error, "Cannot dismiss notification"}
355 @spec create_notifications(Activity.t(), keyword()) :: {:ok, [Notification.t()] | []}
356 def create_notifications(activity, options \\ [])
358 def create_notifications(%Activity{data: %{"to" => _, "type" => "Create"}} = activity, options) do
359 object = Object.normalize(activity, false)
361 if object && object.data["type"] == "Answer" do
364 do_create_notifications(activity, options)
368 def create_notifications(%Activity{data: %{"type" => type}} = activity, options)
369 when type in ["Follow", "Like", "Announce", "Move", "EmojiReact"] do
370 do_create_notifications(activity, options)
373 def create_notifications(_, _), do: {:ok, []}
375 defp do_create_notifications(%Activity{} = activity, options) do
376 do_send = Keyword.get(options, :do_send, true)
378 {enabled_receivers, disabled_receivers} = get_notified_from_activity(activity)
379 potential_receivers = enabled_receivers ++ disabled_receivers
382 Enum.map(potential_receivers, fn user ->
383 do_send = do_send && user in enabled_receivers
384 create_notification(activity, user, do_send)
386 |> Enum.reject(&is_nil/1)
391 defp type_from_activity(%{data: %{"type" => type}} = activity) do
394 if Activity.follow_accepted?(activity) do
410 "pleroma:emoji_reaction"
412 # Compatibility with old reactions
414 "pleroma:emoji_reaction"
418 |> type_from_activity_object()
421 raise "No notification type for activity type #{t}"
425 defp type_from_activity_object(%{data: %{"type" => "Create", "object" => %{}}}), do: "mention"
427 defp type_from_activity_object(%{data: %{"type" => "Create"}} = activity) do
428 object = Object.get_by_ap_id(activity.data["object"])
430 case object && object.data["type"] do
431 "ChatMessage" -> "pleroma:chat_mention"
436 # TODO move to sql, too.
437 def create_notification(%Activity{} = activity, %User{} = user, do_send \\ true) do
438 unless skip?(activity, user) do
439 {:ok, %{notification: notification}} =
441 |> Multi.insert(:notification, %Notification{
444 type: type_from_activity(activity)
446 |> Marker.multi_set_last_read_id(user, "notifications")
447 |> Repo.transaction()
450 Streamer.stream(["user", "user:notification"], notification)
451 Push.send(notification)
459 Returns a tuple with 2 elements:
460 {notification-enabled receivers, currently disabled receivers (blocking / [thread] muting)}
462 NOTE: might be called for FAKE Activities, see ActivityPub.Utils.get_notified_from_object/1
464 @spec get_notified_from_activity(Activity.t(), boolean()) :: {list(User.t()), list(User.t())}
465 def get_notified_from_activity(activity, local_only \\ true)
467 def get_notified_from_activity(%Activity{data: %{"type" => type}} = activity, local_only)
468 when type in ["Create", "Like", "Announce", "Follow", "Move", "EmojiReact"] do
469 potential_receiver_ap_ids = get_potential_receiver_ap_ids(activity)
471 potential_receivers =
472 User.get_users_from_set(potential_receiver_ap_ids, local_only: local_only)
474 notification_enabled_ap_ids =
475 potential_receiver_ap_ids
476 |> exclude_domain_blocker_ap_ids(activity, potential_receivers)
477 |> exclude_relationship_restricted_ap_ids(activity)
478 |> exclude_thread_muter_ap_ids(activity)
480 notification_enabled_users =
481 Enum.filter(potential_receivers, fn u -> u.ap_id in notification_enabled_ap_ids end)
483 {notification_enabled_users, potential_receivers -- notification_enabled_users}
486 def get_notified_from_activity(_, _local_only), do: {[], []}
488 # For some activities, only notify the author of the object
489 def get_potential_receiver_ap_ids(%{data: %{"type" => type, "object" => object_id}})
490 when type in ~w{Like Announce EmojiReact} do
491 case Object.get_cached_by_ap_id(object_id) do
492 %Object{data: %{"actor" => actor}} ->
500 def get_potential_receiver_ap_ids(%{data: %{"type" => "Follow", "object" => object_id}}) do
504 def get_potential_receiver_ap_ids(activity) do
506 |> Utils.maybe_notify_to_recipients(activity)
507 |> Utils.maybe_notify_mentioned_recipients(activity)
508 |> Utils.maybe_notify_subscribers(activity)
509 |> Utils.maybe_notify_followers(activity)
513 @doc "Filters out AP IDs domain-blocking and not following the activity's actor"
514 def exclude_domain_blocker_ap_ids(ap_ids, activity, preloaded_users \\ [])
516 def exclude_domain_blocker_ap_ids([], _activity, _preloaded_users), do: []
518 def exclude_domain_blocker_ap_ids(ap_ids, %Activity{} = activity, preloaded_users) do
519 activity_actor_domain = activity.actor && URI.parse(activity.actor).host
523 |> Enum.map(fn ap_id ->
524 Enum.find(preloaded_users, &(&1.ap_id == ap_id)) ||
525 User.get_cached_by_ap_id(ap_id)
529 domain_blocker_ap_ids = for u <- users, activity_actor_domain in u.domain_blocks, do: u.ap_id
531 domain_blocker_follower_ap_ids =
532 if Enum.any?(domain_blocker_ap_ids) do
534 |> Activity.user_actor()
535 |> FollowingRelationship.followers_ap_ids(domain_blocker_ap_ids)
541 |> Kernel.--(domain_blocker_ap_ids)
542 |> Kernel.++(domain_blocker_follower_ap_ids)
545 @doc "Filters out AP IDs of users basing on their relationships with activity actor user"
546 def exclude_relationship_restricted_ap_ids([], _activity), do: []
548 def exclude_relationship_restricted_ap_ids(ap_ids, %Activity{} = activity) do
549 relationship_restricted_ap_ids =
551 |> Activity.user_actor()
552 |> User.incoming_relationships_ungrouped_ap_ids([
557 Enum.uniq(ap_ids) -- relationship_restricted_ap_ids
560 @doc "Filters out AP IDs of users who mute activity thread"
561 def exclude_thread_muter_ap_ids([], _activity), do: []
563 def exclude_thread_muter_ap_ids(ap_ids, %Activity{} = activity) do
564 thread_muter_ap_ids = ThreadMute.muter_ap_ids(activity.data["context"])
566 Enum.uniq(ap_ids) -- thread_muter_ap_ids
569 @spec skip?(Activity.t(), User.t()) :: boolean()
570 def skip?(%Activity{} = activity, %User{} = user) do
574 :block_from_strangers,
578 |> Enum.find(&skip?(&1, activity, user))
581 def skip?(_, _), do: false
583 @spec skip?(atom(), Activity.t(), User.t()) :: boolean()
584 def skip?(:self, %Activity{} = activity, %User{} = user) do
585 activity.data["actor"] == user.ap_id
588 def skip?(:invisible, %Activity{} = activity, _) do
589 actor = activity.data["actor"]
590 user = User.get_cached_by_ap_id(actor)
591 User.invisible?(user)
595 :block_from_strangers,
596 %Activity{} = activity,
597 %User{notification_settings: %{block_from_strangers: true}} = user
599 actor = activity.data["actor"]
600 follower = User.get_cached_by_ap_id(actor)
601 !User.following?(follower, user)
604 # To do: consider defining recency in hours and checking FollowingRelationship with a single SQL
605 def skip?(:recently_followed, %Activity{data: %{"type" => "Follow"}} = activity, %User{} = user) do
606 actor = activity.data["actor"]
608 Notification.for_user(user)
610 %{activity: %{data: %{"type" => "Follow", "actor" => ^actor}}} -> true
615 def skip?(:filtered, %{data: %{"type" => type}}, _) when type in ["Follow", "Move"], do: false
617 def skip?(:filtered, activity, user) do
618 object = Object.normalize(activity)
624 object.data["actor"] == user.ap_id ->
627 not is_nil(regex = Pleroma.Filter.compose_regex(user, :re)) ->
628 Regex.match?(regex, object.data["content"])
635 def skip?(_, _, _), do: false
637 def for_user_and_activity(user, activity) do
638 from(n in __MODULE__,
639 where: n.user_id == ^user.id,
640 where: n.activity_id == ^activity.id