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 schema "notifications" do
27 field(:seen, :boolean, default: false)
28 belongs_to(:user, User, type: FlakeId.Ecto.CompatType)
29 belongs_to(:activity, Activity, type: FlakeId.Ecto.CompatType)
34 def changeset(%Notification{} = notification, attrs) do
36 |> cast(attrs, [:seen])
39 @spec notifications_info_query(User.t()) :: Ecto.Queryable.t()
40 def notifications_info_query(user) do
41 from(q in Pleroma.Notification,
42 where: q.user_id == ^user.id,
44 unread_count: fragment("SUM( CASE WHEN seen = false THEN 1 ELSE 0 END )"),
46 type(fragment("MAX( CASE WHEN seen = true THEN id ELSE null END )"), :string)
51 def for_user_query(user, opts \\ []) do
53 |> where(user_id: ^user.id)
57 "? not in (SELECT ap_id FROM users WHERE deactivated = 'true')",
61 |> join(:inner, [n], activity in assoc(n, :activity))
62 |> join(:left, [n, a], object in Object,
65 "(?->>'id') = COALESCE((? -> 'object'::text) ->> 'id'::text)",
70 |> preload([n, a, o], activity: {a, object: o})
71 |> exclude_muted(user, opts)
72 |> exclude_blocked(user)
73 |> exclude_visibility(opts)
76 defp exclude_blocked(query, user) do
78 |> where([n, a], a.actor not in ^user.blocks)
81 fragment("substring(? from '.*://([^/]*)')", a.actor) not in ^user.domain_blocks
85 defp exclude_muted(query, _, %{with_muted: true}) do
89 defp exclude_muted(query, user, _opts) do
91 |> where([n, a], a.actor not in ^user.muted_notifications)
92 |> join(:left, [n, a], tm in Pleroma.ThreadMute,
93 on: tm.user_id == ^user.id and tm.context == fragment("?->>'context'", a.data)
95 |> where([n, a, o, tm], is_nil(tm.user_id))
98 @valid_visibilities ~w[direct unlisted public private]
100 defp exclude_visibility(query, %{exclude_visibilities: visibility})
101 when is_list(visibility) do
102 if Enum.all?(visibility, &(&1 in @valid_visibilities)) do
107 "activity_visibility(?, ?, ?) = ANY (?)",
115 Logger.error("Could not exclude visibility to #{visibility}")
120 defp exclude_visibility(query, %{exclude_visibilities: visibility})
121 when visibility in @valid_visibilities do
126 "activity_visibility(?, ?, ?) = (?)",
135 defp exclude_visibility(query, %{exclude_visibilities: visibility})
136 when visibility not in @valid_visibilities do
137 Logger.error("Could not exclude visibility to #{visibility}")
141 defp exclude_visibility(query, _visibility), do: query
143 def for_user(user, opts \\ %{}) do
145 |> for_user_query(opts)
146 |> Pagination.fetch_paginated(opts)
150 Returns notifications for user received since given date.
154 iex> Pleroma.Notification.for_user_since(%Pleroma.User{}, ~N[2019-04-13 11:22:33])
155 [%Pleroma.Notification{}, %Pleroma.Notification{}]
157 iex> Pleroma.Notification.for_user_since(%Pleroma.User{}, ~N[2019-04-15 11:22:33])
160 @spec for_user_since(Pleroma.User.t(), NaiveDateTime.t()) :: [t()]
161 def for_user_since(user, date) do
162 from(n in for_user_query(user),
163 where: n.updated_at > ^date
168 def set_read_up_to(%{id: user_id} = user, id) do
172 where: n.user_id == ^user_id,
174 where: n.seen == false,
175 # Ideally we would preload object and activities here
176 # but Ecto does not support preloads in update_all
180 {:ok, %{ids: {_, notification_ids}}} =
182 |> Multi.update_all(:ids, query, set: [seen: true, updated_at: NaiveDateTime.utc_now()])
183 |> Marker.multi_set_unread_count(user, "notifications")
184 |> Repo.transaction()
187 |> where([n], n.id in ^notification_ids)
188 |> join(:inner, [n], activity in assoc(n, :activity))
189 |> join(:left, [n, a], object in Object,
192 "(?->>'id') = COALESCE((? -> 'object'::text) ->> 'id'::text)",
197 |> preload([n, a, o], activity: {a, object: o})
201 @spec read_one(User.t(), String.t()) ::
202 {:ok, Notification.t()} | {:error, Ecto.Changeset.t()} | nil
203 def read_one(%User{} = user, notification_id) do
204 with {:ok, %Notification{} = notification} <- get(user, notification_id) do
206 |> Multi.update(:update, changeset(notification, %{seen: true}))
207 |> Marker.multi_set_unread_count(user, "notifications")
208 |> Repo.transaction()
210 {:ok, %{update: notification}} -> {:ok, notification}
211 {:error, :update, changeset, _} -> {:error, changeset}
216 def get(%{id: user_id} = _user, id) do
221 join: activity in assoc(n, :activity),
222 preload: [activity: activity]
225 notification = Repo.one(query)
228 %{user_id: ^user_id} ->
232 {:error, "Cannot get notification"}
237 from(n in Notification, where: n.user_id == ^user.id)
241 def destroy_multiple(%{id: user_id} = _user, ids) do
242 from(n in Notification,
244 where: n.user_id == ^user_id
249 def dismiss(%{id: user_id} = _user, id) do
250 notification = Repo.get(Notification, id)
253 %{user_id: ^user_id} ->
254 Repo.delete(notification)
257 {:error, "Cannot dismiss notification"}
261 def create_notifications(%Activity{data: %{"to" => _, "type" => "Create"}} = activity) do
262 object = Object.normalize(activity)
264 unless object && object.data["type"] == "Answer" do
267 |> get_notified_from_activity()
268 |> Enum.map(&create_notification(activity, &1))
276 def create_notifications(%Activity{data: %{"to" => _, "type" => type}} = activity)
277 when type in ["Like", "Announce", "Follow"] do
280 |> get_notified_from_activity
281 |> Enum.map(&create_notification(activity, &1))
286 def create_notifications(_), do: {:ok, []}
288 # TODO move to sql, too.
289 def create_notification(%Activity{} = activity, %User{} = user) do
290 unless skip?(activity, user) do
291 {:ok, %{notification: notification}} =
293 |> Multi.insert(:notification, %Notification{user_id: user.id, activity: activity})
294 |> Marker.multi_set_unread_count(user, "notifications")
295 |> Repo.transaction()
297 ["user", "user:notification"]
298 |> Streamer.stream(notification)
300 Push.send(notification)
305 def get_notified_from_activity(activity, local_only \\ true)
307 def get_notified_from_activity(
308 %Activity{data: %{"to" => _, "type" => type} = _data} = activity,
311 when type in ["Create", "Like", "Announce", "Follow"] do
314 |> Utils.maybe_notify_to_recipients(activity)
315 |> Utils.maybe_notify_mentioned_recipients(activity)
316 |> Utils.maybe_notify_subscribers(activity)
319 User.get_users_from_set(recipients, local_only)
322 def get_notified_from_activity(_, _local_only), do: []
324 @spec skip?(Activity.t(), User.t()) :: boolean()
325 def skip?(activity, user) do
334 |> Enum.any?(&skip?(&1, activity, user))
337 @spec skip?(atom(), Activity.t(), User.t()) :: boolean()
338 def skip?(:self, activity, user) do
339 activity.data["actor"] == user.ap_id
345 %{notification_settings: %{"followers" => false}} = user
347 actor = activity.data["actor"]
348 follower = User.get_cached_by_ap_id(actor)
349 User.following?(follower, user)
355 %{notification_settings: %{"non_followers" => false}} = user
357 actor = activity.data["actor"]
358 follower = User.get_cached_by_ap_id(actor)
359 !User.following?(follower, user)
362 def skip?(:follows, activity, %{notification_settings: %{"follows" => false}} = user) do
363 actor = activity.data["actor"]
364 followed = User.get_cached_by_ap_id(actor)
365 User.following?(user, followed)
371 %{notification_settings: %{"non_follows" => false}} = user
373 actor = activity.data["actor"]
374 followed = User.get_cached_by_ap_id(actor)
375 !User.following?(user, followed)
378 def skip?(:recently_followed, %{data: %{"type" => "Follow"}} = activity, user) do
379 actor = activity.data["actor"]
381 Notification.for_user(user)
383 %{activity: %{data: %{"type" => "Follow", "actor" => ^actor}}} -> true
388 def skip?(_, _, _), do: false