1 defmodule Pleroma.Notification do
3 alias Pleroma.{User, Activity, Notification, Repo}
6 schema "notifications" do
7 field(:seen, :boolean, default: false)
8 belongs_to(:user, Pleroma.User)
9 belongs_to(:activity, Pleroma.Activity)
14 # TODO: Make generic and unify (see activity_pub.ex)
15 defp restrict_max(query, %{"max_id" => max_id}) do
16 from(activity in query, where: activity.id < ^max_id)
19 defp restrict_max(query, _), do: query
21 defp restrict_since(query, %{"since_id" => since_id}) do
22 from(activity in query, where: activity.id > ^since_id)
25 defp restrict_since(query, _), do: query
27 def for_user(user, opts \\ %{}) do
31 where: n.user_id == ^user.id,
32 order_by: [desc: n.id],
39 |> restrict_since(opts)
45 def set_read_up_to(%{id: user_id} = _user, id) do
49 where: n.user_id == ^user_id,
56 Repo.update_all(query, [])
59 def get(%{id: user_id} = _user, id) do
67 notification = Repo.one(query)
70 %{user_id: ^user_id} ->
74 {:error, "Cannot get notification"}
79 query = from(n in Notification, where: n.user_id == ^user.id)
81 Repo.delete_all(query)
84 def dismiss(%{id: user_id} = _user, id) do
85 notification = Repo.get(Notification, id)
88 %{user_id: ^user_id} ->
89 Repo.delete(notification)
92 {:error, "Cannot dismiss notification"}
96 def create_notifications(%Activity{id: _, data: %{"to" => _, "type" => type}} = activity)
97 when type in ["Create", "Like", "Announce", "Follow"] do
98 users = User.get_notified_from_activity(activity)
100 notifications = Enum.map(users, fn user -> create_notification(activity, user) end)
104 def create_notifications(_), do: {:ok, []}
106 # TODO move to sql, too.
107 def create_notification(%Activity{} = activity, %User{} = user) do
108 unless User.blocks?(user, %{ap_id: activity.data["actor"]}) or
109 user.ap_id == activity.data["actor"] do
110 notification = %Notification{user_id: user.id, activity: activity}
111 {:ok, notification} = Repo.insert(notification)
112 Pleroma.Web.Streamer.stream("user", notification)