1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
5 defmodule Pleroma.Notification do
9 alias Pleroma.Notification
11 alias Pleroma.Pagination
14 alias Pleroma.Web.CommonAPI.Utils
15 alias Pleroma.Web.Push
16 alias Pleroma.Web.Streamer
22 @type t :: %__MODULE__{}
24 @include_muted_option :with_muted
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 defp for_user_query_ap_id_opts(user, opts) do
42 if opts[@include_muted_option], do: [], else: [:notification_mute]
44 preloaded_ap_ids = User.outgoing_relations_ap_ids(user, ap_id_relations)
46 exclude_blocked_opts = Map.merge(%{blocked_users_ap_ids: preloaded_ap_ids[:block]}, opts)
48 exclude_notification_muted_opts =
49 Map.merge(%{notification_muted_users_ap_ids: preloaded_ap_ids[:notification_mute]}, opts)
51 {exclude_blocked_opts, exclude_notification_muted_opts}
54 def for_user_query(user, opts \\ %{}) do
55 {exclude_blocked_opts, exclude_notification_muted_opts} =
56 for_user_query_ap_id_opts(user, opts)
59 |> where(user_id: ^user.id)
63 "? not in (SELECT ap_id FROM users WHERE deactivated = 'true')",
67 |> join(:inner, [n], activity in assoc(n, :activity))
68 |> join(:left, [n, a], object in Object,
71 "(?->>'id') = COALESCE((? -> 'object'::text) ->> 'id'::text)",
76 |> preload([n, a, o], activity: {a, object: o})
77 |> exclude_notification_muted(user, exclude_notification_muted_opts)
78 |> exclude_blocked(user, exclude_blocked_opts)
79 |> exclude_visibility(opts)
82 defp exclude_blocked(query, user, opts) do
83 blocked_ap_ids = opts[:blocked_users_ap_ids] || User.blocked_users_ap_ids(user)
86 |> where([n, a], a.actor not in ^blocked_ap_ids)
89 fragment("substring(? from '.*://([^/]*)')", a.actor) not in ^user.domain_blocks
93 defp exclude_notification_muted(query, _, %{@include_muted_option => true}) do
97 defp exclude_notification_muted(query, user, opts) do
98 notification_muted_ap_ids =
99 opts[:notification_muted_users_ap_ids] || User.notification_muted_users_ap_ids(user)
102 |> where([n, a], a.actor not in ^notification_muted_ap_ids)
103 |> join(:left, [n, a], tm in Pleroma.ThreadMute,
104 on: tm.user_id == ^user.id and tm.context == fragment("?->>'context'", a.data)
106 |> where([n, a, o, tm], is_nil(tm.user_id))
109 @valid_visibilities ~w[direct unlisted public private]
111 defp exclude_visibility(query, %{exclude_visibilities: visibility})
112 when is_list(visibility) do
113 if Enum.all?(visibility, &(&1 in @valid_visibilities)) do
115 |> join(:left, [n, a], mutated_activity in Pleroma.Activity,
117 fragment("?->>'context'", a.data) ==
118 fragment("?->>'context'", mutated_activity.data) and
119 fragment("(?->>'type' = 'Like' or ?->>'type' = 'Announce')", a.data, a.data) and
120 fragment("?->>'type'", mutated_activity.data) == "Create",
121 as: :mutated_activity
124 [n, a, mutated_activity: mutated_activity],
127 CASE WHEN (?->>'type') = 'Like' or (?->>'type') = 'Announce'
128 THEN (activity_visibility(?, ?, ?) = ANY (?))
129 ELSE (activity_visibility(?, ?, ?) = ANY (?)) END
133 mutated_activity.actor,
134 mutated_activity.recipients,
135 mutated_activity.data,
144 Logger.error("Could not exclude visibility to #{visibility}")
149 defp exclude_visibility(query, %{exclude_visibilities: visibility})
150 when visibility in @valid_visibilities do
151 exclude_visibility(query, [visibility])
154 defp exclude_visibility(query, %{exclude_visibilities: visibility})
155 when visibility not in @valid_visibilities do
156 Logger.error("Could not exclude visibility to #{visibility}")
160 defp exclude_visibility(query, _visibility), do: query
162 def for_user(user, opts \\ %{}) do
164 |> for_user_query(opts)
165 |> Pagination.fetch_paginated(opts)
169 Returns notifications for user received since given date.
173 iex> Pleroma.Notification.for_user_since(%Pleroma.User{}, ~N[2019-04-13 11:22:33])
174 [%Pleroma.Notification{}, %Pleroma.Notification{}]
176 iex> Pleroma.Notification.for_user_since(%Pleroma.User{}, ~N[2019-04-15 11:22:33])
179 @spec for_user_since(Pleroma.User.t(), NaiveDateTime.t()) :: [t()]
180 def for_user_since(user, date) do
181 from(n in for_user_query(user),
182 where: n.updated_at > ^date
187 def set_read_up_to(%{id: user_id} = _user, id) do
191 where: n.user_id == ^user_id,
193 where: n.seen == false,
197 updated_at: ^NaiveDateTime.utc_now()
200 # Ideally we would preload object and activities here
201 # but Ecto does not support preloads in update_all
205 {_, notification_ids} = Repo.update_all(query, [])
208 |> where([n], n.id in ^notification_ids)
209 |> join(:inner, [n], activity in assoc(n, :activity))
210 |> join(:left, [n, a], object in Object,
213 "(?->>'id') = COALESCE((? -> 'object'::text) ->> 'id'::text)",
218 |> preload([n, a, o], activity: {a, object: o})
222 def read_one(%User{} = user, notification_id) do
223 with {:ok, %Notification{} = notification} <- get(user, notification_id) do
225 |> changeset(%{seen: true})
230 def get(%{id: user_id} = _user, id) do
235 join: activity in assoc(n, :activity),
236 preload: [activity: activity]
239 notification = Repo.one(query)
242 %{user_id: ^user_id} ->
246 {:error, "Cannot get notification"}
251 from(n in Notification, where: n.user_id == ^user.id)
255 def destroy_multiple(%{id: user_id} = _user, ids) do
256 from(n in Notification,
258 where: n.user_id == ^user_id
263 def dismiss(%{id: user_id} = _user, id) do
264 notification = Repo.get(Notification, id)
267 %{user_id: ^user_id} ->
268 Repo.delete(notification)
271 {:error, "Cannot dismiss notification"}
275 def create_notifications(%Activity{data: %{"to" => _, "type" => "Create"}} = activity) do
276 object = Object.normalize(activity)
278 unless object && object.data["type"] == "Answer" do
279 users = get_notified_from_activity(activity)
280 notifications = Enum.map(users, fn user -> create_notification(activity, user) end)
287 def create_notifications(%Activity{data: %{"type" => type}} = activity)
288 when type in ["Like", "Announce", "Follow", "Move", "EmojiReact"] do
291 |> get_notified_from_activity()
292 |> Enum.map(&create_notification(activity, &1))
297 def create_notifications(_), do: {:ok, []}
299 # TODO move to sql, too.
300 def create_notification(%Activity{} = activity, %User{} = user) do
301 unless skip?(activity, user) do
302 notification = %Notification{user_id: user.id, activity: activity}
303 {:ok, notification} = Repo.insert(notification)
305 ["user", "user:notification"]
306 |> Streamer.stream(notification)
308 Push.send(notification)
313 def get_notified_from_activity(activity, local_only \\ true)
315 def get_notified_from_activity(%Activity{data: %{"type" => type}} = activity, local_only)
316 when type in ["Create", "Like", "Announce", "Follow", "Move", "EmojiReact"] do
318 |> Utils.maybe_notify_to_recipients(activity)
319 |> Utils.maybe_notify_mentioned_recipients(activity)
320 |> Utils.maybe_notify_subscribers(activity)
321 |> Utils.maybe_notify_followers(activity)
323 |> User.get_users_from_set(local_only)
326 def get_notified_from_activity(_, _local_only), do: []
328 @spec skip?(Activity.t(), User.t()) :: boolean()
329 def skip?(activity, user) do
338 |> Enum.any?(&skip?(&1, activity, user))
341 @spec skip?(atom(), Activity.t(), User.t()) :: boolean()
342 def skip?(:self, activity, user) do
343 activity.data["actor"] == user.ap_id
349 %{notification_settings: %{followers: false}} = user
351 actor = activity.data["actor"]
352 follower = User.get_cached_by_ap_id(actor)
353 User.following?(follower, user)
359 %{notification_settings: %{non_followers: false}} = user
361 actor = activity.data["actor"]
362 follower = User.get_cached_by_ap_id(actor)
363 !User.following?(follower, user)
366 def skip?(:follows, activity, %{notification_settings: %{follows: false}} = user) do
367 actor = activity.data["actor"]
368 followed = User.get_cached_by_ap_id(actor)
369 User.following?(user, followed)
375 %{notification_settings: %{non_follows: false}} = user
377 actor = activity.data["actor"]
378 followed = User.get_cached_by_ap_id(actor)
379 !User.following?(user, followed)
382 def skip?(:recently_followed, %{data: %{"type" => "Follow"}} = activity, user) do
383 actor = activity.data["actor"]
385 Notification.for_user(user)
387 %{activity: %{data: %{"type" => "Follow", "actor" => ^actor}}} -> true
392 def skip?(_, _, _), do: false