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
9 alias Pleroma.Notification
10 alias Pleroma.Pagination
13 alias Pleroma.Web.CommonAPI
14 alias Pleroma.Web.CommonAPI.Utils
19 schema "notifications" do
20 field(:seen, :boolean, default: false)
21 belongs_to(:user, User, type: Pleroma.FlakeId)
22 belongs_to(:activity, Activity, type: Pleroma.FlakeId)
27 def changeset(%Notification{} = notification, attrs) do
29 |> cast(attrs, [:seen])
32 def for_user_query(user) do
34 |> where(user_id: ^user.id)
35 |> join(:inner, [n], activity in assoc(n, :activity))
39 def for_user(user, opts \\ %{}) do
42 |> Pagination.fetch_paginated(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 read_one(%User{} = user, notification_id) do
60 with {:ok, %Notification{} = notification} <- get(user, notification_id) do
62 |> changeset(%{seen: true})
67 def get(%{id: user_id} = _user, id) do
72 join: activity in assoc(n, :activity),
73 preload: [activity: activity]
76 notification = Repo.one(query)
79 %{user_id: ^user_id} ->
83 {:error, "Cannot get notification"}
88 from(n in Notification, where: n.user_id == ^user.id)
92 def dismiss(%{id: user_id} = _user, id) do
93 notification = Repo.get(Notification, id)
96 %{user_id: ^user_id} ->
97 Repo.delete(notification)
100 {:error, "Cannot dismiss notification"}
104 def create_notifications(%Activity{data: %{"to" => _, "type" => type}} = activity)
105 when type in ["Create", "Like", "Announce", "Follow"] do
106 users = get_notified_from_activity(activity)
108 notifications = Enum.map(users, fn user -> create_notification(activity, user) end)
112 def create_notifications(_), do: {:ok, []}
114 # TODO move to sql, too.
115 def create_notification(%Activity{} = activity, %User{} = user) do
116 unless User.blocks?(user, %{ap_id: activity.data["actor"]}) or
117 CommonAPI.thread_muted?(user, activity) or user.ap_id == activity.data["actor"] or
118 (activity.data["type"] == "Follow" and
119 Enum.any?(Notification.for_user(user), fn notif ->
120 notif.activity.data["type"] == "Follow" and
121 notif.activity.data["actor"] == activity.data["actor"]
123 notification = %Notification{user_id: user.id, activity: activity}
124 {:ok, notification} = Repo.insert(notification)
125 Pleroma.Web.Streamer.stream("user", notification)
126 Pleroma.Web.Push.send(notification)
131 def get_notified_from_activity(activity, local_only \\ true)
133 def get_notified_from_activity(
134 %Activity{data: %{"to" => _, "type" => type} = _data} = activity,
137 when type in ["Create", "Like", "Announce", "Follow"] do
140 |> Utils.maybe_notify_to_recipients(activity)
141 |> Utils.maybe_notify_mentioned_recipients(activity)
144 User.get_users_from_set(recipients, local_only)
147 def get_notified_from_activity(_, _local_only), do: []