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
148 "activity_visibility(?, ?, ?) = ANY (?)",
156 Logger.error("Could not exclude visibility to #{visibility}")
161 defp exclude_visibility(query, %{exclude_visibilities: visibility})
162 when visibility in @valid_visibilities do
167 "activity_visibility(?, ?, ?) = (?)",
176 defp exclude_visibility(query, %{exclude_visibilities: visibility})
177 when visibility not in @valid_visibilities do
178 Logger.error("Could not exclude visibility to #{visibility}")
182 defp exclude_visibility(query, _visibility), do: query
184 def for_user(user, opts \\ %{}) do
186 |> for_user_query(opts)
187 |> Pagination.fetch_paginated(opts)
191 Returns notifications for user received since given date.
195 iex> Pleroma.Notification.for_user_since(%Pleroma.User{}, ~N[2019-04-13 11:22:33])
196 [%Pleroma.Notification{}, %Pleroma.Notification{}]
198 iex> Pleroma.Notification.for_user_since(%Pleroma.User{}, ~N[2019-04-15 11:22:33])
201 @spec for_user_since(Pleroma.User.t(), NaiveDateTime.t()) :: [t()]
202 def for_user_since(user, date) do
203 from(n in for_user_query(user),
204 where: n.updated_at > ^date
209 def set_read_up_to(%{id: user_id} = user, id) do
213 where: n.user_id == ^user_id,
215 where: n.seen == false,
216 # Ideally we would preload object and activities here
217 # but Ecto does not support preloads in update_all
221 {:ok, %{ids: {_, notification_ids}}} =
223 |> Multi.update_all(:ids, query, set: [seen: true, updated_at: NaiveDateTime.utc_now()])
224 |> Marker.multi_set_unread_count(user, "notifications")
225 |> Repo.transaction()
228 |> where([n], n.id in ^notification_ids)
229 |> join(:inner, [n], activity in assoc(n, :activity))
230 |> join(:left, [n, a], object in Object,
233 "(?->>'id') = COALESCE((? -> 'object'::text) ->> 'id'::text)",
238 |> preload([n, a, o], activity: {a, object: o})
242 @spec read_one(User.t(), String.t()) ::
243 {:ok, Notification.t()} | {:error, Ecto.Changeset.t()} | nil
244 def read_one(%User{} = user, notification_id) do
245 with {:ok, %Notification{} = notification} <- get(user, notification_id) do
247 |> Multi.update(:update, changeset(notification, %{seen: true}))
248 |> Marker.multi_set_unread_count(user, "notifications")
249 |> Repo.transaction()
251 {:ok, %{update: notification}} -> {:ok, notification}
252 {:error, :update, changeset, _} -> {:error, changeset}
257 def get(%{id: user_id} = _user, id) do
262 join: activity in assoc(n, :activity),
263 preload: [activity: activity]
266 notification = Repo.one(query)
269 %{user_id: ^user_id} ->
273 {:error, "Cannot get notification"}
278 from(n in Notification, where: n.user_id == ^user.id)
282 def destroy_multiple(%{id: user_id} = _user, ids) do
283 from(n in Notification,
285 where: n.user_id == ^user_id
290 def dismiss(%{id: user_id} = _user, id) do
291 notification = Repo.get(Notification, id)
294 %{user_id: ^user_id} ->
295 Repo.delete(notification)
298 {:error, "Cannot dismiss notification"}
302 def create_notifications(%Activity{data: %{"to" => _, "type" => "Create"}} = activity) do
303 object = Object.normalize(activity)
305 unless object && object.data["type"] == "Answer" do
308 |> get_notified_from_activity()
309 |> Enum.map(&create_notification(activity, &1))
317 def create_notifications(%Activity{data: %{"type" => type}} = activity)
318 when type in ["Like", "Announce", "Follow", "Move"] do
321 |> get_notified_from_activity()
322 |> Enum.map(&create_notification(activity, &1))
327 def create_notifications(_), do: {:ok, []}
329 # TODO move to sql, too.
330 def create_notification(%Activity{} = activity, %User{} = user) do
331 unless skip?(activity, user) do
332 {:ok, %{notification: notification}} =
334 |> Multi.insert(:notification, %Notification{user_id: user.id, activity: activity})
335 |> Marker.multi_set_unread_count(user, "notifications")
336 |> Repo.transaction()
338 ["user", "user:notification"]
339 |> Streamer.stream(notification)
341 Push.send(notification)
346 def get_notified_from_activity(activity, local_only \\ true)
348 def get_notified_from_activity(%Activity{data: %{"type" => type}} = activity, local_only)
349 when type in ["Create", "Like", "Announce", "Follow", "Move"] do
351 |> Utils.maybe_notify_to_recipients(activity)
352 |> Utils.maybe_notify_mentioned_recipients(activity)
353 |> Utils.maybe_notify_subscribers(activity)
354 |> Utils.maybe_notify_followers(activity)
356 |> User.get_users_from_set(local_only)
359 def get_notified_from_activity(_, _local_only), do: []
361 @spec skip?(Activity.t(), User.t()) :: boolean()
362 def skip?(activity, user) do
371 |> Enum.any?(&skip?(&1, activity, user))
374 @spec skip?(atom(), Activity.t(), User.t()) :: boolean()
375 def skip?(:self, activity, user) do
376 activity.data["actor"] == user.ap_id
382 %{notification_settings: %{"followers" => false}} = user
384 actor = activity.data["actor"]
385 follower = User.get_cached_by_ap_id(actor)
386 User.following?(follower, user)
392 %{notification_settings: %{"non_followers" => false}} = user
394 actor = activity.data["actor"]
395 follower = User.get_cached_by_ap_id(actor)
396 !User.following?(follower, user)
399 def skip?(:follows, activity, %{notification_settings: %{"follows" => false}} = user) do
400 actor = activity.data["actor"]
401 followed = User.get_cached_by_ap_id(actor)
402 User.following?(user, followed)
408 %{notification_settings: %{"non_follows" => false}} = user
410 actor = activity.data["actor"]
411 followed = User.get_cached_by_ap_id(actor)
412 !User.following?(user, followed)
415 def skip?(:recently_followed, %{data: %{"type" => "Follow"}} = activity, user) do
416 actor = activity.data["actor"]
418 Notification.for_user(user)
420 %{activity: %{data: %{"type" => "Follow", "actor" => ^actor}}} -> true
425 def skip?(_, _, _), do: false