Merge branch '459_fix_user_profile_crash' into 'develop'
[akkoma] / lib / pleroma / web / streamer.ex
1 defmodule Pleroma.Web.Streamer do
2 use GenServer
3 require Logger
4 alias Pleroma.{User, Notification, Activity, Object, Repo}
5 alias Pleroma.Web.ActivityPub.ActivityPub
6
7 @keepalive_interval :timer.seconds(30)
8
9 def start_link do
10 GenServer.start_link(__MODULE__, %{}, name: __MODULE__)
11 end
12
13 def add_socket(topic, socket) do
14 GenServer.cast(__MODULE__, %{action: :add, socket: socket, topic: topic})
15 end
16
17 def remove_socket(topic, socket) do
18 GenServer.cast(__MODULE__, %{action: :remove, socket: socket, topic: topic})
19 end
20
21 def stream(topic, item) do
22 GenServer.cast(__MODULE__, %{action: :stream, topic: topic, item: item})
23 end
24
25 def init(args) do
26 spawn(fn ->
27 # 30 seconds
28 Process.sleep(@keepalive_interval)
29 GenServer.cast(__MODULE__, %{action: :ping})
30 end)
31
32 {:ok, args}
33 end
34
35 def handle_cast(%{action: :ping}, topics) do
36 Map.values(topics)
37 |> List.flatten()
38 |> Enum.each(fn socket ->
39 Logger.debug("Sending keepalive ping")
40 send(socket.transport_pid, {:text, ""})
41 end)
42
43 spawn(fn ->
44 # 30 seconds
45 Process.sleep(@keepalive_interval)
46 GenServer.cast(__MODULE__, %{action: :ping})
47 end)
48
49 {:noreply, topics}
50 end
51
52 def handle_cast(%{action: :stream, topic: "direct", item: item}, topics) do
53 recipient_topics =
54 User.get_recipients_from_activity(item)
55 |> Enum.map(fn %{id: id} -> "direct:#{id}" end)
56
57 Enum.each(recipient_topics || [], fn user_topic ->
58 Logger.debug("Trying to push direct message to #{user_topic}\n\n")
59 push_to_socket(topics, user_topic, item)
60 end)
61
62 {:noreply, topics}
63 end
64
65 def handle_cast(%{action: :stream, topic: "list", item: item}, topics) do
66 # filter the recipient list if the activity is not public, see #270.
67 recipient_lists =
68 case ActivityPub.is_public?(item) do
69 true ->
70 Pleroma.List.get_lists_from_activity(item)
71
72 _ ->
73 Pleroma.List.get_lists_from_activity(item)
74 |> Enum.filter(fn list ->
75 owner = Repo.get(User, list.user_id)
76
77 ActivityPub.visible_for_user?(item, owner)
78 end)
79 end
80
81 recipient_topics =
82 recipient_lists
83 |> Enum.map(fn %{id: id} -> "list:#{id}" end)
84
85 Enum.each(recipient_topics || [], fn list_topic ->
86 Logger.debug("Trying to push message to #{list_topic}\n\n")
87 push_to_socket(topics, list_topic, item)
88 end)
89
90 {:noreply, topics}
91 end
92
93 def handle_cast(%{action: :stream, topic: "user", item: %Notification{} = item}, topics) do
94 topic = "user:#{item.user_id}"
95
96 Enum.each(topics[topic] || [], fn socket ->
97 json =
98 %{
99 event: "notification",
100 payload:
101 Pleroma.Web.MastodonAPI.MastodonAPIController.render_notification(
102 socket.assigns["user"],
103 item
104 )
105 |> Jason.encode!()
106 }
107 |> Jason.encode!()
108
109 send(socket.transport_pid, {:text, json})
110 end)
111
112 {:noreply, topics}
113 end
114
115 def handle_cast(%{action: :stream, topic: "user", item: item}, topics) do
116 Logger.debug("Trying to push to users")
117
118 recipient_topics =
119 User.get_recipients_from_activity(item)
120 |> Enum.map(fn %{id: id} -> "user:#{id}" end)
121
122 Enum.each(recipient_topics, fn topic ->
123 push_to_socket(topics, topic, item)
124 end)
125
126 {:noreply, topics}
127 end
128
129 def handle_cast(%{action: :stream, topic: topic, item: item}, topics) do
130 Logger.debug("Trying to push to #{topic}")
131 Logger.debug("Pushing item to #{topic}")
132 push_to_socket(topics, topic, item)
133 {:noreply, topics}
134 end
135
136 def handle_cast(%{action: :add, topic: topic, socket: socket}, sockets) do
137 topic = internal_topic(topic, socket)
138 sockets_for_topic = sockets[topic] || []
139 sockets_for_topic = Enum.uniq([socket | sockets_for_topic])
140 sockets = Map.put(sockets, topic, sockets_for_topic)
141 Logger.debug("Got new conn for #{topic}")
142 {:noreply, sockets}
143 end
144
145 def handle_cast(%{action: :remove, topic: topic, socket: socket}, sockets) do
146 topic = internal_topic(topic, socket)
147 sockets_for_topic = sockets[topic] || []
148 sockets_for_topic = List.delete(sockets_for_topic, socket)
149 sockets = Map.put(sockets, topic, sockets_for_topic)
150 Logger.debug("Removed conn for #{topic}")
151 {:noreply, sockets}
152 end
153
154 def handle_cast(m, state) do
155 Logger.info("Unknown: #{inspect(m)}, #{inspect(state)}")
156 {:noreply, state}
157 end
158
159 defp represent_update(%Activity{} = activity, %User{} = user) do
160 %{
161 event: "update",
162 payload:
163 Pleroma.Web.MastodonAPI.StatusView.render(
164 "status.json",
165 activity: activity,
166 for: user
167 )
168 |> Jason.encode!()
169 }
170 |> Jason.encode!()
171 end
172
173 defp represent_update(%Activity{} = activity) do
174 %{
175 event: "update",
176 payload:
177 Pleroma.Web.MastodonAPI.StatusView.render(
178 "status.json",
179 activity: activity
180 )
181 |> Jason.encode!()
182 }
183 |> Jason.encode!()
184 end
185
186 def push_to_socket(topics, topic, %Activity{data: %{"type" => "Announce"}} = item) do
187 Enum.each(topics[topic] || [], fn socket ->
188 # Get the current user so we have up-to-date blocks etc.
189 if socket.assigns[:user] do
190 user = User.get_cached_by_ap_id(socket.assigns[:user].ap_id)
191 blocks = user.info.blocks || []
192
193 parent = Object.normalize(item.data["object"])
194
195 unless is_nil(parent) or item.actor in blocks or parent.data["actor"] in blocks do
196 send(socket.transport_pid, {:text, represent_update(item, user)})
197 end
198 else
199 send(socket.transport_pid, {:text, represent_update(item)})
200 end
201 end)
202 end
203
204 def push_to_socket(topics, topic, item) do
205 Enum.each(topics[topic] || [], fn socket ->
206 # Get the current user so we have up-to-date blocks etc.
207 if socket.assigns[:user] do
208 user = User.get_cached_by_ap_id(socket.assigns[:user].ap_id)
209 blocks = user.info.blocks || []
210
211 unless item.actor in blocks do
212 send(socket.transport_pid, {:text, represent_update(item, user)})
213 end
214 else
215 send(socket.transport_pid, {:text, represent_update(item)})
216 end
217 end)
218 end
219
220 defp internal_topic(topic, socket) when topic in ~w[user direct] do
221 "#{topic}:#{socket.assigns[:user].id}"
222 end
223
224 defp internal_topic(topic, _), do: topic
225 end