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 timeline: "notifications",
45 user_id: type(^user.id, :string),
46 unread_count: fragment("SUM( CASE WHEN seen = false THEN 1 ELSE 0 END )"),
48 type(fragment("MAX( CASE WHEN seen = true THEN id ELSE null END )"), :string)
53 def for_user_query(user, opts \\ []) do
55 |> where(user_id: ^user.id)
59 "? not in (SELECT ap_id FROM users WHERE deactivated = 'true')",
63 |> join(:inner, [n], activity in assoc(n, :activity))
64 |> join(:left, [n, a], object in Object,
67 "(?->>'id') = COALESCE((? -> 'object'::text) ->> 'id'::text)",
72 |> preload([n, a, o], activity: {a, object: o})
73 |> exclude_muted(user, opts)
74 |> exclude_blocked(user)
75 |> exclude_visibility(opts)
78 defp exclude_blocked(query, user) do
80 |> where([n, a], a.actor not in ^user.blocks)
83 fragment("substring(? from '.*://([^/]*)')", a.actor) not in ^user.domain_blocks
87 defp exclude_muted(query, _, %{with_muted: true}) do
91 defp exclude_muted(query, user, _opts) do
93 |> where([n, a], a.actor not in ^user.muted_notifications)
94 |> join(:left, [n, a], tm in Pleroma.ThreadMute,
95 on: tm.user_id == ^user.id and tm.context == fragment("?->>'context'", a.data)
97 |> where([n, a, o, tm], is_nil(tm.user_id))
100 @valid_visibilities ~w[direct unlisted public private]
102 defp exclude_visibility(query, %{exclude_visibilities: visibility})
103 when is_list(visibility) do
104 if Enum.all?(visibility, &(&1 in @valid_visibilities)) do
109 "activity_visibility(?, ?, ?) = ANY (?)",
117 Logger.error("Could not exclude visibility to #{visibility}")
122 defp exclude_visibility(query, %{exclude_visibilities: visibility})
123 when visibility in @valid_visibilities do
128 "activity_visibility(?, ?, ?) = (?)",
137 defp exclude_visibility(query, %{exclude_visibilities: visibility})
138 when visibility not in @valid_visibilities do
139 Logger.error("Could not exclude visibility to #{visibility}")
143 defp exclude_visibility(query, _visibility), do: query
145 def for_user(user, opts \\ %{}) do
147 |> for_user_query(opts)
148 |> Pagination.fetch_paginated(opts)
152 Returns notifications for user received since given date.
156 iex> Pleroma.Notification.for_user_since(%Pleroma.User{}, ~N[2019-04-13 11:22:33])
157 [%Pleroma.Notification{}, %Pleroma.Notification{}]
159 iex> Pleroma.Notification.for_user_since(%Pleroma.User{}, ~N[2019-04-15 11:22:33])
162 @spec for_user_since(Pleroma.User.t(), NaiveDateTime.t()) :: [t()]
163 def for_user_since(user, date) do
164 from(n in for_user_query(user),
165 where: n.updated_at > ^date
170 def set_read_up_to(%{id: user_id} = user, id) do
174 where: n.user_id == ^user_id,
176 where: n.seen == false,
177 # Ideally we would preload object and activities here
178 # but Ecto does not support preloads in update_all
182 {:ok, %{ids: {_, notification_ids}}} =
184 |> Multi.update_all(:ids, query, set: [seen: true, updated_at: NaiveDateTime.utc_now()])
185 |> Marker.multi_set_unread_count(user, "notifications")
186 |> Repo.transaction()
189 |> where([n], n.id in ^notification_ids)
190 |> join(:inner, [n], activity in assoc(n, :activity))
191 |> join(:left, [n, a], object in Object,
194 "(?->>'id') = COALESCE((? -> 'object'::text) ->> 'id'::text)",
199 |> preload([n, a, o], activity: {a, object: o})
203 @spec read_one(User.t(), String.t()) ::
204 {:ok, Notification.t()} | {:error, Ecto.Changeset.t()} | nil
205 def read_one(%User{} = user, notification_id) do
206 with {:ok, %Notification{} = notification} <- get(user, notification_id) do
208 |> Multi.update(:update, changeset(notification, %{seen: true}))
209 |> Marker.multi_set_unread_count(user, "notifications")
210 |> Repo.transaction()
212 {:ok, %{update: notification}} -> {:ok, notification}
213 {:error, :update, changeset, _} -> {:error, changeset}
218 def get(%{id: user_id} = _user, id) do
223 join: activity in assoc(n, :activity),
224 preload: [activity: activity]
227 notification = Repo.one(query)
230 %{user_id: ^user_id} ->
234 {:error, "Cannot get notification"}
239 from(n in Notification, where: n.user_id == ^user.id)
243 def destroy_multiple(%{id: user_id} = _user, ids) do
244 from(n in Notification,
246 where: n.user_id == ^user_id
251 def dismiss(%{id: user_id} = _user, id) do
252 notification = Repo.get(Notification, id)
255 %{user_id: ^user_id} ->
256 Repo.delete(notification)
259 {:error, "Cannot dismiss notification"}
263 def create_notifications(%Activity{data: %{"to" => _, "type" => "Create"}} = activity) do
264 object = Object.normalize(activity)
266 unless object && object.data["type"] == "Answer" do
269 |> get_notified_from_activity()
270 |> Enum.map(&create_notification(activity, &1))
278 def create_notifications(%Activity{data: %{"to" => _, "type" => type}} = activity)
279 when type in ["Like", "Announce", "Follow"] do
282 |> get_notified_from_activity
283 |> Enum.map(&create_notification(activity, &1))
288 def create_notifications(_), do: {:ok, []}
290 # TODO move to sql, too.
291 def create_notification(%Activity{} = activity, %User{} = user) do
292 unless skip?(activity, user) do
293 {:ok, %{notification: notification}} =
295 |> Multi.insert(:notification, %Notification{user_id: user.id, activity: activity})
296 |> Marker.multi_set_unread_count(user, "notifications")
297 |> Repo.transaction()
299 ["user", "user:notification"]
300 |> Streamer.stream(notification)
302 Push.send(notification)
307 def get_notified_from_activity(activity, local_only \\ true)
309 def get_notified_from_activity(
310 %Activity{data: %{"to" => _, "type" => type} = _data} = activity,
313 when type in ["Create", "Like", "Announce", "Follow"] do
316 |> Utils.maybe_notify_to_recipients(activity)
317 |> Utils.maybe_notify_mentioned_recipients(activity)
318 |> Utils.maybe_notify_subscribers(activity)
321 User.get_users_from_set(recipients, local_only)
324 def get_notified_from_activity(_, _local_only), do: []
326 @spec skip?(Activity.t(), User.t()) :: boolean()
327 def skip?(activity, user) do
336 |> Enum.any?(&skip?(&1, activity, user))
339 @spec skip?(atom(), Activity.t(), User.t()) :: boolean()
340 def skip?(:self, activity, user) do
341 activity.data["actor"] == user.ap_id
347 %{notification_settings: %{"followers" => false}} = user
349 actor = activity.data["actor"]
350 follower = User.get_cached_by_ap_id(actor)
351 User.following?(follower, user)
357 %{notification_settings: %{"non_followers" => false}} = user
359 actor = activity.data["actor"]
360 follower = User.get_cached_by_ap_id(actor)
361 !User.following?(follower, user)
364 def skip?(:follows, activity, %{notification_settings: %{"follows" => false}} = user) do
365 actor = activity.data["actor"]
366 followed = User.get_cached_by_ap_id(actor)
367 User.following?(user, followed)
373 %{notification_settings: %{"non_follows" => false}} = user
375 actor = activity.data["actor"]
376 followed = User.get_cached_by_ap_id(actor)
377 !User.following?(user, followed)
380 def skip?(:recently_followed, %{data: %{"type" => "Follow"}} = activity, user) do
381 actor = activity.data["actor"]
383 Notification.for_user(user)
385 %{activity: %{data: %{"type" => "Follow", "actor" => ^actor}}} -> true
390 def skip?(_, _, _), do: false