Merge branch 'feature/blocks' into 'develop'
[akkoma] / lib / pleroma / notification.ex
1 defmodule Pleroma.Notification do
2 use Ecto.Schema
3 alias Pleroma.{User, Activity, Notification, Repo}
4 import Ecto.Query
5
6 schema "notifications" do
7 field :seen, :boolean, default: false
8 belongs_to :user, Pleroma.User
9 belongs_to :activity, Pleroma.Activity
10
11 timestamps()
12 end
13
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
17 end
18 defp restrict_max(query, _), do: query
19
20 defp restrict_since(query, %{"since_id" => since_id}) do
21 from activity in query, where: activity.id > ^since_id
22 end
23 defp restrict_since(query, _), do: query
24
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],
29 preload: [:activity],
30 limit: 20
31
32 query = query
33 |> restrict_since(opts)
34 |> restrict_max(opts)
35
36 Repo.all(query)
37 end
38
39 def create_notifications(%Activity{id: id, data: %{"to" => to, "type" => type}} = activity) when type in ["Create", "Like", "Announce", "Follow"] do
40 users = User.get_notified_from_activity(activity)
41
42 notifications = Enum.map(users, fn (user) -> create_notification(activity, user) end)
43 {:ok, notifications}
44 end
45 def create_notifications(_), do: {:ok, []}
46
47 # TODO move to sql, too.
48 def create_notification(%Activity{} = activity, %User{} = user) do
49 unless User.blocks?(user, %{ap_id: activity.data["actor"]}) do
50 notification = %Notification{user_id: user.id, activity_id: activity.id}
51 {:ok, notification} = Repo.insert(notification)
52 notification
53 end
54 end
55 end
56