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 get(%{id: user_id} = _user, id) do
53 notification = Repo.one(query)
56 %{user_id: ^user_id} ->
60 {:error, "Cannot get notification"}
65 query = from(n in Notification, where: n.user_id == ^user.id)
67 Repo.delete_all(query)
70 def dismiss(%{id: user_id} = _user, id) do
71 notification = Repo.get(Notification, id)
74 %{user_id: ^user_id} ->
75 Repo.delete(notification)
78 {:error, "Cannot dismiss notification"}
82 def create_notifications(%Activity{id: _, data: %{"to" => _, "type" => type}} = activity)
83 when type in ["Create", "Like", "Announce", "Follow"] do
84 users = User.get_notified_from_activity(activity)
86 notifications = Enum.map(users, fn user -> create_notification(activity, user) end)
90 def create_notifications(_), do: {:ok, []}
92 # TODO move to sql, too.
93 def create_notification(%Activity{} = activity, %User{} = user) do
94 unless User.blocks?(user, %{ap_id: activity.data["actor"]}) or
95 user.ap_id == activity.data["actor"] do
96 notification = %Notification{user_id: user.id, activity: activity}
97 {:ok, notification} = Repo.insert(notification)
98 Pleroma.Web.Streamer.stream("user", notification)