Merge branch 'feature/unrepeats' 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
19 defp restrict_max(query, _), do: query
20
21 defp restrict_since(query, %{"since_id" => since_id}) do
22 from(activity in query, where: activity.id > ^since_id)
23 end
24
25 defp restrict_since(query, _), do: query
26
27 def for_user(user, opts \\ %{}) do
28 query =
29 from(
30 n in Notification,
31 where: n.user_id == ^user.id,
32 order_by: [desc: n.id],
33 preload: [:activity],
34 limit: 20
35 )
36
37 query =
38 query
39 |> restrict_since(opts)
40 |> restrict_max(opts)
41
42 Repo.all(query)
43 end
44
45 def get(%{id: user_id} = _user, id) do
46 query =
47 from(
48 n in Notification,
49 where: n.id == ^id,
50 preload: [:activity]
51 )
52
53 notification = Repo.one(query)
54
55 case notification do
56 %{user_id: ^user_id} ->
57 {:ok, notification}
58
59 _ ->
60 {:error, "Cannot get notification"}
61 end
62 end
63
64 def clear(user) do
65 query = from(n in Notification, where: n.user_id == ^user.id)
66
67 Repo.delete_all(query)
68 end
69
70 def dismiss(%{id: user_id} = _user, id) do
71 notification = Repo.get(Notification, id)
72
73 case notification do
74 %{user_id: ^user_id} ->
75 Repo.delete(notification)
76
77 _ ->
78 {:error, "Cannot dismiss notification"}
79 end
80 end
81
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)
85
86 notifications = Enum.map(users, fn user -> create_notification(activity, user) end)
87 {:ok, notifications}
88 end
89
90 def create_notifications(_), do: {:ok, []}
91
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)
99 notification
100 end
101 end
102 end