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 def for_user_query(user, opts \\ []) do
41 |> where(user_id: ^user.id)
45 "? not in (SELECT ap_id FROM users WHERE deactivated = 'true')",
49 |> join(:inner, [n], activity in assoc(n, :activity))
50 |> join(:left, [n, a], object in Object,
53 "(?->>'id') = COALESCE((? -> 'object'::text) ->> 'id'::text)",
58 |> preload([n, a, o], activity: {a, object: o})
59 |> exclude_muted(user, opts)
60 |> exclude_blocked(user)
61 |> exclude_visibility(opts)
64 defp exclude_blocked(query, user) do
66 |> where([n, a], a.actor not in ^user.blocks)
69 fragment("substring(? from '.*://([^/]*)')", a.actor) not in ^user.domain_blocks
73 defp exclude_muted(query, _, %{with_muted: true}) do
77 defp exclude_muted(query, user, _opts) do
79 |> where([n, a], a.actor not in ^user.muted_notifications)
80 |> join(:left, [n, a], tm in Pleroma.ThreadMute,
81 on: tm.user_id == ^user.id and tm.context == fragment("?->>'context'", a.data)
83 |> where([n, a, o, tm], is_nil(tm.user_id))
86 @valid_visibilities ~w[direct unlisted public private]
88 defp exclude_visibility(query, %{exclude_visibilities: visibility})
89 when is_list(visibility) do
90 if Enum.all?(visibility, &(&1 in @valid_visibilities)) do
95 "activity_visibility(?, ?, ?) = ANY (?)",
103 Logger.error("Could not exclude visibility to #{visibility}")
108 defp exclude_visibility(query, %{exclude_visibilities: visibility})
109 when visibility in @valid_visibilities do
114 "activity_visibility(?, ?, ?) = (?)",
123 defp exclude_visibility(query, %{exclude_visibilities: visibility})
124 when visibility not in @valid_visibilities do
125 Logger.error("Could not exclude visibility to #{visibility}")
129 defp exclude_visibility(query, _visibility), do: query
131 def for_user(user, opts \\ %{}) do
133 |> for_user_query(opts)
134 |> Pagination.fetch_paginated(opts)
138 Returns notifications for user received since given date.
142 iex> Pleroma.Notification.for_user_since(%Pleroma.User{}, ~N[2019-04-13 11:22:33])
143 [%Pleroma.Notification{}, %Pleroma.Notification{}]
145 iex> Pleroma.Notification.for_user_since(%Pleroma.User{}, ~N[2019-04-15 11:22:33])
148 @spec for_user_since(Pleroma.User.t(), NaiveDateTime.t()) :: [t()]
149 def for_user_since(user, date) do
150 from(n in for_user_query(user),
151 where: n.updated_at > ^date
156 def set_read_up_to(%{id: user_id} = user, id) do
160 where: n.user_id == ^user_id,
162 where: n.seen == false,
163 # Ideally we would preload object and activities here
164 # but Ecto does not support preloads in update_all
168 {:ok, %{ids: {_, notification_ids}}} =
170 |> Multi.update_all(:ids, query, set: [seen: true, updated_at: NaiveDateTime.utc_now()])
171 |> Marker.multi_set_unread_count(user, "notifications")
172 |> Repo.transaction()
175 |> where([n], n.id in ^notification_ids)
176 |> join(:inner, [n], activity in assoc(n, :activity))
177 |> join(:left, [n, a], object in Object,
180 "(?->>'id') = COALESCE((? -> 'object'::text) ->> 'id'::text)",
185 |> preload([n, a, o], activity: {a, object: o})
189 @spec read_one(User.t(), String.t()) ::
190 {:ok, Notification.t()} | {:error, Ecto.Changeset.t()} | nil
191 def read_one(%User{} = user, notification_id) do
192 with {:ok, %Notification{} = notification} <- get(user, notification_id) do
194 |> Multi.update(:update, changeset(notification, %{seen: true}))
195 |> Marker.multi_set_unread_count(user, "notifications")
196 |> Repo.transaction()
198 {:ok, %{update: notification}} -> {:ok, notification}
199 {:error, :update, changeset, _} -> {:error, changeset}
204 def get(%{id: user_id} = _user, id) do
209 join: activity in assoc(n, :activity),
210 preload: [activity: activity]
213 notification = Repo.one(query)
216 %{user_id: ^user_id} ->
220 {:error, "Cannot get notification"}
225 from(n in Notification, where: n.user_id == ^user.id)
229 def destroy_multiple(%{id: user_id} = _user, ids) do
230 from(n in Notification,
232 where: n.user_id == ^user_id
237 def dismiss(%{id: user_id} = _user, id) do
238 notification = Repo.get(Notification, id)
241 %{user_id: ^user_id} ->
242 Repo.delete(notification)
245 {:error, "Cannot dismiss notification"}
249 def create_notifications(%Activity{data: %{"to" => _, "type" => "Create"}} = activity) do
250 object = Object.normalize(activity)
252 unless object && object.data["type"] == "Answer" do
255 |> get_notified_from_activity()
256 |> Enum.map(&create_notification(activity, &1))
264 def create_notifications(%Activity{data: %{"to" => _, "type" => type}} = activity)
265 when type in ["Like", "Announce", "Follow"] do
268 |> get_notified_from_activity
269 |> Enum.map(&create_notification(activity, &1))
274 def create_notifications(_), do: {:ok, []}
276 # TODO move to sql, too.
277 def create_notification(%Activity{} = activity, %User{} = user) do
278 unless skip?(activity, user) do
279 {:ok, %{notification: notification}} =
281 |> Multi.insert(:notification, %Notification{user_id: user.id, activity: activity})
282 |> Marker.multi_set_unread_count(user, "notifications")
283 |> Repo.transaction()
285 ["user", "user:notification"]
286 |> Streamer.stream(notification)
288 Push.send(notification)
293 def get_notified_from_activity(activity, local_only \\ true)
295 def get_notified_from_activity(
296 %Activity{data: %{"to" => _, "type" => type} = _data} = activity,
299 when type in ["Create", "Like", "Announce", "Follow"] do
302 |> Utils.maybe_notify_to_recipients(activity)
303 |> Utils.maybe_notify_mentioned_recipients(activity)
304 |> Utils.maybe_notify_subscribers(activity)
307 User.get_users_from_set(recipients, local_only)
310 def get_notified_from_activity(_, _local_only), do: []
312 @spec skip?(Activity.t(), User.t()) :: boolean()
313 def skip?(activity, user) do
322 |> Enum.any?(&skip?(&1, activity, user))
325 @spec skip?(atom(), Activity.t(), User.t()) :: boolean()
326 def skip?(:self, activity, user) do
327 activity.data["actor"] == user.ap_id
333 %{notification_settings: %{"followers" => false}} = user
335 actor = activity.data["actor"]
336 follower = User.get_cached_by_ap_id(actor)
337 User.following?(follower, user)
343 %{notification_settings: %{"non_followers" => false}} = user
345 actor = activity.data["actor"]
346 follower = User.get_cached_by_ap_id(actor)
347 !User.following?(follower, user)
350 def skip?(:follows, activity, %{notification_settings: %{"follows" => false}} = user) do
351 actor = activity.data["actor"]
352 followed = User.get_cached_by_ap_id(actor)
353 User.following?(user, followed)
359 %{notification_settings: %{"non_follows" => false}} = user
361 actor = activity.data["actor"]
362 followed = User.get_cached_by_ap_id(actor)
363 !User.following?(user, followed)
366 def skip?(:recently_followed, %{data: %{"type" => "Follow"}} = activity, user) do
367 actor = activity.data["actor"]
369 Notification.for_user(user)
371 %{activity: %{data: %{"type" => "Follow", "actor" => ^actor}}} -> true
376 def skip?(_, _, _), do: false