1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2019 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
5 defmodule Pleroma.Notification do
11 alias Pleroma.Notification
13 alias Pleroma.Pagination
16 alias Pleroma.Web.CommonAPI.Utils
17 alias Pleroma.Web.Push
18 alias Pleroma.Web.Streamer
24 @type t :: %__MODULE__{}
26 @include_muted_option :with_muted
28 schema "notifications" do
29 field(:seen, :boolean, default: false)
30 belongs_to(:user, User, type: FlakeId.Ecto.CompatType)
31 belongs_to(:activity, Activity, type: FlakeId.Ecto.CompatType)
36 def changeset(%Notification{} = notification, attrs) do
38 |> cast(attrs, [:seen])
41 @spec unread_count_query(User.t()) :: Ecto.Queryable.t()
42 def unread_count_query(user) do
43 from(q in Pleroma.Notification,
44 where: q.user_id == ^user.id,
45 where: q.seen == false
49 @spec last_read_query(User.t()) :: Ecto.Queryable.t()
50 def last_read_query(user) do
51 from(q in Pleroma.Notification,
52 where: q.user_id == ^user.id,
53 where: q.seen == true,
54 select: type(q.id, :string),
60 defp for_user_query_ap_id_opts(user, opts) do
63 if opts[@include_muted_option], do: [], else: [:notification_mute]
65 preloaded_ap_ids = User.outgoing_relations_ap_ids(user, ap_id_relations)
67 exclude_blocked_opts = Map.merge(%{blocked_users_ap_ids: preloaded_ap_ids[:block]}, opts)
69 exclude_notification_muted_opts =
70 Map.merge(%{notification_muted_users_ap_ids: preloaded_ap_ids[:notification_mute]}, opts)
72 {exclude_blocked_opts, exclude_notification_muted_opts}
75 def for_user_query(user, opts \\ %{}) do
76 {exclude_blocked_opts, exclude_notification_muted_opts} =
77 for_user_query_ap_id_opts(user, opts)
80 |> where(user_id: ^user.id)
84 "? not in (SELECT ap_id FROM users WHERE deactivated = 'true')",
88 |> join(:inner, [n], activity in assoc(n, :activity))
89 |> join(:left, [n, a], object in Object,
92 "(?->>'id') = COALESCE((? -> 'object'::text) ->> 'id'::text)",
97 |> preload([n, a, o], activity: {a, object: o})
98 |> exclude_notification_muted(user, exclude_notification_muted_opts)
99 |> exclude_blocked(user, exclude_blocked_opts)
100 |> exclude_visibility(opts)
101 |> exclude_move(opts)
104 defp exclude_blocked(query, user, opts) do
105 blocked_ap_ids = opts[:blocked_users_ap_ids] || User.blocked_users_ap_ids(user)
108 |> where([n, a], a.actor not in ^blocked_ap_ids)
111 fragment("substring(? from '.*://([^/]*)')", a.actor) not in ^user.domain_blocks
115 defp exclude_notification_muted(query, _, %{@include_muted_option => true}) do
119 defp exclude_notification_muted(query, user, opts) do
120 notification_muted_ap_ids =
121 opts[:notification_muted_users_ap_ids] || User.notification_muted_users_ap_ids(user)
124 |> where([n, a], a.actor not in ^notification_muted_ap_ids)
125 |> join(:left, [n, a], tm in Pleroma.ThreadMute,
126 on: tm.user_id == ^user.id and tm.context == fragment("?->>'context'", a.data)
128 |> where([n, a, o, tm], is_nil(tm.user_id))
131 defp exclude_move(query, %{with_move: true}) do
135 defp exclude_move(query, _opts) do
136 where(query, [n, a], fragment("?->>'type' != 'Move'", a.data))
139 @valid_visibilities ~w[direct unlisted public private]
141 defp exclude_visibility(query, %{exclude_visibilities: visibility})
142 when is_list(visibility) do
143 if Enum.all?(visibility, &(&1 in @valid_visibilities)) do
145 |> join(:left, [n, a], mutated_activity in Pleroma.Activity,
147 fragment("?->>'context'", a.data) ==
148 fragment("?->>'context'", mutated_activity.data) and
149 fragment("(?->>'type' = 'Like' or ?->>'type' = 'Announce')", a.data, a.data) and
150 fragment("?->>'type'", mutated_activity.data) == "Create",
151 as: :mutated_activity
154 [n, a, mutated_activity: mutated_activity],
157 CASE WHEN (?->>'type') = 'Like' or (?->>'type') = 'Announce'
158 THEN (activity_visibility(?, ?, ?) = ANY (?))
159 ELSE (activity_visibility(?, ?, ?) = ANY (?)) END
163 mutated_activity.actor,
164 mutated_activity.recipients,
165 mutated_activity.data,
174 Logger.error("Could not exclude visibility to #{visibility}")
179 defp exclude_visibility(query, %{exclude_visibilities: visibility})
180 when visibility in @valid_visibilities do
181 exclude_visibility(query, [visibility])
184 defp exclude_visibility(query, %{exclude_visibilities: visibility})
185 when visibility not in @valid_visibilities do
186 Logger.error("Could not exclude visibility to #{visibility}")
190 defp exclude_visibility(query, _visibility), do: query
192 def for_user(user, opts \\ %{}) do
194 |> for_user_query(opts)
195 |> Pagination.fetch_paginated(opts)
199 Returns notifications for user received since given date.
203 iex> Pleroma.Notification.for_user_since(%Pleroma.User{}, ~N[2019-04-13 11:22:33])
204 [%Pleroma.Notification{}, %Pleroma.Notification{}]
206 iex> Pleroma.Notification.for_user_since(%Pleroma.User{}, ~N[2019-04-15 11:22:33])
209 @spec for_user_since(Pleroma.User.t(), NaiveDateTime.t()) :: [t()]
210 def for_user_since(user, date) do
211 from(n in for_user_query(user),
212 where: n.updated_at > ^date
217 def set_read_up_to(%{id: user_id} = user, id) do
221 where: n.user_id == ^user_id,
223 where: n.seen == false,
224 # Ideally we would preload object and activities here
225 # but Ecto does not support preloads in update_all
229 {:ok, %{ids: {_, notification_ids}}} =
231 |> Multi.update_all(:ids, query, set: [seen: true, updated_at: NaiveDateTime.utc_now()])
232 |> Marker.multi_set_unread_count(user, "notifications")
233 |> Repo.transaction()
236 |> where([n], n.id in ^notification_ids)
237 |> join(:inner, [n], activity in assoc(n, :activity))
238 |> join(:left, [n, a], object in Object,
241 "(?->>'id') = COALESCE((? -> 'object'::text) ->> 'id'::text)",
246 |> preload([n, a, o], activity: {a, object: o})
250 @spec read_one(User.t(), String.t()) ::
251 {:ok, Notification.t()} | {:error, Ecto.Changeset.t()} | nil
252 def read_one(%User{} = user, notification_id) do
253 with {:ok, %Notification{} = notification} <- get(user, notification_id) do
255 |> Multi.update(:update, changeset(notification, %{seen: true}))
256 |> Marker.multi_set_unread_count(user, "notifications")
257 |> Repo.transaction()
259 {:ok, %{update: notification}} -> {:ok, notification}
260 {:error, :update, changeset, _} -> {:error, changeset}
265 def get(%{id: user_id} = _user, id) do
270 join: activity in assoc(n, :activity),
271 preload: [activity: activity]
274 notification = Repo.one(query)
277 %{user_id: ^user_id} ->
281 {:error, "Cannot get notification"}
286 from(n in Notification, where: n.user_id == ^user.id)
290 def destroy_multiple(%{id: user_id} = _user, ids) do
291 from(n in Notification,
293 where: n.user_id == ^user_id
298 def dismiss(%{id: user_id} = _user, id) do
299 notification = Repo.get(Notification, id)
302 %{user_id: ^user_id} ->
303 Repo.delete(notification)
306 {:error, "Cannot dismiss notification"}
310 def create_notifications(%Activity{data: %{"to" => _, "type" => "Create"}} = activity) do
311 object = Object.normalize(activity)
313 unless object && object.data["type"] == "Answer" do
316 |> get_notified_from_activity()
317 |> Enum.map(&create_notification(activity, &1))
325 def create_notifications(%Activity{data: %{"type" => type}} = activity)
326 when type in ["Like", "Announce", "Follow", "Move", "EmojiReact"] do
329 |> get_notified_from_activity()
330 |> Enum.map(&create_notification(activity, &1))
335 def create_notifications(_), do: {:ok, []}
337 # TODO move to sql, too.
338 def create_notification(%Activity{} = activity, %User{} = user) do
339 unless skip?(activity, user) do
340 {:ok, %{notification: notification}} =
342 |> Multi.insert(:notification, %Notification{user_id: user.id, activity: activity})
343 |> Marker.multi_set_unread_count(user, "notifications")
344 |> Repo.transaction()
346 ["user", "user:notification"]
347 |> Streamer.stream(notification)
349 Push.send(notification)
354 def get_notified_from_activity(activity, local_only \\ true)
356 def get_notified_from_activity(%Activity{data: %{"type" => type}} = activity, local_only)
357 when type in ["Create", "Like", "Announce", "Follow", "Move", "EmojiReact"] do
359 |> Utils.maybe_notify_to_recipients(activity)
360 |> Utils.maybe_notify_mentioned_recipients(activity)
361 |> Utils.maybe_notify_subscribers(activity)
362 |> Utils.maybe_notify_followers(activity)
364 |> User.get_users_from_set(local_only)
367 def get_notified_from_activity(_, _local_only), do: []
369 @spec skip?(Activity.t(), User.t()) :: boolean()
370 def skip?(activity, user) do
379 |> Enum.any?(&skip?(&1, activity, user))
382 @spec skip?(atom(), Activity.t(), User.t()) :: boolean()
383 def skip?(:self, activity, user) do
384 activity.data["actor"] == user.ap_id
390 %{notification_settings: %{followers: false}} = user
392 actor = activity.data["actor"]
393 follower = User.get_cached_by_ap_id(actor)
394 User.following?(follower, user)
400 %{notification_settings: %{non_followers: false}} = user
402 actor = activity.data["actor"]
403 follower = User.get_cached_by_ap_id(actor)
404 !User.following?(follower, user)
407 def skip?(:follows, activity, %{notification_settings: %{follows: false}} = user) do
408 actor = activity.data["actor"]
409 followed = User.get_cached_by_ap_id(actor)
410 User.following?(user, followed)
416 %{notification_settings: %{non_follows: false}} = user
418 actor = activity.data["actor"]
419 followed = User.get_cached_by_ap_id(actor)
420 !User.following?(user, followed)
423 def skip?(:recently_followed, %{data: %{"type" => "Follow"}} = activity, user) do
424 actor = activity.data["actor"]
426 Notification.for_user(user)
428 %{activity: %{data: %{"type" => "Follow", "actor" => ^actor}}} -> true
433 def skip?(_, _, _), do: false