1 defmodule Pleroma.Web.ActivityPub.ActivityPub do
2 alias Pleroma.{Activity, Repo, Object, Upload, User, Notification}
3 alias Pleroma.Web.ActivityPub.Transmogrifier
4 alias Pleroma.Web.WebFinger
5 alias Pleroma.Web.Federator
6 alias Pleroma.Web.OStatus
8 import Pleroma.Web.ActivityPub.Utils
11 @httpoison Application.get_env(:pleroma, :httpoison)
13 @instance Application.get_env(:pleroma, :instance)
14 @rewrite_policy Keyword.get(@instance, :rewrite_policy)
16 def get_recipients(data) do
17 (data["to"] || []) ++ (data["cc"] || [])
20 def insert(map, local \\ true) when is_map(map) do
21 with nil <- Activity.get_by_ap_id(map["id"]),
22 map <- lazy_put_activity_defaults(map),
23 :ok <- insert_full_object(map),
24 {:ok, map} <- @rewrite_policy.filter(map) do
26 Repo.insert(%Activity{
30 recipients: get_recipients(map)
33 Notification.create_notifications(activity)
37 %Activity{} = activity -> {:ok, activity}
38 error -> {:error, error}
42 def stream_out(activity) do
43 if activity.data["type"] in ["Create", "Announce"] do
44 Pleroma.Web.Streamer.stream("user", activity)
46 if Enum.member?(activity.data["to"], "https://www.w3.org/ns/activitystreams#Public") do
47 Pleroma.Web.Streamer.stream("public", activity)
50 Pleroma.Web.Streamer.stream("public:local", activity)
56 def create(%{to: to, actor: actor, context: context, object: object} = params) do
57 additional = params[:additional] || %{}
58 # only accept false as false value
59 local = !(params[:local] == false)
60 published = params[:published]
64 %{to: to, actor: actor, published: published, context: context, object: object},
67 {:ok, activity} <- insert(create_data, local),
68 :ok <- maybe_federate(activity) do
73 def accept(%{to: to, actor: actor, object: object} = params) do
74 # only accept false as false value
75 local = !(params[:local] == false)
77 with data <- %{"to" => to, "type" => "Accept", "actor" => actor, "object" => object},
78 {:ok, activity} <- insert(data, local),
79 :ok <- maybe_federate(activity) do
84 def update(%{to: to, cc: cc, actor: actor, object: object} = params) do
85 # only accept false as false value
86 local = !(params[:local] == false)
95 {:ok, activity} <- insert(data, local),
96 :ok <- maybe_federate(activity) do
101 # TODO: This is weird, maybe we shouldn't check here if we can make the activity.
103 %User{ap_id: ap_id} = user,
104 %Object{data: %{"id" => _}} = object,
108 with nil <- get_existing_like(ap_id, object),
109 like_data <- make_like_data(user, object, activity_id),
110 {:ok, activity} <- insert(like_data, local),
111 {:ok, object} <- add_like_to_object(activity, object),
112 :ok <- maybe_federate(activity) do
113 {:ok, activity, object}
115 %Activity{} = activity -> {:ok, activity, object}
116 error -> {:error, error}
120 def unlike(%User{} = actor, %Object{} = object) do
121 with %Activity{} = activity <- get_existing_like(actor.ap_id, object),
122 {:ok, _activity} <- Repo.delete(activity),
123 {:ok, object} <- remove_like_from_object(activity, object) do
131 %User{ap_id: _} = user,
132 %Object{data: %{"id" => _}} = object,
136 with true <- is_public?(object),
137 announce_data <- make_announce_data(user, object, activity_id),
138 {:ok, activity} <- insert(announce_data, local),
139 {:ok, object} <- add_announce_to_object(activity, object),
140 :ok <- maybe_federate(activity) do
141 {:ok, activity, object}
143 error -> {:error, error}
147 def follow(follower, followed, activity_id \\ nil, local \\ true) do
148 with data <- make_follow_data(follower, followed, activity_id),
149 {:ok, activity} <- insert(data, local),
150 :ok <- maybe_federate(activity) do
155 def unfollow(follower, followed, local \\ true) do
156 with %Activity{} = follow_activity <- fetch_latest_follow(follower, followed),
157 unfollow_data <- make_unfollow_data(follower, followed, follow_activity),
158 {:ok, activity} <- insert(unfollow_data, local),
160 maybe_federate(activity) do
165 def delete(%Object{data: %{"id" => id, "actor" => actor}} = object, local \\ true) do
166 user = User.get_cached_by_ap_id(actor)
172 "to" => [user.follower_address, "https://www.w3.org/ns/activitystreams#Public"]
175 with Repo.delete(object),
176 Repo.delete_all(Activity.all_non_create_by_object_ap_id_q(id)),
177 {:ok, activity} <- insert(data, local),
178 :ok <- maybe_federate(activity) do
183 def fetch_activities_for_context(context, opts \\ %{}) do
184 public = ["https://www.w3.org/ns/activitystreams#Public"]
187 if opts["user"], do: [opts["user"].ap_id | opts["user"].following] ++ public, else: public
189 query = from(activity in Activity)
193 |> restrict_blocked(opts)
194 |> restrict_recipients(recipients, opts["user"])
201 "?->>'type' = ? and ?->>'context' = ?",
207 order_by: [desc: :id]
213 # TODO: Make this work properly with unlisted.
214 def fetch_public_activities(opts \\ %{}) do
215 q = fetch_activities_query(["https://www.w3.org/ns/activitystreams#Public"], opts)
222 defp restrict_since(query, %{"since_id" => since_id}) do
223 from(activity in query, where: activity.id > ^since_id)
226 defp restrict_since(query, _), do: query
228 defp restrict_tag(query, %{"tag" => tag}) do
231 where: fragment("? <@ (? #> '{\"object\",\"tag\"}')", ^tag, activity.data)
235 defp restrict_tag(query, _), do: query
237 defp restrict_recipients(query, [], user), do: query
239 defp restrict_recipients(query, recipients, nil) do
240 from(activity in query, where: fragment("? && ?", ^recipients, activity.recipients))
243 defp restrict_recipients(query, recipients, user) do
246 where: fragment("? && ?", ^recipients, activity.recipients),
247 or_where: activity.actor == ^user.ap_id
251 defp restrict_limit(query, %{"limit" => limit}) do
252 from(activity in query, limit: ^limit)
255 defp restrict_limit(query, _), do: query
257 defp restrict_local(query, %{"local_only" => true}) do
258 from(activity in query, where: activity.local == true)
261 defp restrict_local(query, _), do: query
263 defp restrict_max(query, %{"max_id" => max_id}) do
264 from(activity in query, where: activity.id < ^max_id)
267 defp restrict_max(query, _), do: query
269 defp restrict_actor(query, %{"actor_id" => actor_id}) do
270 from(activity in query, where: activity.actor == ^actor_id)
273 defp restrict_actor(query, _), do: query
275 defp restrict_type(query, %{"type" => type}) when is_binary(type) do
276 restrict_type(query, %{"type" => [type]})
279 defp restrict_type(query, %{"type" => type}) do
280 from(activity in query, where: fragment("?->>'type' = ANY(?)", activity.data, ^type))
283 defp restrict_type(query, _), do: query
285 defp restrict_favorited_by(query, %{"favorited_by" => ap_id}) do
288 where: fragment("? <@ (? #> '{\"object\",\"likes\"}')", ^ap_id, activity.data)
292 defp restrict_favorited_by(query, _), do: query
294 defp restrict_media(query, %{"only_media" => val}) when val == "true" or val == "1" do
297 where: fragment("not (? #> '{\"object\",\"attachment\"}' = ?)", activity.data, ^[])
301 defp restrict_media(query, _), do: query
303 # Only search through last 100_000 activities by default
304 defp restrict_recent(query, %{"whole_db" => true}), do: query
306 defp restrict_recent(query, _) do
307 since = (Repo.aggregate(Activity, :max, :id) || 0) - 100_000
309 from(activity in query, where: activity.id > ^since)
312 defp restrict_blocked(query, %{"blocking_user" => %User{info: info}}) do
313 blocks = info["blocks"] || []
314 from(activity in query, where: fragment("not (? = ANY(?))", activity.actor, ^blocks))
317 defp restrict_blocked(query, _), do: query
319 def fetch_activities_query(recipients, opts \\ %{}) do
322 activity in Activity,
324 order_by: [fragment("? desc nulls last", activity.id)]
328 |> restrict_recipients(recipients, opts["user"])
329 |> restrict_tag(opts)
330 |> restrict_since(opts)
331 |> restrict_local(opts)
332 |> restrict_limit(opts)
333 |> restrict_max(opts)
334 |> restrict_actor(opts)
335 |> restrict_type(opts)
336 |> restrict_favorited_by(opts)
337 |> restrict_recent(opts)
338 |> restrict_blocked(opts)
339 |> restrict_media(opts)
342 def fetch_activities(recipients, opts \\ %{}) do
343 fetch_activities_query(recipients, opts)
349 data = Upload.store(file)
350 Repo.insert(%Object{data: data})
353 def user_data_from_user_object(data) do
355 data["icon"]["url"] &&
358 "url" => [%{"href" => data["icon"]["url"]}]
362 data["image"]["url"] &&
365 "url" => [%{"href" => data["image"]["url"]}]
371 "ap_enabled" => true,
372 "source_data" => data,
376 nickname: "#{data["preferredUsername"]}@#{URI.parse(data["id"]).host}",
378 follower_address: data["followers"],
385 def fetch_and_prepare_user_from_ap_id(ap_id) do
386 with {:ok, %{status_code: 200, body: body}} <-
387 @httpoison.get(ap_id, Accept: "application/activity+json"),
388 {:ok, data} <- Jason.decode(body) do
389 user_data_from_user_object(data)
391 e -> Logger.error("Could not decode user at fetch #{ap_id}, #{inspect(e)}")
395 def make_user_from_ap_id(ap_id) do
396 if user = User.get_by_ap_id(ap_id) do
397 Transmogrifier.upgrade_user_from_ap_id(ap_id)
399 with {:ok, data} <- fetch_and_prepare_user_from_ap_id(ap_id) do
400 User.insert_or_update_user(data)
407 def make_user_from_nickname(nickname) do
408 with {:ok, %{"ap_id" => ap_id}} when not is_nil(ap_id) <- WebFinger.finger(nickname) do
409 make_user_from_ap_id(ap_id)
411 _e -> {:error, "No AP id in WebFinger"}
415 def publish(actor, activity) do
417 if actor.follower_address in activity.recipients do
418 {:ok, followers} = User.get_followers(actor)
419 followers |> Enum.filter(&(!&1.local))
425 (Pleroma.Web.Salmon.remote_users(activity) ++ followers)
426 |> Enum.filter(fn user -> User.ap_enabled?(user) end)
427 |> Enum.map(fn %{info: %{"source_data" => data}} ->
428 (data["endpoints"] && data["endpoints"]["sharedInbox"]) || data["inbox"]
432 {:ok, data} = Transmogrifier.prepare_outgoing(activity.data)
433 json = Jason.encode!(data)
435 Enum.each(remote_inboxes, fn inbox ->
436 Federator.enqueue(:publish_single_ap, %{
440 id: activity.data["id"]
445 def publish_one(%{inbox: inbox, json: json, actor: actor, id: id}) do
446 Logger.info("Federating #{id} to #{inbox}")
447 host = URI.parse(inbox).host
450 Pleroma.Web.HTTPSignatures.sign(actor, %{host: host, "content-length": byte_size(json)})
455 [{"Content-Type", "application/activity+json"}, {"signature", signature}],
456 hackney: [pool: :default]
461 # This will create a Create activity, which we need internally at the moment.
462 def fetch_object_from_id(id) do
463 if object = Object.get_cached_by_ap_id(id) do
466 Logger.info("Fetching #{id} via AP")
468 with true <- String.starts_with?(id, "http"),
469 {:ok, %{body: body, status_code: code}} when code in 200..299 <-
472 [Accept: "application/activity+json"],
473 follow_redirect: true,
477 {:ok, data} <- Jason.decode(body),
478 nil <- Object.get_by_ap_id(data["id"]),
483 "actor" => data["attributedTo"],
486 {:ok, activity} <- Transmogrifier.handle_incoming(params) do
487 {:ok, Object.get_by_ap_id(activity.data["object"]["id"])}
489 object = %Object{} ->
493 Logger.info("Couldn't get object via AP, trying out OStatus fetching...")
495 case OStatus.fetch_activity_from_url(id) do
496 {:ok, [activity | _]} -> {:ok, Object.get_by_ap_id(activity.data["object"]["id"])}
503 def is_public?(activity) do
504 "https://www.w3.org/ns/activitystreams#Public" in (activity.data["to"] ++
505 (activity.data["cc"] || []))
508 def visible_for_user?(activity, nil) do
512 def visible_for_user?(activity, user) do
513 x = [user.ap_id | user.following]
514 y = activity.data["to"] ++ (activity.data["cc"] || [])
515 visible_for_user?(activity, nil) || Enum.any?(x, &(&1 in y))