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 def get_recipients(data) do
14 (data["to"] || []) ++ (data["cc"] || [])
17 def insert(map, local \\ true) when is_map(map) do
18 with nil <- Activity.get_by_ap_id(map["id"]),
19 map <- lazy_put_activity_defaults(map),
20 :ok <- insert_full_object(map) do
22 Repo.insert(%Activity{
26 recipients: get_recipients(map)
29 Notification.create_notifications(activity)
33 %Activity{} = activity -> {:ok, activity}
34 error -> {:error, error}
38 def stream_out(activity) do
39 if activity.data["type"] in ["Create", "Announce"] do
40 Pleroma.Web.Streamer.stream("user", activity)
42 if Enum.member?(activity.data["to"], "https://www.w3.org/ns/activitystreams#Public") do
43 Pleroma.Web.Streamer.stream("public", activity)
46 Pleroma.Web.Streamer.stream("public:local", activity)
52 def create(%{to: to, actor: actor, context: context, object: object} = params) do
53 additional = params[:additional] || %{}
54 # only accept false as false value
55 local = !(params[:local] == false)
56 published = params[:published]
60 %{to: to, actor: actor, published: published, context: context, object: object},
63 {:ok, activity} <- insert(create_data, local),
64 :ok <- maybe_federate(activity) do
69 def accept(%{to: to, actor: actor, object: object} = params) do
70 # only accept false as false value
71 local = !(params[:local] == false)
73 with data <- %{"to" => to, "type" => "Accept", "actor" => actor, "object" => object},
74 {:ok, activity} <- insert(data, local),
75 :ok <- maybe_federate(activity) do
80 def update(%{to: to, cc: cc, actor: actor, object: object} = params) do
81 # only accept false as false value
82 local = !(params[:local] == false)
91 {:ok, activity} <- insert(data, local),
92 :ok <- maybe_federate(activity) do
97 # TODO: This is weird, maybe we shouldn't check here if we can make the activity.
99 %User{ap_id: ap_id} = user,
100 %Object{data: %{"id" => _}} = object,
104 with nil <- get_existing_like(ap_id, object),
105 like_data <- make_like_data(user, object, activity_id),
106 {:ok, activity} <- insert(like_data, local),
107 {:ok, object} <- add_like_to_object(activity, object),
108 :ok <- maybe_federate(activity) do
109 {:ok, activity, object}
111 %Activity{} = activity -> {:ok, activity, object}
112 error -> {:error, error}
116 def unlike(%User{} = actor, %Object{} = object) do
117 with %Activity{} = activity <- get_existing_like(actor.ap_id, object),
118 {:ok, _activity} <- Repo.delete(activity),
119 {:ok, object} <- remove_like_from_object(activity, object) do
127 %User{ap_id: _} = user,
128 %Object{data: %{"id" => _}} = object,
132 with true <- is_public?(object),
133 announce_data <- make_announce_data(user, object, activity_id),
134 {:ok, activity} <- insert(announce_data, local),
135 {:ok, object} <- add_announce_to_object(activity, object),
136 :ok <- maybe_federate(activity) do
137 {:ok, activity, object}
139 error -> {:error, error}
143 def unannounce(%User{} = actor, %Object{} = object, local \\ true) do
144 with %Activity{} = activity <- get_existing_announce(actor.ap_id, object),
145 unannounce_data <- make_unannounce_data(actor, object),
146 {:ok, unannounce_activity} <- insert(unannounce_data, local),
147 {:ok, _activity} <- Repo.delete(activity),
148 {:ok, object} <- remove_announce_from_object(activity, object) do
149 {:ok, unannounce_activity, activity, object}
155 def follow(follower, followed, activity_id \\ nil, local \\ true) do
156 with data <- make_follow_data(follower, followed, activity_id),
157 {:ok, activity} <- insert(data, local),
158 :ok <- maybe_federate(activity) do
163 def unfollow(follower, followed, local \\ true) do
164 with %Activity{} = follow_activity <- fetch_latest_follow(follower, followed),
165 unfollow_data <- make_unfollow_data(follower, followed, follow_activity),
166 {:ok, activity} <- insert(unfollow_data, local),
168 maybe_federate(activity) do
173 def delete(%Object{data: %{"id" => id, "actor" => actor}} = object, local \\ true) do
174 user = User.get_cached_by_ap_id(actor)
180 "to" => [user.follower_address, "https://www.w3.org/ns/activitystreams#Public"]
183 with Repo.delete(object),
184 Repo.delete_all(Activity.all_non_create_by_object_ap_id_q(id)),
185 {:ok, activity} <- insert(data, local),
186 :ok <- maybe_federate(activity) do
191 def fetch_activities_for_context(context, opts \\ %{}) do
192 public = ["https://www.w3.org/ns/activitystreams#Public"]
195 if opts["user"], do: [opts["user"].ap_id | opts["user"].following] ++ public, else: public
197 query = from(activity in Activity)
201 |> restrict_blocked(opts)
202 |> restrict_recipients(recipients, opts["user"])
209 "?->>'type' = ? and ?->>'context' = ?",
215 order_by: [desc: :id]
221 # TODO: Make this work properly with unlisted.
222 def fetch_public_activities(opts \\ %{}) do
223 q = fetch_activities_query(["https://www.w3.org/ns/activitystreams#Public"], opts)
230 defp restrict_since(query, %{"since_id" => since_id}) do
231 from(activity in query, where: activity.id > ^since_id)
234 defp restrict_since(query, _), do: query
236 defp restrict_tag(query, %{"tag" => tag}) do
239 where: fragment("? <@ (? #> '{\"object\",\"tag\"}')", ^tag, activity.data)
243 defp restrict_tag(query, _), do: query
245 defp restrict_recipients(query, [], user), do: query
247 defp restrict_recipients(query, recipients, nil) do
248 from(activity in query, where: fragment("? && ?", ^recipients, activity.recipients))
251 defp restrict_recipients(query, recipients, user) do
254 where: fragment("? && ?", ^recipients, activity.recipients),
255 or_where: activity.actor == ^user.ap_id
259 defp restrict_limit(query, %{"limit" => limit}) do
260 from(activity in query, limit: ^limit)
263 defp restrict_limit(query, _), do: query
265 defp restrict_local(query, %{"local_only" => true}) do
266 from(activity in query, where: activity.local == true)
269 defp restrict_local(query, _), do: query
271 defp restrict_max(query, %{"max_id" => max_id}) do
272 from(activity in query, where: activity.id < ^max_id)
275 defp restrict_max(query, _), do: query
277 defp restrict_actor(query, %{"actor_id" => actor_id}) do
278 from(activity in query, where: activity.actor == ^actor_id)
281 defp restrict_actor(query, _), do: query
283 defp restrict_type(query, %{"type" => type}) when is_binary(type) do
284 restrict_type(query, %{"type" => [type]})
287 defp restrict_type(query, %{"type" => type}) do
288 from(activity in query, where: fragment("?->>'type' = ANY(?)", activity.data, ^type))
291 defp restrict_type(query, _), do: query
293 defp restrict_favorited_by(query, %{"favorited_by" => ap_id}) do
296 where: fragment("? <@ (? #> '{\"object\",\"likes\"}')", ^ap_id, activity.data)
300 defp restrict_favorited_by(query, _), do: query
302 defp restrict_media(query, %{"only_media" => val}) when val == "true" or val == "1" do
305 where: fragment("not (? #> '{\"object\",\"attachment\"}' = ?)", activity.data, ^[])
309 defp restrict_media(query, _), do: query
311 # Only search through last 100_000 activities by default
312 defp restrict_recent(query, %{"whole_db" => true}), do: query
314 defp restrict_recent(query, _) do
315 since = (Repo.aggregate(Activity, :max, :id) || 0) - 100_000
317 from(activity in query, where: activity.id > ^since)
320 defp restrict_blocked(query, %{"blocking_user" => %User{info: info}}) do
321 blocks = info["blocks"] || []
322 from(activity in query, where: fragment("not (? = ANY(?))", activity.actor, ^blocks))
325 defp restrict_blocked(query, _), do: query
327 def fetch_activities_query(recipients, opts \\ %{}) do
330 activity in Activity,
332 order_by: [fragment("? desc nulls last", activity.id)]
336 |> restrict_recipients(recipients, opts["user"])
337 |> restrict_tag(opts)
338 |> restrict_since(opts)
339 |> restrict_local(opts)
340 |> restrict_limit(opts)
341 |> restrict_max(opts)
342 |> restrict_actor(opts)
343 |> restrict_type(opts)
344 |> restrict_favorited_by(opts)
345 |> restrict_recent(opts)
346 |> restrict_blocked(opts)
347 |> restrict_media(opts)
350 def fetch_activities(recipients, opts \\ %{}) do
351 fetch_activities_query(recipients, opts)
357 data = Upload.store(file)
358 Repo.insert(%Object{data: data})
361 def user_data_from_user_object(data) do
363 data["icon"]["url"] &&
366 "url" => [%{"href" => data["icon"]["url"]}]
370 data["image"]["url"] &&
373 "url" => [%{"href" => data["image"]["url"]}]
379 "ap_enabled" => true,
380 "source_data" => data,
384 nickname: "#{data["preferredUsername"]}@#{URI.parse(data["id"]).host}",
386 follower_address: data["followers"],
393 def fetch_and_prepare_user_from_ap_id(ap_id) do
394 with {:ok, %{status_code: 200, body: body}} <-
395 @httpoison.get(ap_id, Accept: "application/activity+json"),
396 {:ok, data} <- Jason.decode(body) do
397 user_data_from_user_object(data)
399 e -> Logger.error("Could not decode user at fetch #{ap_id}, #{inspect(e)}")
403 def make_user_from_ap_id(ap_id) do
404 if user = User.get_by_ap_id(ap_id) do
405 Transmogrifier.upgrade_user_from_ap_id(ap_id)
407 with {:ok, data} <- fetch_and_prepare_user_from_ap_id(ap_id) do
408 User.insert_or_update_user(data)
415 def make_user_from_nickname(nickname) do
416 with {:ok, %{"ap_id" => ap_id}} when not is_nil(ap_id) <- WebFinger.finger(nickname) do
417 make_user_from_ap_id(ap_id)
419 _e -> {:error, "No AP id in WebFinger"}
423 def publish(actor, activity) do
425 if actor.follower_address in activity.recipients do
426 {:ok, followers} = User.get_followers(actor)
427 followers |> Enum.filter(&(!&1.local))
433 (Pleroma.Web.Salmon.remote_users(activity) ++ followers)
434 |> Enum.filter(fn user -> User.ap_enabled?(user) end)
435 |> Enum.map(fn %{info: %{"source_data" => data}} ->
436 (data["endpoints"] && data["endpoints"]["sharedInbox"]) || data["inbox"]
440 {:ok, data} = Transmogrifier.prepare_outgoing(activity.data)
441 json = Jason.encode!(data)
443 Enum.each(remote_inboxes, fn inbox ->
444 Federator.enqueue(:publish_single_ap, %{
448 id: activity.data["id"]
453 def publish_one(%{inbox: inbox, json: json, actor: actor, id: id}) do
454 Logger.info("Federating #{id} to #{inbox}")
455 host = URI.parse(inbox).host
458 Pleroma.Web.HTTPSignatures.sign(actor, %{host: host, "content-length": byte_size(json)})
463 [{"Content-Type", "application/activity+json"}, {"signature", signature}],
464 hackney: [pool: :default]
469 # This will create a Create activity, which we need internally at the moment.
470 def fetch_object_from_id(id) do
471 if object = Object.get_cached_by_ap_id(id) do
474 Logger.info("Fetching #{id} via AP")
476 with true <- String.starts_with?(id, "http"),
477 {:ok, %{body: body, status_code: code}} when code in 200..299 <-
480 [Accept: "application/activity+json"],
481 follow_redirect: true,
485 {:ok, data} <- Jason.decode(body),
486 nil <- Object.get_by_ap_id(data["id"]),
491 "actor" => data["attributedTo"],
494 {:ok, activity} <- Transmogrifier.handle_incoming(params) do
495 {:ok, Object.get_by_ap_id(activity.data["object"]["id"])}
497 object = %Object{} ->
501 Logger.info("Couldn't get object via AP, trying out OStatus fetching...")
503 case OStatus.fetch_activity_from_url(id) do
504 {:ok, [activity | _]} -> {:ok, Object.get_by_ap_id(activity.data["object"]["id"])}
511 def is_public?(activity) do
512 "https://www.w3.org/ns/activitystreams#Public" in (activity.data["to"] ++
513 (activity.data["cc"] || []))
516 def visible_for_user?(activity, nil) do
520 def visible_for_user?(activity, user) do
521 x = [user.ap_id | user.following]
522 y = activity.data["to"] ++ (activity.data["cc"] || [])
523 visible_for_user?(activity, nil) || Enum.any?(x, &(&1 in y))