1 defmodule Pleroma.Web.ActivityPub.ActivityPub do
2 alias Pleroma.{Activity, Repo, Object, Upload, User, Notification}
3 alias Pleroma.Web.ActivityPub.{Transmogrifier, MRF}
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)
15 def get_recipients(data) do
16 (data["to"] || []) ++ (data["cc"] || [])
19 def insert(map, local \\ true) when is_map(map) do
20 with nil <- Activity.get_by_ap_id(map["id"]),
21 map <- lazy_put_activity_defaults(map),
22 {:ok, map} <- MRF.filter(map),
23 :ok <- insert_full_object(map) do
25 Repo.insert(%Activity{
29 recipients: get_recipients(map)
32 Notification.create_notifications(activity)
36 %Activity{} = activity -> {:ok, activity}
37 error -> {:error, error}
41 def stream_out(activity) do
42 if activity.data["type"] in ["Create", "Announce"] do
43 Pleroma.Web.Streamer.stream("user", activity)
45 if Enum.member?(activity.data["to"], "https://www.w3.org/ns/activitystreams#Public") do
46 Pleroma.Web.Streamer.stream("public", activity)
49 Pleroma.Web.Streamer.stream("public:local", activity)
55 def create(%{to: to, actor: actor, context: context, object: object} = params) do
56 additional = params[:additional] || %{}
57 # only accept false as false value
58 local = !(params[:local] == false)
59 published = params[:published]
63 %{to: to, actor: actor, published: published, context: context, object: object},
66 {:ok, activity} <- insert(create_data, local),
67 :ok <- maybe_federate(activity),
68 {:ok, _actor} <- User.increase_note_count(actor) 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),
179 {:ok, _actor} <- User.decrease_note_count(user) do
184 def fetch_activities_for_context(context, opts \\ %{}) do
185 public = ["https://www.w3.org/ns/activitystreams#Public"]
188 if opts["user"], do: [opts["user"].ap_id | opts["user"].following] ++ public, else: public
190 query = from(activity in Activity)
194 |> restrict_blocked(opts)
195 |> restrict_recipients(recipients, opts["user"])
202 "?->>'type' = ? and ?->>'context' = ?",
208 order_by: [desc: :id]
214 def fetch_public_activities(opts \\ %{}) do
215 q = fetch_activities_query(["https://www.w3.org/ns/activitystreams#Public"], opts)
218 |> restrict_unlisted()
223 defp restrict_since(query, %{"since_id" => since_id}) do
224 from(activity in query, where: activity.id > ^since_id)
227 defp restrict_since(query, _), do: query
229 defp restrict_tag(query, %{"tag" => tag}) do
232 where: fragment("? <@ (? #> '{\"object\",\"tag\"}')", ^tag, activity.data)
236 defp restrict_tag(query, _), do: query
238 defp restrict_recipients(query, [], _user), do: query
240 defp restrict_recipients(query, recipients, nil) do
241 from(activity in query, where: fragment("? && ?", ^recipients, activity.recipients))
244 defp restrict_recipients(query, recipients, user) do
247 where: fragment("? && ?", ^recipients, activity.recipients),
248 or_where: activity.actor == ^user.ap_id
252 defp restrict_limit(query, %{"limit" => limit}) do
253 from(activity in query, limit: ^limit)
256 defp restrict_limit(query, _), do: query
258 defp restrict_local(query, %{"local_only" => true}) do
259 from(activity in query, where: activity.local == true)
262 defp restrict_local(query, _), do: query
264 defp restrict_max(query, %{"max_id" => max_id}) do
265 from(activity in query, where: activity.id < ^max_id)
268 defp restrict_max(query, _), do: query
270 defp restrict_actor(query, %{"actor_id" => actor_id}) do
271 from(activity in query, where: activity.actor == ^actor_id)
274 defp restrict_actor(query, _), do: query
276 defp restrict_type(query, %{"type" => type}) when is_binary(type) do
277 restrict_type(query, %{"type" => [type]})
280 defp restrict_type(query, %{"type" => type}) do
281 from(activity in query, where: fragment("?->>'type' = ANY(?)", activity.data, ^type))
284 defp restrict_type(query, _), do: query
286 defp restrict_favorited_by(query, %{"favorited_by" => ap_id}) do
289 where: fragment("? <@ (? #> '{\"object\",\"likes\"}')", ^ap_id, activity.data)
293 defp restrict_favorited_by(query, _), do: query
295 defp restrict_media(query, %{"only_media" => val}) when val == "true" or val == "1" do
298 where: fragment("not (? #> '{\"object\",\"attachment\"}' = ?)", activity.data, ^[])
302 defp restrict_media(query, _), do: query
304 # Only search through last 100_000 activities by default
305 defp restrict_recent(query, %{"whole_db" => true}), do: query
307 defp restrict_recent(query, _) do
308 since = (Repo.aggregate(Activity, :max, :id) || 0) - 100_000
310 from(activity in query, where: activity.id > ^since)
313 defp restrict_blocked(query, %{"blocking_user" => %User{info: info}}) do
314 blocks = info["blocks"] || []
318 where: fragment("not (? = ANY(?))", activity.actor, ^blocks),
319 where: fragment("not (?->'to' \\?| ?)", activity.data, ^blocks)
323 defp restrict_blocked(query, _), do: query
325 defp restrict_unlisted(query) do
330 "not (coalesce(?->'cc', '{}'::jsonb) \\?| ?)",
332 ^["https://www.w3.org/ns/activitystreams#Public"]
337 def fetch_activities_query(recipients, opts \\ %{}) do
340 activity in Activity,
342 order_by: [fragment("? desc nulls last", activity.id)]
346 |> restrict_recipients(recipients, opts["user"])
347 |> restrict_tag(opts)
348 |> restrict_since(opts)
349 |> restrict_local(opts)
350 |> restrict_limit(opts)
351 |> restrict_max(opts)
352 |> restrict_actor(opts)
353 |> restrict_type(opts)
354 |> restrict_favorited_by(opts)
355 |> restrict_recent(opts)
356 |> restrict_blocked(opts)
357 |> restrict_media(opts)
360 def fetch_activities(recipients, opts \\ %{}) do
361 fetch_activities_query(recipients, opts)
367 data = Upload.store(file)
368 Repo.insert(%Object{data: data})
371 def user_data_from_user_object(data) do
373 data["icon"]["url"] &&
376 "url" => [%{"href" => data["icon"]["url"]}]
380 data["image"]["url"] &&
383 "url" => [%{"href" => data["image"]["url"]}]
389 "ap_enabled" => true,
390 "source_data" => data,
394 nickname: "#{data["preferredUsername"]}@#{URI.parse(data["id"]).host}",
396 follower_address: data["followers"],
403 def fetch_and_prepare_user_from_ap_id(ap_id) do
404 with {:ok, %{status_code: 200, body: body}} <-
405 @httpoison.get(ap_id, Accept: "application/activity+json"),
406 {:ok, data} <- Jason.decode(body) do
407 user_data_from_user_object(data)
409 e -> Logger.error("Could not decode user at fetch #{ap_id}, #{inspect(e)}")
413 def make_user_from_ap_id(ap_id) do
414 if _user = User.get_by_ap_id(ap_id) do
415 Transmogrifier.upgrade_user_from_ap_id(ap_id)
417 with {:ok, data} <- fetch_and_prepare_user_from_ap_id(ap_id) do
418 User.insert_or_update_user(data)
425 def make_user_from_nickname(nickname) do
426 with {:ok, %{"ap_id" => ap_id}} when not is_nil(ap_id) <- WebFinger.finger(nickname) do
427 make_user_from_ap_id(ap_id)
429 _e -> {:error, "No AP id in WebFinger"}
433 def publish(actor, activity) do
435 if actor.follower_address in activity.recipients do
436 {:ok, followers} = User.get_followers(actor)
437 followers |> Enum.filter(&(!&1.local))
443 (Pleroma.Web.Salmon.remote_users(activity) ++ followers)
444 |> Enum.filter(fn user -> User.ap_enabled?(user) end)
445 |> Enum.map(fn %{info: %{"source_data" => data}} ->
446 (data["endpoints"] && data["endpoints"]["sharedInbox"]) || data["inbox"]
450 {:ok, data} = Transmogrifier.prepare_outgoing(activity.data)
451 json = Jason.encode!(data)
453 Enum.each(remote_inboxes, fn inbox ->
454 Federator.enqueue(:publish_single_ap, %{
458 id: activity.data["id"]
463 def publish_one(%{inbox: inbox, json: json, actor: actor, id: id}) do
464 Logger.info("Federating #{id} to #{inbox}")
465 host = URI.parse(inbox).host
468 Pleroma.Web.HTTPSignatures.sign(actor, %{host: host, "content-length": byte_size(json)})
473 [{"Content-Type", "application/activity+json"}, {"signature", signature}],
474 hackney: [pool: :default]
479 # This will create a Create activity, which we need internally at the moment.
480 def fetch_object_from_id(id) do
481 if object = Object.get_cached_by_ap_id(id) do
484 Logger.info("Fetching #{id} via AP")
486 with true <- String.starts_with?(id, "http"),
487 {:ok, %{body: body, status_code: code}} when code in 200..299 <-
490 [Accept: "application/activity+json"],
491 follow_redirect: true,
495 {:ok, data} <- Jason.decode(body),
496 nil <- Object.get_by_ap_id(data["id"]),
501 "actor" => data["attributedTo"],
504 {:ok, activity} <- Transmogrifier.handle_incoming(params) do
505 {:ok, Object.get_by_ap_id(activity.data["object"]["id"])}
507 object = %Object{} ->
511 Logger.info("Couldn't get object via AP, trying out OStatus fetching...")
513 case OStatus.fetch_activity_from_url(id) do
514 {:ok, [activity | _]} -> {:ok, Object.get_by_ap_id(activity.data["object"]["id"])}
521 def is_public?(activity) do
522 "https://www.w3.org/ns/activitystreams#Public" in (activity.data["to"] ++
523 (activity.data["cc"] || []))
526 def visible_for_user?(activity, nil) do
530 def visible_for_user?(activity, user) do
531 x = [user.ap_id | user.following]
532 y = activity.data["to"] ++ (activity.data["cc"] || [])
533 visible_for_user?(activity, nil) || Enum.any?(x, &(&1 in y))