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
7 alias Pleroma.{User, Activity, Notification, Repo}
8 alias Pleroma.Web.CommonAPI.Utils
11 schema "notifications" do
12 field(:seen, :boolean, default: false)
13 belongs_to(:user, Pleroma.User)
14 belongs_to(:activity, Pleroma.Activity)
19 # TODO: Make generic and unify (see activity_pub.ex)
20 defp restrict_max(query, %{"max_id" => max_id}) do
21 from(activity in query, where: activity.id < ^max_id)
24 defp restrict_max(query, _), do: query
26 defp restrict_since(query, %{"since_id" => since_id}) do
27 from(activity in query, where: activity.id > ^since_id)
30 defp restrict_since(query, _), do: query
32 def for_user(user, opts \\ %{}) do
36 where: n.user_id == ^user.id,
37 order_by: [desc: n.id],
44 |> restrict_since(opts)
50 def set_read_up_to(%{id: user_id} = _user, id) do
54 where: n.user_id == ^user_id,
61 Repo.update_all(query, [])
64 def get(%{id: user_id} = _user, id) do
72 notification = Repo.one(query)
75 %{user_id: ^user_id} ->
79 {:error, "Cannot get notification"}
84 from(n in Notification, where: n.user_id == ^user.id)
88 def dismiss(%{id: user_id} = _user, id) do
89 notification = Repo.get(Notification, id)
92 %{user_id: ^user_id} ->
93 Repo.delete(notification)
96 {:error, "Cannot dismiss notification"}
100 def create_notifications(%Activity{id: _, data: %{"to" => _, "type" => type}} = activity)
101 when type in ["Create", "Like", "Announce", "Follow"] do
102 users = get_notified_from_activity(activity)
104 notifications = Enum.map(users, fn user -> create_notification(activity, user) end)
108 def create_notifications(_), do: {:ok, []}
110 # TODO move to sql, too.
111 def create_notification(%Activity{} = activity, %User{} = user) do
112 unless User.blocks?(user, %{ap_id: activity.data["actor"]}) or
113 user.ap_id == activity.data["actor"] or
114 (activity.data["type"] == "Follow" and
115 Enum.any?(Notification.for_user(user), fn notif ->
116 notif.activity.data["type"] == "Follow" and
117 notif.activity.data["actor"] == activity.data["actor"]
119 notification = %Notification{user_id: user.id, activity: activity}
120 {:ok, notification} = Repo.insert(notification)
121 Pleroma.Web.Streamer.stream("user", notification)
122 Pleroma.Web.Push.send(notification)
127 def get_notified_from_activity(activity, local_only \\ true)
129 def get_notified_from_activity(
130 %Activity{data: %{"to" => _, "type" => type} = _data} = activity,
133 when type in ["Create", "Like", "Announce", "Follow"] do
136 |> Utils.maybe_notify_to_recipients(activity)
137 |> Utils.maybe_notify_mentioned_recipients(activity)
140 User.get_users_from_set(recipients, local_only)
143 def get_notified_from_activity(_, _local_only), do: []