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 public = "https://www.w3.org/ns/activitystreams#Public"
58 if activity.data["type"] in ["Create", "Announce"] do
59 Pleroma.Web.Streamer.stream("user", activity)
61 if Enum.member?(activity.data["to"], public) do
62 Pleroma.Web.Streamer.stream("public", activity)
65 Pleroma.Web.Streamer.stream("public:local", activity)
68 if !Enum.member?(activity.data["cc"] || [], public) &&
71 User.get_by_ap_id(activity.data["actor"]).follower_address
73 do: Pleroma.Web.Streamer.stream("direct", activity)
78 def create(%{to: to, actor: actor, context: context, object: object} = params) do
79 additional = params[:additional] || %{}
80 # only accept false as false value
81 local = !(params[:local] == false)
82 published = params[:published]
86 %{to: to, actor: actor, published: published, context: context, object: object},
89 {:ok, activity} <- insert(create_data, local),
90 :ok <- maybe_federate(activity),
91 {:ok, _actor} <- User.increase_note_count(actor) do
96 def accept(%{to: to, actor: actor, object: object} = params) do
97 # only accept false as false value
98 local = !(params[:local] == false)
100 with data <- %{"to" => to, "type" => "Accept", "actor" => actor, "object" => object},
101 {:ok, activity} <- insert(data, local),
102 :ok <- maybe_federate(activity) do
107 def reject(%{to: to, actor: actor, object: object} = params) do
108 # only accept false as false value
109 local = !(params[:local] == false)
111 with data <- %{"to" => to, "type" => "Reject", "actor" => actor, "object" => object},
112 {:ok, activity} <- insert(data, local),
113 :ok <- maybe_federate(activity) do
118 def update(%{to: to, cc: cc, actor: actor, object: object} = params) do
119 # only accept false as false value
120 local = !(params[:local] == false)
129 {:ok, activity} <- insert(data, local),
130 :ok <- maybe_federate(activity) do
135 # TODO: This is weird, maybe we shouldn't check here if we can make the activity.
137 %User{ap_id: ap_id} = user,
138 %Object{data: %{"id" => _}} = object,
142 with nil <- get_existing_like(ap_id, object),
143 like_data <- make_like_data(user, object, activity_id),
144 {:ok, activity} <- insert(like_data, local),
145 {:ok, object} <- add_like_to_object(activity, object),
146 :ok <- maybe_federate(activity) do
147 {:ok, activity, object}
149 %Activity{} = activity -> {:ok, activity, object}
150 error -> {:error, error}
160 with %Activity{} = like_activity <- get_existing_like(actor.ap_id, object),
161 unlike_data <- make_unlike_data(actor, like_activity, activity_id),
162 {:ok, unlike_activity} <- insert(unlike_data, local),
163 {:ok, _activity} <- Repo.delete(like_activity),
164 {:ok, object} <- remove_like_from_object(like_activity, object),
165 :ok <- maybe_federate(unlike_activity) do
166 {:ok, unlike_activity, like_activity, object}
173 %User{ap_id: _} = user,
174 %Object{data: %{"id" => _}} = object,
178 with true <- is_public?(object),
179 announce_data <- make_announce_data(user, object, activity_id),
180 {:ok, activity} <- insert(announce_data, local),
181 {:ok, object} <- add_announce_to_object(activity, object),
182 :ok <- maybe_federate(activity) do
183 {:ok, activity, object}
185 error -> {:error, error}
195 with %Activity{} = announce_activity <- get_existing_announce(actor.ap_id, object),
196 unannounce_data <- make_unannounce_data(actor, announce_activity, activity_id),
197 {:ok, unannounce_activity} <- insert(unannounce_data, local),
198 :ok <- maybe_federate(unannounce_activity),
199 {:ok, _activity} <- Repo.delete(announce_activity),
200 {:ok, object} <- remove_announce_from_object(announce_activity, object) do
201 {:ok, unannounce_activity, announce_activity, object}
207 def follow(follower, followed, activity_id \\ nil, local \\ true) do
208 with data <- make_follow_data(follower, followed, activity_id),
209 {:ok, activity} <- insert(data, local),
210 :ok <- maybe_federate(activity) do
215 def unfollow(follower, followed, activity_id \\ nil, local \\ true) do
216 with %Activity{} = follow_activity <- fetch_latest_follow(follower, followed),
217 unfollow_data <- make_unfollow_data(follower, followed, follow_activity, activity_id),
218 {:ok, activity} <- insert(unfollow_data, local),
219 :ok <- maybe_federate(activity) do
224 def delete(%Object{data: %{"id" => id, "actor" => actor}} = object, local \\ true) do
225 user = User.get_cached_by_ap_id(actor)
231 "to" => [user.follower_address, "https://www.w3.org/ns/activitystreams#Public"]
234 with Repo.delete(object),
235 Repo.delete_all(Activity.all_non_create_by_object_ap_id_q(id)),
236 {:ok, activity} <- insert(data, local),
237 :ok <- maybe_federate(activity),
238 {:ok, _actor} <- User.decrease_note_count(user) do
243 def block(blocker, blocked, activity_id \\ nil, local \\ true) do
244 follow_activity = fetch_latest_follow(blocker, blocked)
246 if follow_activity do
247 unfollow(blocker, blocked, nil, local)
250 with block_data <- make_block_data(blocker, blocked, activity_id),
251 {:ok, activity} <- insert(block_data, local),
252 :ok <- maybe_federate(activity) do
257 def unblock(blocker, blocked, activity_id \\ nil, local \\ true) do
258 with %Activity{} = block_activity <- fetch_latest_block(blocker, blocked),
259 unblock_data <- make_unblock_data(blocker, blocked, block_activity, activity_id),
260 {:ok, activity} <- insert(unblock_data, local),
261 :ok <- maybe_federate(activity) do
266 def fetch_activities_for_context(context, opts \\ %{}) do
267 public = ["https://www.w3.org/ns/activitystreams#Public"]
270 if opts["user"], do: [opts["user"].ap_id | opts["user"].following] ++ public, else: public
272 query = from(activity in Activity)
276 |> restrict_blocked(opts)
277 |> restrict_recipients(recipients, opts["user"])
284 "?->>'type' = ? and ?->>'context' = ?",
290 order_by: [desc: :id]
296 def fetch_public_activities(opts \\ %{}) do
297 q = fetch_activities_query(["https://www.w3.org/ns/activitystreams#Public"], opts)
300 |> restrict_unlisted()
305 @valid_visibilities ~w[direct unlisted public private]
307 defp restrict_visibility(query, %{visibility: "direct"}) do
308 public = "https://www.w3.org/ns/activitystreams#Public"
312 join: sender in User,
313 on: sender.ap_id == activity.actor,
314 # Are non-direct statuses with no to/cc possible?
316 fragment("not coalesce(data->'to' \\? ?, false)", ^public) and
317 fragment("not coalesce(data->'cc' \\? ?, false)", ^public) and
318 fragment("not coalesce(data->'to' \\? ?, false)", sender.follower_address)
322 defp restrict_visibility(_query, %{visibility: visibility})
323 when visibility not in @valid_visibilities do
324 Logger.error("Could not restrict visibility to #{visibility}")
327 defp restrict_visibility(query, _visibility), do: query
329 def fetch_user_activities(user, reading_user, params \\ %{}) do
332 |> Map.put("type", ["Create", "Announce"])
333 |> Map.put("actor_id", user.ap_id)
334 |> Map.put("whole_db", true)
338 ["https://www.w3.org/ns/activitystreams#Public"] ++
339 [reading_user.ap_id | reading_user.following]
341 ["https://www.w3.org/ns/activitystreams#Public"]
344 fetch_activities(recipients, params)
348 defp restrict_since(query, %{"since_id" => since_id}) do
349 from(activity in query, where: activity.id > ^since_id)
352 defp restrict_since(query, _), do: query
354 defp restrict_tag(query, %{"tag" => tag}) do
357 where: fragment("? <@ (? #> '{\"object\",\"tag\"}')", ^tag, activity.data)
361 defp restrict_tag(query, _), do: query
363 defp restrict_recipients(query, [], _user), do: query
365 defp restrict_recipients(query, recipients, nil) do
366 from(activity in query, where: fragment("? && ?", ^recipients, activity.recipients))
369 defp restrict_recipients(query, recipients, user) do
372 where: fragment("? && ?", ^recipients, activity.recipients),
373 or_where: activity.actor == ^user.ap_id
377 defp restrict_limit(query, %{"limit" => limit}) do
378 from(activity in query, limit: ^limit)
381 defp restrict_limit(query, _), do: query
383 defp restrict_local(query, %{"local_only" => true}) do
384 from(activity in query, where: activity.local == true)
387 defp restrict_local(query, _), do: query
389 defp restrict_max(query, %{"max_id" => max_id}) do
390 from(activity in query, where: activity.id < ^max_id)
393 defp restrict_max(query, _), do: query
395 defp restrict_actor(query, %{"actor_id" => actor_id}) do
396 from(activity in query, where: activity.actor == ^actor_id)
399 defp restrict_actor(query, _), do: query
401 defp restrict_type(query, %{"type" => type}) when is_binary(type) do
402 restrict_type(query, %{"type" => [type]})
405 defp restrict_type(query, %{"type" => type}) do
406 from(activity in query, where: fragment("?->>'type' = ANY(?)", activity.data, ^type))
409 defp restrict_type(query, _), do: query
411 defp restrict_favorited_by(query, %{"favorited_by" => ap_id}) do
414 where: fragment("? <@ (? #> '{\"object\",\"likes\"}')", ^ap_id, activity.data)
418 defp restrict_favorited_by(query, _), do: query
420 defp restrict_media(query, %{"only_media" => val}) when val == "true" or val == "1" do
423 where: fragment("not (? #> '{\"object\",\"attachment\"}' = ?)", activity.data, ^[])
427 defp restrict_media(query, _), do: query
429 # Only search through last 100_000 activities by default
430 defp restrict_recent(query, %{"whole_db" => true}), do: query
432 defp restrict_recent(query, _) do
433 since = (Repo.aggregate(Activity, :max, :id) || 0) - 100_000
435 from(activity in query, where: activity.id > ^since)
438 defp restrict_blocked(query, %{"blocking_user" => %User{info: info}}) do
439 blocks = info["blocks"] || []
443 where: fragment("not (? = ANY(?))", activity.actor, ^blocks),
444 where: fragment("not (?->'to' \\?| ?)", activity.data, ^blocks)
448 defp restrict_blocked(query, _), do: query
450 defp restrict_unlisted(query) do
455 "not (coalesce(?->'cc', '{}'::jsonb) \\?| ?)",
457 ^["https://www.w3.org/ns/activitystreams#Public"]
462 def fetch_activities_query(recipients, opts \\ %{}) do
465 activity in Activity,
467 order_by: [fragment("? desc nulls last", activity.id)]
471 |> restrict_recipients(recipients, opts["user"])
472 |> restrict_tag(opts)
473 |> restrict_since(opts)
474 |> restrict_local(opts)
475 |> restrict_limit(opts)
476 |> restrict_max(opts)
477 |> restrict_actor(opts)
478 |> restrict_type(opts)
479 |> restrict_favorited_by(opts)
480 |> restrict_recent(opts)
481 |> restrict_blocked(opts)
482 |> restrict_media(opts)
483 |> restrict_visibility(opts)
486 def fetch_activities(recipients, opts \\ %{}) do
487 fetch_activities_query(recipients, opts)
493 data = Upload.store(file)
494 Repo.insert(%Object{data: data})
497 def user_data_from_user_object(data) do
499 data["icon"]["url"] &&
502 "url" => [%{"href" => data["icon"]["url"]}]
506 data["image"]["url"] &&
509 "url" => [%{"href" => data["image"]["url"]}]
512 locked = data["manuallyApprovesFollowers"] || false
513 data = Transmogrifier.maybe_fix_user_object(data)
518 "ap_enabled" => true,
519 "source_data" => data,
524 nickname: "#{data["preferredUsername"]}@#{URI.parse(data["id"]).host}",
526 follower_address: data["followers"],
533 def fetch_and_prepare_user_from_ap_id(ap_id) do
534 with {:ok, %{status_code: 200, body: body}} <-
535 @httpoison.get(ap_id, Accept: "application/activity+json"),
536 {:ok, data} <- Jason.decode(body) do
537 user_data_from_user_object(data)
539 e -> Logger.error("Could not decode user at fetch #{ap_id}, #{inspect(e)}")
543 def make_user_from_ap_id(ap_id) do
544 if _user = User.get_by_ap_id(ap_id) do
545 Transmogrifier.upgrade_user_from_ap_id(ap_id)
547 with {:ok, data} <- fetch_and_prepare_user_from_ap_id(ap_id) do
548 User.insert_or_update_user(data)
555 def make_user_from_nickname(nickname) do
556 with {:ok, %{"ap_id" => ap_id}} when not is_nil(ap_id) <- WebFinger.finger(nickname) do
557 make_user_from_ap_id(ap_id)
559 _e -> {:error, "No AP id in WebFinger"}
563 def publish(actor, activity) do
565 if actor.follower_address in activity.recipients do
566 {:ok, followers} = User.get_followers(actor)
567 followers |> Enum.filter(&(!&1.local))
573 (Pleroma.Web.Salmon.remote_users(activity) ++ followers)
574 |> Enum.filter(fn user -> User.ap_enabled?(user) end)
575 |> Enum.map(fn %{info: %{"source_data" => data}} ->
576 (data["endpoints"] && data["endpoints"]["sharedInbox"]) || data["inbox"]
580 {:ok, data} = Transmogrifier.prepare_outgoing(activity.data)
581 json = Jason.encode!(data)
583 Enum.each(remote_inboxes, fn inbox ->
584 Federator.enqueue(:publish_single_ap, %{
588 id: activity.data["id"]
593 def publish_one(%{inbox: inbox, json: json, actor: actor, id: id}) do
594 Logger.info("Federating #{id} to #{inbox}")
595 host = URI.parse(inbox).host
598 Pleroma.Web.HTTPSignatures.sign(actor, %{host: host, "content-length": byte_size(json)})
603 [{"Content-Type", "application/activity+json"}, {"signature", signature}],
604 hackney: [pool: :default]
609 # This will create a Create activity, which we need internally at the moment.
610 def fetch_object_from_id(id) do
611 if object = Object.get_cached_by_ap_id(id) do
614 Logger.info("Fetching #{id} via AP")
616 with true <- String.starts_with?(id, "http"),
617 {:ok, %{body: body, status_code: code}} when code in 200..299 <-
620 [Accept: "application/activity+json"],
621 follow_redirect: true,
625 {:ok, data} <- Jason.decode(body),
626 nil <- Object.get_by_ap_id(data["id"]),
631 "actor" => data["attributedTo"],
634 {:ok, activity} <- Transmogrifier.handle_incoming(params) do
635 {:ok, Object.get_by_ap_id(activity.data["object"]["id"])}
637 object = %Object{} ->
641 Logger.info("Couldn't get object via AP, trying out OStatus fetching...")
643 case OStatus.fetch_activity_from_url(id) do
644 {:ok, [activity | _]} -> {:ok, Object.get_by_ap_id(activity.data["object"]["id"])}
651 def is_public?(activity) do
652 "https://www.w3.org/ns/activitystreams#Public" in (activity.data["to"] ++
653 (activity.data["cc"] || []))
656 def visible_for_user?(activity, nil) do
660 def visible_for_user?(activity, user) do
661 x = [user.ap_id | user.following]
662 y = activity.data["to"] ++ (activity.data["cc"] || [])
663 visible_for_user?(activity, nil) || Enum.any?(x, &(&1 in y))