1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
5 defmodule Pleroma.Web.Streamer do
9 alias Pleroma.Chat.MessageReference
11 alias Pleroma.Conversation.Participation
12 alias Pleroma.Notification
15 alias Pleroma.Web.ActivityPub.ActivityPub
16 alias Pleroma.Web.ActivityPub.Visibility
17 alias Pleroma.Web.CommonAPI
18 alias Pleroma.Web.OAuth.Token
19 alias Pleroma.Web.Plugs.OAuthScopesPlug
20 alias Pleroma.Web.StreamerView
23 @registry Pleroma.Web.StreamerRegistry
25 def registry, do: @registry
27 @public_streams ["public", "public:local", "public:media", "public:local:media"]
28 @user_streams ["user", "user:notification", "direct", "user:pleroma_chat"]
30 @doc "Expands and authorizes a stream, and registers the process for streaming."
31 @spec get_topic_and_add_socket(
37 {:ok, topic :: String.t()} | {:error, :bad_topic} | {:error, :unauthorized}
38 def get_topic_and_add_socket(stream, user, oauth_token, params \\ %{}) do
39 with {:ok, topic} <- get_topic(stream, user, oauth_token, params) do
40 add_socket(topic, user)
44 @doc "Expand and authorizes a stream"
45 @spec get_topic(stream :: String.t(), User.t() | nil, Token.t() | nil, Map.t()) ::
46 {:ok, topic :: String.t()} | {:error, :bad_topic}
47 def get_topic(stream, user, oauth_token, params \\ %{})
49 # Allow all public steams.
50 def get_topic(stream, _user, _oauth_token, _params) when stream in @public_streams do
54 # Allow all hashtags streams.
55 def get_topic("hashtag", _user, _oauth_token, %{"tag" => tag} = _params) do
56 {:ok, "hashtag:" <> tag}
59 # Allow remote instance streams.
60 def get_topic("public:remote", _user, _oauth_token, %{"instance" => instance} = _params) do
61 {:ok, "public:remote:" <> instance}
64 def get_topic("public:remote:media", _user, _oauth_token, %{"instance" => instance} = _params) do
65 {:ok, "public:remote:media:" <> instance}
68 # Expand user streams.
71 %User{id: user_id} = user,
72 %Token{user_id: user_id} = oauth_token,
75 when stream in @user_streams do
76 # Note: "read" works for all user streams (not mentioning it since it's an ancestor scope)
78 if stream == "user:notification" do
79 ["read:notifications"]
84 if OAuthScopesPlug.filter_descendants(required_scopes, oauth_token.scopes) == [] do
85 {:error, :unauthorized}
87 {:ok, stream <> ":" <> to_string(user.id)}
91 def get_topic(stream, _user, _oauth_token, _params) when stream in @user_streams do
92 {:error, :unauthorized}
98 %User{id: user_id} = user,
99 %Token{user_id: user_id} = oauth_token,
103 OAuthScopesPlug.filter_descendants(["read", "read:lists"], oauth_token.scopes) == [] ->
104 {:error, :unauthorized}
106 Pleroma.List.get(id, user) ->
107 {:ok, "list:" <> to_string(id)}
114 def get_topic("list", _user, _oauth_token, _params) do
115 {:error, :unauthorized}
118 def get_topic(_stream, _user, _oauth_token, _params) do
122 @doc "Registers the process for streaming. Use `get_topic/3` to get the full authorized topic."
123 def add_socket(topic, user) do
124 if should_env_send?() do
125 auth? = if user, do: true
126 Registry.register(@registry, topic, auth?)
132 def remove_socket(topic) do
133 if should_env_send?(), do: Registry.unregister(@registry, topic)
136 def stream(topics, items) do
137 if should_env_send?() do
138 for topic <- List.wrap(topics), item <- List.wrap(items) do
139 spawn(fn -> do_stream(topic, item) end)
144 def filtered_by_user?(user, item, streamed_type \\ :activity)
146 def filtered_by_user?(%User{} = user, %Activity{} = item, streamed_type) do
147 %{block: blocked_ap_ids, mute: muted_ap_ids, reblog_mute: reblog_muted_ap_ids} =
148 User.outgoing_relationships_ap_ids(user, [:block, :mute, :reblog_mute])
150 recipient_blocks = MapSet.new(blocked_ap_ids ++ muted_ap_ids)
151 recipients = MapSet.new(item.recipients)
152 domain_blocks = Pleroma.Web.ActivityPub.MRF.subdomains_regex(user.domain_blocks)
154 with parent <- Object.normalize(item, fetch: false) || item,
155 true <- Enum.all?([blocked_ap_ids, muted_ap_ids], &(item.actor not in &1)),
156 true <- item.data["type"] != "Announce" || item.actor not in reblog_muted_ap_ids,
158 !(streamed_type == :activity && item.data["type"] == "Announce" &&
159 parent.data["actor"] == user.ap_id),
160 true <- Enum.all?([blocked_ap_ids, muted_ap_ids], &(parent.data["actor"] not in &1)),
161 true <- MapSet.disjoint?(recipients, recipient_blocks),
162 %{host: item_host} <- URI.parse(item.actor),
163 %{host: parent_host} <- URI.parse(parent.data["actor"]),
164 false <- Pleroma.Web.ActivityPub.MRF.subdomain_match?(domain_blocks, item_host),
165 false <- Pleroma.Web.ActivityPub.MRF.subdomain_match?(domain_blocks, parent_host),
166 true <- thread_containment(item, user),
167 false <- CommonAPI.thread_muted?(user, parent) do
174 def filtered_by_user?(%User{} = user, %Notification{activity: activity}, _) do
175 filtered_by_user?(user, activity, :notification)
178 defp do_stream("direct", item) do
180 User.get_recipients_from_activity(item)
181 |> Enum.map(fn %{id: id} -> "direct:#{id}" end)
183 Enum.each(recipient_topics, fn user_topic ->
184 Logger.debug("Trying to push direct message to #{user_topic}\n\n")
185 push_to_socket(user_topic, item)
189 defp do_stream("follow_relationship", item) do
190 text = StreamerView.render("follow_relationships_update.json", item)
191 user_topic = "user:#{item.follower.id}"
193 Logger.debug("Trying to push follow relationship update to #{user_topic}\n\n")
195 Registry.dispatch(@registry, user_topic, fn list ->
196 Enum.each(list, fn {pid, _auth} ->
197 send(pid, {:text, text})
202 defp do_stream("participation", participation) do
203 user_topic = "direct:#{participation.user_id}"
204 Logger.debug("Trying to push a conversation participation to #{user_topic}\n\n")
206 push_to_socket(user_topic, participation)
209 defp do_stream("list", item) do
210 # filter the recipient list if the activity is not public, see #270.
212 case Visibility.is_public?(item) do
214 Pleroma.List.get_lists_from_activity(item)
217 Pleroma.List.get_lists_from_activity(item)
218 |> Enum.filter(fn list ->
219 owner = User.get_cached_by_id(list.user_id)
221 Visibility.visible_for_user?(item, owner)
227 |> Enum.map(fn %{id: id} -> "list:#{id}" end)
229 Enum.each(recipient_topics, fn list_topic ->
230 Logger.debug("Trying to push message to #{list_topic}\n\n")
231 push_to_socket(list_topic, item)
235 defp do_stream(topic, %Notification{} = item)
236 when topic in ["user", "user:notification"] do
237 Registry.dispatch(@registry, "#{topic}:#{item.user_id}", fn list ->
238 Enum.each(list, fn {pid, _auth} ->
239 send(pid, {:render_with_user, StreamerView, "notification.json", item})
244 defp do_stream(topic, {user, %MessageReference{} = cm_ref})
245 when topic in ["user", "user:pleroma_chat"] do
246 topic = "#{topic}:#{user.id}"
248 text = StreamerView.render("chat_update.json", %{chat_message_reference: cm_ref})
250 Registry.dispatch(@registry, topic, fn list ->
251 Enum.each(list, fn {pid, _auth} ->
252 send(pid, {:text, text})
257 defp do_stream("user", item) do
258 Logger.debug("Trying to push to users")
261 User.get_recipients_from_activity(item)
262 |> Enum.map(fn %{id: id} -> "user:#{id}" end)
264 Enum.each(recipient_topics, fn topic ->
265 push_to_socket(topic, item)
269 defp do_stream(topic, item) do
270 Logger.debug("Trying to push to #{topic}")
271 Logger.debug("Pushing item to #{topic}")
272 push_to_socket(topic, item)
275 defp push_to_socket(topic, %Participation{} = participation) do
276 rendered = StreamerView.render("conversation.json", participation)
278 Registry.dispatch(@registry, topic, fn list ->
279 Enum.each(list, fn {pid, _} ->
280 send(pid, {:text, rendered})
285 defp push_to_socket(topic, %Activity{
286 data: %{"type" => "Delete", "deleted_activity_id" => deleted_activity_id}
288 rendered = Jason.encode!(%{event: "delete", payload: to_string(deleted_activity_id)})
290 Registry.dispatch(@registry, topic, fn list ->
291 Enum.each(list, fn {pid, _} ->
292 send(pid, {:text, rendered})
297 defp push_to_socket(_topic, %Activity{data: %{"type" => "Delete"}}), do: :noop
299 defp push_to_socket(topic, item) do
300 anon_render = StreamerView.render("update.json", item)
302 Registry.dispatch(@registry, topic, fn list ->
303 Enum.each(list, fn {pid, auth?} ->
305 send(pid, {:render_with_user, StreamerView, "update.json", item})
307 send(pid, {:text, anon_render})
313 defp thread_containment(_activity, %User{skip_thread_containment: true}), do: true
315 defp thread_containment(activity, user) do
316 if Config.get([:instance, :skip_thread_containment]) do
319 ActivityPub.contain_activity(activity, user)
323 # In test environement, only return true if the registry is started.
324 # In benchmark environment, returns false.
325 # In any other environment, always returns true.
328 def should_env_send? do
329 case Process.whereis(@registry) do
338 @mix_env == :benchmark ->
339 def should_env_send?, do: false
342 def should_env_send?, do: true