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 defp check_actor_is_active(actor) do
20 if not is_nil(actor) do
21 with user <- User.get_cached_by_ap_id(actor),
22 nil <- user.info["deactivated"] do
32 def insert(map, local \\ true) when is_map(map) do
33 with nil <- Activity.get_by_ap_id(map["id"]),
34 map <- lazy_put_activity_defaults(map),
35 :ok <- check_actor_is_active(map["actor"]),
36 {:ok, map} <- MRF.filter(map),
37 :ok <- insert_full_object(map) do
39 Repo.insert(%Activity{
43 recipients: get_recipients(map)
46 Notification.create_notifications(activity)
50 %Activity{} = activity -> {:ok, activity}
51 error -> {:error, error}
55 def stream_out(activity) do
56 if activity.data["type"] in ["Create", "Announce"] do
57 Pleroma.Web.Streamer.stream("user", activity)
59 if Enum.member?(activity.data["to"], "https://www.w3.org/ns/activitystreams#Public") do
60 Pleroma.Web.Streamer.stream("public", activity)
63 Pleroma.Web.Streamer.stream("public:local", activity)
69 def create(%{to: to, actor: actor, context: context, object: object} = params) do
70 additional = params[:additional] || %{}
71 # only accept false as false value
72 local = !(params[:local] == false)
73 published = params[:published]
77 %{to: to, actor: actor, published: published, context: context, object: object},
80 {:ok, activity} <- insert(create_data, local),
81 :ok <- maybe_federate(activity),
82 {:ok, _actor} <- User.increase_note_count(actor) do
87 def accept(%{to: to, actor: actor, object: object} = params) do
88 # only accept false as false value
89 local = !(params[:local] == false)
91 with data <- %{"to" => to, "type" => "Accept", "actor" => actor, "object" => object},
92 {:ok, activity} <- insert(data, local),
93 :ok <- maybe_federate(activity) do
98 def update(%{to: to, cc: cc, actor: actor, object: object} = params) do
99 # only accept false as false value
100 local = !(params[:local] == false)
109 {:ok, activity} <- insert(data, local),
110 :ok <- maybe_federate(activity) do
115 # TODO: This is weird, maybe we shouldn't check here if we can make the activity.
117 %User{ap_id: ap_id} = user,
118 %Object{data: %{"id" => _}} = object,
122 with nil <- get_existing_like(ap_id, object),
123 like_data <- make_like_data(user, object, activity_id),
124 {:ok, activity} <- insert(like_data, local),
125 {:ok, object} <- add_like_to_object(activity, object),
126 :ok <- maybe_federate(activity) do
127 {:ok, activity, object}
129 %Activity{} = activity -> {:ok, activity, object}
130 error -> {:error, error}
134 def unlike(%User{} = actor, %Object{} = object) do
135 with %Activity{} = activity <- get_existing_like(actor.ap_id, object),
136 {:ok, _activity} <- Repo.delete(activity),
137 {:ok, object} <- remove_like_from_object(activity, object) do
145 %User{ap_id: _} = user,
146 %Object{data: %{"id" => _}} = object,
150 with true <- is_public?(object),
151 announce_data <- make_announce_data(user, object, activity_id),
152 {:ok, activity} <- insert(announce_data, local),
153 {:ok, object} <- add_announce_to_object(activity, object),
154 :ok <- maybe_federate(activity) do
155 {:ok, activity, object}
157 error -> {:error, error}
167 with %Activity{} = announce_activity <- get_existing_announce(actor.ap_id, object),
168 unannounce_data <- make_unannounce_data(actor, announce_activity, activity_id),
169 {:ok, unannounce_activity} <- insert(unannounce_data, local),
170 :ok <- maybe_federate(unannounce_activity),
171 {:ok, _activity} <- Repo.delete(announce_activity),
172 {:ok, object} <- remove_announce_from_object(announce_activity, object) do
173 {:ok, unannounce_activity, announce_activity, object}
179 def follow(follower, followed, activity_id \\ nil, local \\ true) do
180 with data <- make_follow_data(follower, followed, activity_id),
181 {:ok, activity} <- insert(data, local),
182 :ok <- maybe_federate(activity) do
187 def unfollow(follower, followed, local \\ true) do
188 with %Activity{} = follow_activity <- fetch_latest_follow(follower, followed),
189 unfollow_data <- make_unfollow_data(follower, followed, follow_activity),
190 {:ok, activity} <- insert(unfollow_data, local),
192 maybe_federate(activity) do
197 def delete(%Object{data: %{"id" => id, "actor" => actor}} = object, local \\ true) do
198 user = User.get_cached_by_ap_id(actor)
204 "to" => [user.follower_address, "https://www.w3.org/ns/activitystreams#Public"]
207 with Repo.delete(object),
208 Repo.delete_all(Activity.all_non_create_by_object_ap_id_q(id)),
209 {:ok, activity} <- insert(data, local),
210 :ok <- maybe_federate(activity),
211 {:ok, _actor} <- User.decrease_note_count(user) do
216 def fetch_activities_for_context(context, opts \\ %{}) do
217 public = ["https://www.w3.org/ns/activitystreams#Public"]
220 if opts["user"], do: [opts["user"].ap_id | opts["user"].following] ++ public, else: public
222 query = from(activity in Activity)
226 |> restrict_blocked(opts)
227 |> restrict_recipients(recipients, opts["user"])
234 "?->>'type' = ? and ?->>'context' = ?",
240 order_by: [desc: :id]
246 def fetch_public_activities(opts \\ %{}) do
247 q = fetch_activities_query(["https://www.w3.org/ns/activitystreams#Public"], opts)
250 |> restrict_unlisted()
255 defp restrict_since(query, %{"since_id" => since_id}) do
256 from(activity in query, where: activity.id > ^since_id)
259 defp restrict_since(query, _), do: query
261 defp restrict_tag(query, %{"tag" => tag}) do
264 where: fragment("? <@ (? #> '{\"object\",\"tag\"}')", ^tag, activity.data)
268 defp restrict_tag(query, _), do: query
270 defp restrict_recipients(query, [], _user), do: query
272 defp restrict_recipients(query, recipients, nil) do
273 from(activity in query, where: fragment("? && ?", ^recipients, activity.recipients))
276 defp restrict_recipients(query, recipients, user) do
279 where: fragment("? && ?", ^recipients, activity.recipients),
280 or_where: activity.actor == ^user.ap_id
284 defp restrict_limit(query, %{"limit" => limit}) do
285 from(activity in query, limit: ^limit)
288 defp restrict_limit(query, _), do: query
290 defp restrict_local(query, %{"local_only" => true}) do
291 from(activity in query, where: activity.local == true)
294 defp restrict_local(query, _), do: query
296 defp restrict_max(query, %{"max_id" => max_id}) do
297 from(activity in query, where: activity.id < ^max_id)
300 defp restrict_max(query, _), do: query
302 defp restrict_actor(query, %{"actor_id" => actor_id}) do
303 from(activity in query, where: activity.actor == ^actor_id)
306 defp restrict_actor(query, _), do: query
308 defp restrict_type(query, %{"type" => type}) when is_binary(type) do
309 restrict_type(query, %{"type" => [type]})
312 defp restrict_type(query, %{"type" => type}) do
313 from(activity in query, where: fragment("?->>'type' = ANY(?)", activity.data, ^type))
316 defp restrict_type(query, _), do: query
318 defp restrict_favorited_by(query, %{"favorited_by" => ap_id}) do
321 where: fragment("? <@ (? #> '{\"object\",\"likes\"}')", ^ap_id, activity.data)
325 defp restrict_favorited_by(query, _), do: query
327 defp restrict_media(query, %{"only_media" => val}) when val == "true" or val == "1" do
330 where: fragment("not (? #> '{\"object\",\"attachment\"}' = ?)", activity.data, ^[])
334 defp restrict_media(query, _), do: query
336 # Only search through last 100_000 activities by default
337 defp restrict_recent(query, %{"whole_db" => true}), do: query
339 defp restrict_recent(query, _) do
340 since = (Repo.aggregate(Activity, :max, :id) || 0) - 100_000
342 from(activity in query, where: activity.id > ^since)
345 defp restrict_blocked(query, %{"blocking_user" => %User{info: info}}) do
346 blocks = info["blocks"] || []
350 where: fragment("not (? = ANY(?))", activity.actor, ^blocks),
351 where: fragment("not (?->'to' \\?| ?)", activity.data, ^blocks)
355 defp restrict_blocked(query, _), do: query
357 defp restrict_unlisted(query) do
362 "not (coalesce(?->'cc', '{}'::jsonb) \\?| ?)",
364 ^["https://www.w3.org/ns/activitystreams#Public"]
369 def fetch_activities_query(recipients, opts \\ %{}) do
372 activity in Activity,
374 order_by: [fragment("? desc nulls last", activity.id)]
378 |> restrict_recipients(recipients, opts["user"])
379 |> restrict_tag(opts)
380 |> restrict_since(opts)
381 |> restrict_local(opts)
382 |> restrict_limit(opts)
383 |> restrict_max(opts)
384 |> restrict_actor(opts)
385 |> restrict_type(opts)
386 |> restrict_favorited_by(opts)
387 |> restrict_recent(opts)
388 |> restrict_blocked(opts)
389 |> restrict_media(opts)
392 def fetch_activities(recipients, opts \\ %{}) do
393 fetch_activities_query(recipients, opts)
399 data = Upload.store(file)
400 Repo.insert(%Object{data: data})
403 def user_data_from_user_object(data) do
405 data["icon"]["url"] &&
408 "url" => [%{"href" => data["icon"]["url"]}]
412 data["image"]["url"] &&
415 "url" => [%{"href" => data["image"]["url"]}]
421 "ap_enabled" => true,
422 "source_data" => data,
426 nickname: "#{data["preferredUsername"]}@#{URI.parse(data["id"]).host}",
428 follower_address: data["followers"],
435 def fetch_and_prepare_user_from_ap_id(ap_id) do
436 with {:ok, %{status_code: 200, body: body}} <-
437 @httpoison.get(ap_id, Accept: "application/activity+json"),
438 {:ok, data} <- Jason.decode(body) do
439 user_data_from_user_object(data)
441 e -> Logger.error("Could not decode user at fetch #{ap_id}, #{inspect(e)}")
445 def make_user_from_ap_id(ap_id) do
446 if _user = User.get_by_ap_id(ap_id) do
447 Transmogrifier.upgrade_user_from_ap_id(ap_id)
449 with {:ok, data} <- fetch_and_prepare_user_from_ap_id(ap_id) do
450 User.insert_or_update_user(data)
457 def make_user_from_nickname(nickname) do
458 with {:ok, %{"ap_id" => ap_id}} when not is_nil(ap_id) <- WebFinger.finger(nickname) do
459 make_user_from_ap_id(ap_id)
461 _e -> {:error, "No AP id in WebFinger"}
465 def publish(actor, activity) do
467 if actor.follower_address in activity.recipients do
468 {:ok, followers} = User.get_followers(actor)
469 followers |> Enum.filter(&(!&1.local))
475 (Pleroma.Web.Salmon.remote_users(activity) ++ followers)
476 |> Enum.filter(fn user -> User.ap_enabled?(user) end)
477 |> Enum.map(fn %{info: %{"source_data" => data}} ->
478 (data["endpoints"] && data["endpoints"]["sharedInbox"]) || data["inbox"]
482 {:ok, data} = Transmogrifier.prepare_outgoing(activity.data)
483 json = Jason.encode!(data)
485 Enum.each(remote_inboxes, fn inbox ->
486 Federator.enqueue(:publish_single_ap, %{
490 id: activity.data["id"]
495 def publish_one(%{inbox: inbox, json: json, actor: actor, id: id}) do
496 Logger.info("Federating #{id} to #{inbox}")
497 host = URI.parse(inbox).host
500 Pleroma.Web.HTTPSignatures.sign(actor, %{host: host, "content-length": byte_size(json)})
505 [{"Content-Type", "application/activity+json"}, {"signature", signature}],
506 hackney: [pool: :default]
511 # This will create a Create activity, which we need internally at the moment.
512 def fetch_object_from_id(id) do
513 if object = Object.get_cached_by_ap_id(id) do
516 Logger.info("Fetching #{id} via AP")
518 with true <- String.starts_with?(id, "http"),
519 {:ok, %{body: body, status_code: code}} when code in 200..299 <-
522 [Accept: "application/activity+json"],
523 follow_redirect: true,
527 {:ok, data} <- Jason.decode(body),
528 nil <- Object.get_by_ap_id(data["id"]),
533 "actor" => data["attributedTo"],
536 {:ok, activity} <- Transmogrifier.handle_incoming(params) do
537 {:ok, Object.get_by_ap_id(activity.data["object"]["id"])}
539 object = %Object{} ->
543 Logger.info("Couldn't get object via AP, trying out OStatus fetching...")
545 case OStatus.fetch_activity_from_url(id) do
546 {:ok, [activity | _]} -> {:ok, Object.get_by_ap_id(activity.data["object"]["id"])}
553 def is_public?(activity) do
554 "https://www.w3.org/ns/activitystreams#Public" in (activity.data["to"] ++
555 (activity.data["cc"] || []))
558 def visible_for_user?(activity, nil) do
562 def visible_for_user?(activity, user) do
563 x = [user.ap_id | user.following]
564 y = activity.data["to"] ++ (activity.data["cc"] || [])
565 visible_for_user?(activity, nil) || Enum.any?(x, &(&1 in y))