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
10 alias Pleroma.Conversation.Participation
11 alias Pleroma.Notification
14 alias Pleroma.Web.ActivityPub.ActivityPub
15 alias Pleroma.Web.ActivityPub.Visibility
16 alias Pleroma.Web.CommonAPI
17 alias Pleroma.Web.OAuth.Token
18 alias Pleroma.Web.Plugs.OAuthScopesPlug
19 alias Pleroma.Web.StreamerView
22 @registry Pleroma.Web.StreamerRegistry
24 def registry, do: @registry
26 @public_streams ["public", "public:local", "public:media", "public:local:media"]
27 @user_streams ["user", "user:notification", "direct"]
29 @doc "Expands and authorizes a stream, and registers the process for streaming."
30 @spec get_topic_and_add_socket(
36 {:ok, topic :: String.t()} | {:error, :bad_topic} | {:error, :unauthorized}
37 def get_topic_and_add_socket(stream, user, oauth_token, params \\ %{}) do
38 with {:ok, topic} <- get_topic(stream, user, oauth_token, params) do
39 add_socket(topic, user)
43 @doc "Expand and authorizes a stream"
44 @spec get_topic(stream :: String.t(), User.t() | nil, Token.t() | nil, Map.t()) ::
45 {:ok, topic :: String.t()} | {:error, :bad_topic}
46 def get_topic(stream, user, oauth_token, params \\ %{})
48 # Allow all public steams.
49 def get_topic(stream, _user, _oauth_token, _params) when stream in @public_streams do
53 # Allow all hashtags streams.
54 def get_topic("hashtag", _user, _oauth_token, %{"tag" => tag} = _params) do
55 {:ok, "hashtag:" <> tag}
58 # Allow remote instance streams.
59 def get_topic("public:remote", _user, _oauth_token, %{"instance" => instance} = _params) do
60 {:ok, "public:remote:" <> instance}
63 def get_topic("public:remote:media", _user, _oauth_token, %{"instance" => instance} = _params) do
64 {:ok, "public:remote:media:" <> instance}
67 # Expand user streams.
70 %User{id: user_id} = user,
71 %Token{user_id: user_id} = oauth_token,
74 when stream in @user_streams do
75 # Note: "read" works for all user streams (not mentioning it since it's an ancestor scope)
77 if stream == "user:notification" do
78 ["read:notifications"]
83 if OAuthScopesPlug.filter_descendants(required_scopes, oauth_token.scopes) == [] do
84 {:error, :unauthorized}
86 {:ok, stream <> ":" <> to_string(user.id)}
90 def get_topic(stream, _user, _oauth_token, _params) when stream in @user_streams do
91 {:error, :unauthorized}
97 %User{id: user_id} = user,
98 %Token{user_id: user_id} = oauth_token,
102 OAuthScopesPlug.filter_descendants(["read", "read:lists"], oauth_token.scopes) == [] ->
103 {:error, :unauthorized}
105 Pleroma.List.get(id, user) ->
106 {:ok, "list:" <> to_string(id)}
113 def get_topic("list", _user, _oauth_token, _params) do
114 {:error, :unauthorized}
117 def get_topic(_stream, _user, _oauth_token, _params) do
121 @doc "Registers the process for streaming. Use `get_topic/3` to get the full authorized topic."
122 def add_socket(topic, user) do
123 if should_env_send?() do
124 auth? = if user, do: true
125 Registry.register(@registry, topic, auth?)
131 def remove_socket(topic) do
132 if should_env_send?(), do: Registry.unregister(@registry, topic)
135 def stream(topics, items) do
136 if should_env_send?() do
137 for topic <- List.wrap(topics), item <- List.wrap(items) do
138 spawn(fn -> do_stream(topic, item) end)
143 def filtered_by_user?(user, item, streamed_type \\ :activity)
145 def filtered_by_user?(%User{} = user, %Activity{} = item, streamed_type) do
146 %{block: blocked_ap_ids, mute: muted_ap_ids, reblog_mute: reblog_muted_ap_ids} =
147 User.outgoing_relationships_ap_ids(user, [:block, :mute, :reblog_mute])
149 recipient_blocks = MapSet.new(blocked_ap_ids ++ muted_ap_ids)
150 recipients = MapSet.new(item.recipients)
151 domain_blocks = Pleroma.Web.ActivityPub.MRF.subdomains_regex(user.domain_blocks)
153 with parent <- Object.normalize(item, fetch: false) || item,
154 true <- Enum.all?([blocked_ap_ids, muted_ap_ids], &(item.actor not in &1)),
155 true <- item.data["type"] != "Announce" || item.actor not in reblog_muted_ap_ids,
157 !(streamed_type == :activity && item.data["type"] == "Announce" &&
158 parent.data["actor"] == user.ap_id),
159 true <- Enum.all?([blocked_ap_ids, muted_ap_ids], &(parent.data["actor"] not in &1)),
160 true <- MapSet.disjoint?(recipients, recipient_blocks),
161 %{host: item_host} <- URI.parse(item.actor),
162 %{host: parent_host} <- URI.parse(parent.data["actor"]),
163 false <- Pleroma.Web.ActivityPub.MRF.subdomain_match?(domain_blocks, item_host),
164 false <- Pleroma.Web.ActivityPub.MRF.subdomain_match?(domain_blocks, parent_host),
165 true <- thread_containment(item, user),
166 false <- CommonAPI.thread_muted?(user, parent) do
173 def filtered_by_user?(%User{} = user, %Notification{activity: activity}, _) do
174 filtered_by_user?(user, activity, :notification)
177 defp do_stream("direct", item) do
179 User.get_recipients_from_activity(item)
180 |> Enum.map(fn %{id: id} -> "direct:#{id}" end)
182 Enum.each(recipient_topics, fn user_topic ->
183 Logger.debug("Trying to push direct message to #{user_topic}\n\n")
184 push_to_socket(user_topic, item)
188 defp do_stream("follow_relationship", item) do
189 text = StreamerView.render("follow_relationships_update.json", item)
190 user_topic = "user:#{item.follower.id}"
192 Logger.debug("Trying to push follow relationship update to #{user_topic}\n\n")
194 Registry.dispatch(@registry, user_topic, fn list ->
195 Enum.each(list, fn {pid, _auth} ->
196 send(pid, {:text, text})
201 defp do_stream("participation", participation) do
202 user_topic = "direct:#{participation.user_id}"
203 Logger.debug("Trying to push a conversation participation to #{user_topic}\n\n")
205 push_to_socket(user_topic, participation)
208 defp do_stream("list", item) do
209 # filter the recipient list if the activity is not public, see #270.
211 case Visibility.is_public?(item) do
213 Pleroma.List.get_lists_from_activity(item)
216 Pleroma.List.get_lists_from_activity(item)
217 |> Enum.filter(fn list ->
218 owner = User.get_cached_by_id(list.user_id)
220 Visibility.visible_for_user?(item, owner)
226 |> Enum.map(fn %{id: id} -> "list:#{id}" end)
228 Enum.each(recipient_topics, fn list_topic ->
229 Logger.debug("Trying to push message to #{list_topic}\n\n")
230 push_to_socket(list_topic, item)
234 defp do_stream(topic, %Notification{} = item)
235 when topic in ["user", "user:notification"] do
236 Registry.dispatch(@registry, "#{topic}:#{item.user_id}", fn list ->
237 Enum.each(list, fn {pid, _auth} ->
238 send(pid, {:render_with_user, StreamerView, "notification.json", item})
243 defp do_stream("user", item) do
244 Logger.debug("Trying to push to users")
247 User.get_recipients_from_activity(item)
248 |> Enum.map(fn %{id: id} -> "user:#{id}" end)
250 Enum.each(recipient_topics, fn topic ->
251 push_to_socket(topic, item)
255 defp do_stream(topic, item) do
256 Logger.debug("Trying to push to #{topic}")
257 Logger.debug("Pushing item to #{topic}")
258 push_to_socket(topic, item)
261 defp push_to_socket(topic, %Participation{} = participation) do
262 rendered = StreamerView.render("conversation.json", participation)
264 Registry.dispatch(@registry, topic, fn list ->
265 Enum.each(list, fn {pid, _} ->
266 send(pid, {:text, rendered})
271 defp push_to_socket(topic, %Activity{
272 data: %{"type" => "Delete", "deleted_activity_id" => deleted_activity_id}
274 rendered = Jason.encode!(%{event: "delete", payload: to_string(deleted_activity_id)})
276 Registry.dispatch(@registry, topic, fn list ->
277 Enum.each(list, fn {pid, _} ->
278 send(pid, {:text, rendered})
283 defp push_to_socket(_topic, %Activity{data: %{"type" => "Delete"}}), do: :noop
285 defp push_to_socket(topic, item) do
286 anon_render = StreamerView.render("update.json", item)
288 Registry.dispatch(@registry, topic, fn list ->
289 Enum.each(list, fn {pid, auth?} ->
291 send(pid, {:render_with_user, StreamerView, "update.json", item})
293 send(pid, {:text, anon_render})
299 defp thread_containment(_activity, %User{skip_thread_containment: true}), do: true
301 defp thread_containment(activity, user) do
302 if Config.get([:instance, :skip_thread_containment]) do
305 ActivityPub.contain_activity(activity, user)
309 # In test environement, only return true if the registry is started.
310 # In benchmark environment, returns false.
311 # In any other environment, always returns true.
314 def should_env_send? do
315 case Process.whereis(@registry) do
324 @mix_env == :benchmark ->
325 def should_env_send?, do: false
328 def should_env_send?, do: true