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),
65 {:ok, actor} <- User.increase_note_count(actor) do
70 def accept(%{to: to, actor: actor, object: object} = params) do
71 # only accept false as false value
72 local = !(params[:local] == false)
74 with data <- %{"to" => to, "type" => "Accept", "actor" => actor, "object" => object},
75 {:ok, activity} <- insert(data, local),
76 :ok <- maybe_federate(activity) do
81 def update(%{to: to, cc: cc, actor: actor, object: object} = params) do
82 # only accept false as false value
83 local = !(params[:local] == false)
92 {:ok, activity} <- insert(data, local),
93 :ok <- maybe_federate(activity) do
98 # TODO: This is weird, maybe we shouldn't check here if we can make the activity.
100 %User{ap_id: ap_id} = user,
101 %Object{data: %{"id" => _}} = object,
105 with nil <- get_existing_like(ap_id, object),
106 like_data <- make_like_data(user, object, activity_id),
107 {:ok, activity} <- insert(like_data, local),
108 {:ok, object} <- add_like_to_object(activity, object),
109 :ok <- maybe_federate(activity) do
110 {:ok, activity, object}
112 %Activity{} = activity -> {:ok, activity, object}
113 error -> {:error, error}
117 def unlike(%User{} = actor, %Object{} = object) do
118 with %Activity{} = activity <- get_existing_like(actor.ap_id, object),
119 {:ok, _activity} <- Repo.delete(activity),
120 {:ok, object} <- remove_like_from_object(activity, object) do
128 %User{ap_id: _} = user,
129 %Object{data: %{"id" => _}} = object,
133 with true <- is_public?(object),
134 announce_data <- make_announce_data(user, object, activity_id),
135 {:ok, activity} <- insert(announce_data, local),
136 {:ok, object} <- add_announce_to_object(activity, object),
137 :ok <- maybe_federate(activity) do
138 {:ok, activity, object}
140 error -> {:error, error}
144 def follow(follower, followed, activity_id \\ nil, local \\ true) do
145 with data <- make_follow_data(follower, followed, activity_id),
146 {:ok, activity} <- insert(data, local),
147 :ok <- maybe_federate(activity) do
152 def unfollow(follower, followed, local \\ true) do
153 with %Activity{} = follow_activity <- fetch_latest_follow(follower, followed),
154 unfollow_data <- make_unfollow_data(follower, followed, follow_activity),
155 {:ok, activity} <- insert(unfollow_data, local),
157 maybe_federate(activity) do
162 def delete(%Object{data: %{"id" => id, "actor" => actor}} = object, local \\ true) do
163 user = User.get_cached_by_ap_id(actor)
169 "to" => [user.follower_address, "https://www.w3.org/ns/activitystreams#Public"]
172 with Repo.delete(object),
173 Repo.delete_all(Activity.all_non_create_by_object_ap_id_q(id)),
174 {:ok, activity} <- insert(data, local),
175 :ok <- maybe_federate(activity),
176 {:ok, actor} <- User.decrease_note_count(user) do
181 def fetch_activities_for_context(context, opts \\ %{}) do
182 public = ["https://www.w3.org/ns/activitystreams#Public"]
185 if opts["user"], do: [opts["user"].ap_id | opts["user"].following] ++ public, else: public
187 query = from(activity in Activity)
191 |> restrict_blocked(opts)
192 |> restrict_recipients(recipients, opts["user"])
199 "?->>'type' = ? and ?->>'context' = ?",
205 order_by: [desc: :id]
211 # TODO: Make this work properly with unlisted.
212 def fetch_public_activities(opts \\ %{}) do
213 q = fetch_activities_query(["https://www.w3.org/ns/activitystreams#Public"], opts)
220 defp restrict_since(query, %{"since_id" => since_id}) do
221 from(activity in query, where: activity.id > ^since_id)
224 defp restrict_since(query, _), do: query
226 defp restrict_tag(query, %{"tag" => tag}) do
229 where: fragment("? <@ (? #> '{\"object\",\"tag\"}')", ^tag, activity.data)
233 defp restrict_tag(query, _), do: query
235 defp restrict_recipients(query, [], user), do: query
237 defp restrict_recipients(query, recipients, nil) do
238 from(activity in query, where: fragment("? && ?", ^recipients, activity.recipients))
241 defp restrict_recipients(query, recipients, user) do
244 where: fragment("? && ?", ^recipients, activity.recipients),
245 or_where: activity.actor == ^user.ap_id
249 defp restrict_limit(query, %{"limit" => limit}) do
250 from(activity in query, limit: ^limit)
253 defp restrict_limit(query, _), do: query
255 defp restrict_local(query, %{"local_only" => true}) do
256 from(activity in query, where: activity.local == true)
259 defp restrict_local(query, _), do: query
261 defp restrict_max(query, %{"max_id" => max_id}) do
262 from(activity in query, where: activity.id < ^max_id)
265 defp restrict_max(query, _), do: query
267 defp restrict_actor(query, %{"actor_id" => actor_id}) do
268 from(activity in query, where: activity.actor == ^actor_id)
271 defp restrict_actor(query, _), do: query
273 defp restrict_type(query, %{"type" => type}) when is_binary(type) do
274 restrict_type(query, %{"type" => [type]})
277 defp restrict_type(query, %{"type" => type}) do
278 from(activity in query, where: fragment("?->>'type' = ANY(?)", activity.data, ^type))
281 defp restrict_type(query, _), do: query
283 defp restrict_favorited_by(query, %{"favorited_by" => ap_id}) do
286 where: fragment("? <@ (? #> '{\"object\",\"likes\"}')", ^ap_id, activity.data)
290 defp restrict_favorited_by(query, _), do: query
292 defp restrict_media(query, %{"only_media" => val}) when val == "true" or val == "1" do
295 where: fragment("not (? #> '{\"object\",\"attachment\"}' = ?)", activity.data, ^[])
299 defp restrict_media(query, _), do: query
301 # Only search through last 100_000 activities by default
302 defp restrict_recent(query, %{"whole_db" => true}), do: query
304 defp restrict_recent(query, _) do
305 since = (Repo.aggregate(Activity, :max, :id) || 0) - 100_000
307 from(activity in query, where: activity.id > ^since)
310 defp restrict_blocked(query, %{"blocking_user" => %User{info: info}}) do
311 blocks = info["blocks"] || []
312 from(activity in query, where: fragment("not (? = ANY(?))", activity.actor, ^blocks))
315 defp restrict_blocked(query, _), do: query
317 def fetch_activities_query(recipients, opts \\ %{}) do
320 activity in Activity,
322 order_by: [fragment("? desc nulls last", activity.id)]
326 |> restrict_recipients(recipients, opts["user"])
327 |> restrict_tag(opts)
328 |> restrict_since(opts)
329 |> restrict_local(opts)
330 |> restrict_limit(opts)
331 |> restrict_max(opts)
332 |> restrict_actor(opts)
333 |> restrict_type(opts)
334 |> restrict_favorited_by(opts)
335 |> restrict_recent(opts)
336 |> restrict_blocked(opts)
337 |> restrict_media(opts)
340 def fetch_activities(recipients, opts \\ %{}) do
341 fetch_activities_query(recipients, opts)
347 data = Upload.store(file)
348 Repo.insert(%Object{data: data})
351 def user_data_from_user_object(data) do
353 data["icon"]["url"] &&
356 "url" => [%{"href" => data["icon"]["url"]}]
360 data["image"]["url"] &&
363 "url" => [%{"href" => data["image"]["url"]}]
369 "ap_enabled" => true,
370 "source_data" => data,
374 nickname: "#{data["preferredUsername"]}@#{URI.parse(data["id"]).host}",
376 follower_address: data["followers"],
383 def fetch_and_prepare_user_from_ap_id(ap_id) do
384 with {:ok, %{status_code: 200, body: body}} <-
385 @httpoison.get(ap_id, Accept: "application/activity+json"),
386 {:ok, data} <- Jason.decode(body) do
387 user_data_from_user_object(data)
389 e -> Logger.error("Could not decode user at fetch #{ap_id}, #{inspect(e)}")
393 def make_user_from_ap_id(ap_id) do
394 if user = User.get_by_ap_id(ap_id) do
395 Transmogrifier.upgrade_user_from_ap_id(ap_id)
397 with {:ok, data} <- fetch_and_prepare_user_from_ap_id(ap_id) do
398 User.insert_or_update_user(data)
405 def make_user_from_nickname(nickname) do
406 with {:ok, %{"ap_id" => ap_id}} when not is_nil(ap_id) <- WebFinger.finger(nickname) do
407 make_user_from_ap_id(ap_id)
409 _e -> {:error, "No AP id in WebFinger"}
413 def publish(actor, activity) do
415 if actor.follower_address in activity.recipients do
416 {:ok, followers} = User.get_followers(actor)
417 followers |> Enum.filter(&(!&1.local))
423 (Pleroma.Web.Salmon.remote_users(activity) ++ followers)
424 |> Enum.filter(fn user -> User.ap_enabled?(user) end)
425 |> Enum.map(fn %{info: %{"source_data" => data}} ->
426 (data["endpoints"] && data["endpoints"]["sharedInbox"]) || data["inbox"]
430 {:ok, data} = Transmogrifier.prepare_outgoing(activity.data)
431 json = Jason.encode!(data)
433 Enum.each(remote_inboxes, fn inbox ->
434 Federator.enqueue(:publish_single_ap, %{
438 id: activity.data["id"]
443 def publish_one(%{inbox: inbox, json: json, actor: actor, id: id}) do
444 Logger.info("Federating #{id} to #{inbox}")
445 host = URI.parse(inbox).host
448 Pleroma.Web.HTTPSignatures.sign(actor, %{host: host, "content-length": byte_size(json)})
453 [{"Content-Type", "application/activity+json"}, {"signature", signature}],
454 hackney: [pool: :default]
459 # This will create a Create activity, which we need internally at the moment.
460 def fetch_object_from_id(id) do
461 if object = Object.get_cached_by_ap_id(id) do
464 Logger.info("Fetching #{id} via AP")
466 with true <- String.starts_with?(id, "http"),
467 {:ok, %{body: body, status_code: code}} when code in 200..299 <-
470 [Accept: "application/activity+json"],
471 follow_redirect: true,
475 {:ok, data} <- Jason.decode(body),
476 nil <- Object.get_by_ap_id(data["id"]),
481 "actor" => data["attributedTo"],
484 {:ok, activity} <- Transmogrifier.handle_incoming(params) do
485 {:ok, Object.get_by_ap_id(activity.data["object"]["id"])}
487 object = %Object{} ->
491 Logger.info("Couldn't get object via AP, trying out OStatus fetching...")
493 case OStatus.fetch_activity_from_url(id) do
494 {:ok, [activity | _]} -> {:ok, Object.get_by_ap_id(activity.data["object"]["id"])}
501 def is_public?(activity) do
502 "https://www.w3.org/ns/activitystreams#Public" in (activity.data["to"] ++
503 (activity.data["cc"] || []))
506 def visible_for_user?(activity, nil) do
510 def visible_for_user?(activity, user) do
511 x = [user.ap_id | user.following]
512 y = activity.data["to"] ++ (activity.data["cc"] || [])
513 visible_for_user?(activity, nil) || Enum.any?(x, &(&1 in y))