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?
318 [^public, sender.follower_address],
324 defp restrict_visibility(_query, %{visibility: visibility})
325 when visibility not in @valid_visibilities do
326 Logger.error("Could not restrict visibility to #{visibility}")
329 defp restrict_visibility(query, _visibility), do: query
331 def fetch_user_activities(user, reading_user, params \\ %{}) do
334 |> Map.put("type", ["Create", "Announce"])
335 |> Map.put("actor_id", user.ap_id)
336 |> Map.put("whole_db", true)
340 ["https://www.w3.org/ns/activitystreams#Public"] ++
341 [reading_user.ap_id | reading_user.following]
343 ["https://www.w3.org/ns/activitystreams#Public"]
346 fetch_activities(recipients, params)
350 defp restrict_since(query, %{"since_id" => since_id}) do
351 from(activity in query, where: activity.id > ^since_id)
354 defp restrict_since(query, _), do: query
356 defp restrict_tag(query, %{"tag" => tag}) do
359 where: fragment("? <@ (? #> '{\"object\",\"tag\"}')", ^tag, activity.data)
363 defp restrict_tag(query, _), do: query
365 defp restrict_recipients(query, [], _user), do: query
367 defp restrict_recipients(query, recipients, nil) do
368 from(activity in query, where: fragment("? && ?", ^recipients, activity.recipients))
371 defp restrict_recipients(query, recipients, user) do
374 where: fragment("? && ?", ^recipients, activity.recipients),
375 or_where: activity.actor == ^user.ap_id
379 defp restrict_limit(query, %{"limit" => limit}) do
380 from(activity in query, limit: ^limit)
383 defp restrict_limit(query, _), do: query
385 defp restrict_local(query, %{"local_only" => true}) do
386 from(activity in query, where: activity.local == true)
389 defp restrict_local(query, _), do: query
391 defp restrict_max(query, %{"max_id" => max_id}) do
392 from(activity in query, where: activity.id < ^max_id)
395 defp restrict_max(query, _), do: query
397 defp restrict_actor(query, %{"actor_id" => actor_id}) do
398 from(activity in query, where: activity.actor == ^actor_id)
401 defp restrict_actor(query, _), do: query
403 defp restrict_type(query, %{"type" => type}) when is_binary(type) do
404 restrict_type(query, %{"type" => [type]})
407 defp restrict_type(query, %{"type" => type}) do
408 from(activity in query, where: fragment("?->>'type' = ANY(?)", activity.data, ^type))
411 defp restrict_type(query, _), do: query
413 defp restrict_favorited_by(query, %{"favorited_by" => ap_id}) do
416 where: fragment("? <@ (? #> '{\"object\",\"likes\"}')", ^ap_id, activity.data)
420 defp restrict_favorited_by(query, _), do: query
422 defp restrict_media(query, %{"only_media" => val}) when val == "true" or val == "1" do
425 where: fragment("not (? #> '{\"object\",\"attachment\"}' = ?)", activity.data, ^[])
429 defp restrict_media(query, _), do: query
431 # Only search through last 100_000 activities by default
432 defp restrict_recent(query, %{"whole_db" => true}), do: query
434 defp restrict_recent(query, _) do
435 since = (Repo.aggregate(Activity, :max, :id) || 0) - 100_000
437 from(activity in query, where: activity.id > ^since)
440 defp restrict_blocked(query, %{"blocking_user" => %User{info: info}}) do
441 blocks = info["blocks"] || []
442 domain_blocks = info["domain_blocks"] || []
446 where: fragment("not (? = ANY(?))", activity.actor, ^blocks),
447 where: fragment("not (?->'to' \\?| ?)", activity.data, ^blocks),
448 where: fragment("not (split_part(?, '/', 3) = ANY(?))", activity.actor, ^domain_blocks)
452 defp restrict_blocked(query, _), do: query
454 defp restrict_unlisted(query) do
459 "not (coalesce(?->'cc', '{}'::jsonb) \\?| ?)",
461 ^["https://www.w3.org/ns/activitystreams#Public"]
466 def fetch_activities_query(recipients, opts \\ %{}) do
469 activity in Activity,
471 order_by: [fragment("? desc nulls last", activity.id)]
475 |> restrict_recipients(recipients, opts["user"])
476 |> restrict_tag(opts)
477 |> restrict_since(opts)
478 |> restrict_local(opts)
479 |> restrict_limit(opts)
480 |> restrict_max(opts)
481 |> restrict_actor(opts)
482 |> restrict_type(opts)
483 |> restrict_favorited_by(opts)
484 |> restrict_recent(opts)
485 |> restrict_blocked(opts)
486 |> restrict_media(opts)
487 |> restrict_visibility(opts)
490 def fetch_activities(recipients, opts \\ %{}) do
491 fetch_activities_query(recipients, opts)
497 data = Upload.store(file)
498 Repo.insert(%Object{data: data})
501 def user_data_from_user_object(data) do
503 data["icon"]["url"] &&
506 "url" => [%{"href" => data["icon"]["url"]}]
510 data["image"]["url"] &&
513 "url" => [%{"href" => data["image"]["url"]}]
516 locked = data["manuallyApprovesFollowers"] || false
517 data = Transmogrifier.maybe_fix_user_object(data)
522 "ap_enabled" => true,
523 "source_data" => data,
528 nickname: "#{data["preferredUsername"]}@#{URI.parse(data["id"]).host}",
530 follower_address: data["followers"],
537 def fetch_and_prepare_user_from_ap_id(ap_id) do
538 with {:ok, %{status_code: 200, body: body}} <-
539 @httpoison.get(ap_id, Accept: "application/activity+json"),
540 {:ok, data} <- Jason.decode(body) do
541 user_data_from_user_object(data)
543 e -> Logger.error("Could not decode user at fetch #{ap_id}, #{inspect(e)}")
547 def make_user_from_ap_id(ap_id) do
548 if _user = User.get_by_ap_id(ap_id) do
549 Transmogrifier.upgrade_user_from_ap_id(ap_id)
551 with {:ok, data} <- fetch_and_prepare_user_from_ap_id(ap_id) do
552 User.insert_or_update_user(data)
559 def make_user_from_nickname(nickname) do
560 with {:ok, %{"ap_id" => ap_id}} when not is_nil(ap_id) <- WebFinger.finger(nickname) do
561 make_user_from_ap_id(ap_id)
563 _e -> {:error, "No AP id in WebFinger"}
567 @quarantined_instances Keyword.get(@instance, :quarantined_instances, [])
569 def should_federate?(inbox, public) do
573 inbox_info = URI.parse(inbox)
574 inbox_info.host not in @quarantined_instances
578 def publish(actor, activity) do
580 if actor.follower_address in activity.recipients do
581 {:ok, followers} = User.get_followers(actor)
582 followers |> Enum.filter(&(!&1.local))
587 public = is_public?(activity)
590 (Pleroma.Web.Salmon.remote_users(activity) ++ followers)
591 |> Enum.filter(fn user -> User.ap_enabled?(user) end)
592 |> Enum.map(fn %{info: %{"source_data" => data}} ->
593 (data["endpoints"] && data["endpoints"]["sharedInbox"]) || data["inbox"]
596 |> Enum.filter(fn inbox -> should_federate?(inbox, public) end)
598 {:ok, data} = Transmogrifier.prepare_outgoing(activity.data)
599 json = Jason.encode!(data)
601 Enum.each(remote_inboxes, fn inbox ->
602 Federator.enqueue(:publish_single_ap, %{
606 id: activity.data["id"]
611 def publish_one(%{inbox: inbox, json: json, actor: actor, id: id}) do
612 Logger.info("Federating #{id} to #{inbox}")
613 host = URI.parse(inbox).host
616 Pleroma.Web.HTTPSignatures.sign(actor, %{host: host, "content-length": byte_size(json)})
621 [{"Content-Type", "application/activity+json"}, {"signature", signature}],
622 hackney: [pool: :default]
627 # This will create a Create activity, which we need internally at the moment.
628 def fetch_object_from_id(id) do
629 if object = Object.get_cached_by_ap_id(id) do
632 Logger.info("Fetching #{id} via AP")
634 with true <- String.starts_with?(id, "http"),
635 {:ok, %{body: body, status_code: code}} when code in 200..299 <-
638 [Accept: "application/activity+json"],
639 follow_redirect: true,
643 {:ok, data} <- Jason.decode(body),
644 nil <- Object.get_by_ap_id(data["id"]),
649 "actor" => data["attributedTo"],
652 {:ok, activity} <- Transmogrifier.handle_incoming(params) do
653 {:ok, Object.get_by_ap_id(activity.data["object"]["id"])}
655 object = %Object{} ->
659 Logger.info("Couldn't get object via AP, trying out OStatus fetching...")
661 case OStatus.fetch_activity_from_url(id) do
662 {:ok, [activity | _]} -> {:ok, Object.get_by_ap_id(activity.data["object"]["id"])}
669 def is_public?(activity) do
670 "https://www.w3.org/ns/activitystreams#Public" in (activity.data["to"] ++
671 (activity.data["cc"] || []))
674 def visible_for_user?(activity, nil) do
678 def visible_for_user?(activity, user) do
679 x = [user.ap_id | user.following]
680 y = activity.data["to"] ++ (activity.data["cc"] || [])
681 visible_for_user?(activity, nil) || Enum.any?(x, &(&1 in y))