Merge branch 'feature/jsonld-context-cleanup' 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 set_read_up_to(%{id: user_id} = _user, id) do
46 query =
47 from(
48 n in Notification,
49 where: n.user_id == ^user_id,
50 where: n.id <= ^id,
51 update: [
52 set: [seen: true]
53 ]
54 )
55
56 Repo.update_all(query, [])
57 end
58
59 def get(%{id: user_id} = _user, id) do
60 query =
61 from(
62 n in Notification,
63 where: n.id == ^id,
64 preload: [:activity]
65 )
66
67 notification = Repo.one(query)
68
69 case notification do
70 %{user_id: ^user_id} ->
71 {:ok, notification}
72
73 _ ->
74 {:error, "Cannot get notification"}
75 end
76 end
77
78 def clear(user) do
79 query = from(n in Notification, where: n.user_id == ^user.id)
80
81 Repo.delete_all(query)
82 end
83
84 def dismiss(%{id: user_id} = _user, id) do
85 notification = Repo.get(Notification, id)
86
87 case notification do
88 %{user_id: ^user_id} ->
89 Repo.delete(notification)
90
91 _ ->
92 {:error, "Cannot dismiss notification"}
93 end
94 end
95
96 def create_notifications(%Activity{id: _, data: %{"to" => _, "type" => type}} = activity)
97 when type in ["Create", "Like", "Announce", "Follow"] do
98 users = User.get_notified_from_activity(activity)
99
100 notifications = Enum.map(users, fn user -> create_notification(activity, user) end)
101 {:ok, notifications}
102 end
103
104 def create_notifications(_), do: {:ok, []}
105
106 # TODO move to sql, too.
107 def create_notification(%Activity{} = activity, %User{} = user) do
108 unless User.blocks?(user, %{ap_id: activity.data["actor"]}) or
109 user.ap_id == activity.data["actor"] do
110 notification = %Notification{user_id: user.id, activity: activity}
111 {:ok, notification} = Repo.insert(notification)
112 Pleroma.Web.Streamer.stream("user", notification)
113 notification
114 end
115 end
116 end