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
18 defp restrict_max(query, _), do: query
20 defp restrict_since(query, %{"since_id" => since_id}) do
21 from activity in query, where: activity.id > ^since_id
23 defp restrict_since(query, _), do: query
25 def for_user(user, opts \\ %{}) do
26 query = from n in Notification,
27 where: n.user_id == ^user.id,
28 order_by: [desc: n.id],
33 |> restrict_since(opts)
39 def get(%{id: user_id} = _user, id) do
40 query = from n in Notification,
44 notification = Repo.one(query)
46 %{user_id: ^user_id} ->
49 {:error, "Cannot get notification"}
54 query = from n in Notification,
55 where: n.user_id == ^user.id
57 Repo.delete_all(query)
60 def dismiss(%{id: user_id} = _user, id) do
61 notification = Repo.get(Notification, id)
63 %{user_id: ^user_id} ->
64 Repo.delete(notification)
66 {:error, "Cannot dismiss notification"}
70 def create_notifications(%Activity{id: _, data: %{"to" => _, "type" => type}} = activity) when type in ["Create", "Like", "Announce", "Follow"] do
71 users = User.get_notified_from_activity(activity)
73 notifications = Enum.map(users, fn (user) -> create_notification(activity, user) end)
76 def create_notifications(_), do: {:ok, []}
78 # TODO move to sql, too.
79 def create_notification(%Activity{} = activity, %User{} = user) do
80 unless User.blocks?(user, %{ap_id: activity.data["actor"]}) do
81 notification = %Notification{user_id: user.id, activity: activity}
82 {:ok, notification} = Repo.insert(notification)
83 Pleroma.Web.Streamer.stream("user", notification)