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 @instance Application.get_env(:pleroma, :instance)
14 @rewrite_policy Keyword.get(@instance, :rewrite_policy)
16 def get_recipients(data) do
17 (data["to"] || []) ++ (data["cc"] || [])
20 def insert(map, local \\ true) when is_map(map) do
21 with nil <- Activity.get_by_ap_id(map["id"]),
22 map <- lazy_put_activity_defaults(map),
23 {:ok, map} <- @rewrite_policy.filter(map),
24 :ok <- insert_full_object(map) do
26 Repo.insert(%Activity{
30 recipients: get_recipients(map)
33 Notification.create_notifications(activity)
37 %Activity{} = activity -> {:ok, activity}
38 error -> {:error, error}
42 def stream_out(activity) do
43 if activity.data["type"] in ["Create", "Announce"] do
44 Pleroma.Web.Streamer.stream("user", activity)
46 if Enum.member?(activity.data["to"], "https://www.w3.org/ns/activitystreams#Public") do
47 Pleroma.Web.Streamer.stream("public", activity)
50 Pleroma.Web.Streamer.stream("public:local", activity)
56 def create(%{to: to, actor: actor, context: context, object: object} = params) do
57 additional = params[:additional] || %{}
58 # only accept false as false value
59 local = !(params[:local] == false)
60 published = params[:published]
64 %{to: to, actor: actor, published: published, context: context, object: object},
67 {:ok, activity} <- insert(create_data, local),
68 :ok <- maybe_federate(activity),
69 {:ok, _actor} <- User.increase_note_count(actor) do
74 def accept(%{to: to, actor: actor, object: object} = params) do
75 # only accept false as false value
76 local = !(params[:local] == false)
78 with data <- %{"to" => to, "type" => "Accept", "actor" => actor, "object" => object},
79 {:ok, activity} <- insert(data, local),
80 :ok <- maybe_federate(activity) do
85 def update(%{to: to, cc: cc, actor: actor, object: object} = params) do
86 # only accept false as false value
87 local = !(params[:local] == false)
96 {:ok, activity} <- insert(data, local),
97 :ok <- maybe_federate(activity) do
102 # TODO: This is weird, maybe we shouldn't check here if we can make the activity.
104 %User{ap_id: ap_id} = user,
105 %Object{data: %{"id" => _}} = object,
109 with nil <- get_existing_like(ap_id, object),
110 like_data <- make_like_data(user, object, activity_id),
111 {:ok, activity} <- insert(like_data, local),
112 {:ok, object} <- add_like_to_object(activity, object),
113 :ok <- maybe_federate(activity) do
114 {:ok, activity, object}
116 %Activity{} = activity -> {:ok, activity, object}
117 error -> {:error, error}
121 def unlike(%User{} = actor, %Object{} = object) do
122 with %Activity{} = activity <- get_existing_like(actor.ap_id, object),
123 {:ok, _activity} <- Repo.delete(activity),
124 {:ok, object} <- remove_like_from_object(activity, object) do
132 %User{ap_id: _} = user,
133 %Object{data: %{"id" => _}} = object,
137 with true <- is_public?(object),
138 announce_data <- make_announce_data(user, object, activity_id),
139 {:ok, activity} <- insert(announce_data, local),
140 {:ok, object} <- add_announce_to_object(activity, object),
141 :ok <- maybe_federate(activity) do
142 {:ok, activity, object}
144 error -> {:error, error}
148 def follow(follower, followed, activity_id \\ nil, local \\ true) do
149 with data <- make_follow_data(follower, followed, activity_id),
150 {:ok, activity} <- insert(data, local),
151 :ok <- maybe_federate(activity) do
156 def unfollow(follower, followed, local \\ true) do
157 with %Activity{} = follow_activity <- fetch_latest_follow(follower, followed),
158 unfollow_data <- make_unfollow_data(follower, followed, follow_activity),
159 {:ok, activity} <- insert(unfollow_data, local),
161 maybe_federate(activity) do
166 def delete(%Object{data: %{"id" => id, "actor" => actor}} = object, local \\ true) do
167 user = User.get_cached_by_ap_id(actor)
173 "to" => [user.follower_address, "https://www.w3.org/ns/activitystreams#Public"]
176 with Repo.delete(object),
177 Repo.delete_all(Activity.all_non_create_by_object_ap_id_q(id)),
178 {:ok, activity} <- insert(data, local),
179 :ok <- maybe_federate(activity),
180 {:ok, _actor} <- User.decrease_note_count(user) do
185 def fetch_activities_for_context(context, opts \\ %{}) do
186 public = ["https://www.w3.org/ns/activitystreams#Public"]
189 if opts["user"], do: [opts["user"].ap_id | opts["user"].following] ++ public, else: public
191 query = from(activity in Activity)
195 |> restrict_blocked(opts)
196 |> restrict_recipients(recipients, opts["user"])
203 "?->>'type' = ? and ?->>'context' = ?",
209 order_by: [desc: :id]
215 # TODO: Make this work properly with unlisted.
216 def fetch_public_activities(opts \\ %{}) do
217 q = fetch_activities_query(["https://www.w3.org/ns/activitystreams#Public"], opts)
224 defp restrict_since(query, %{"since_id" => since_id}) do
225 from(activity in query, where: activity.id > ^since_id)
228 defp restrict_since(query, _), do: query
230 defp restrict_tag(query, %{"tag" => tag}) do
233 where: fragment("? <@ (? #> '{\"object\",\"tag\"}')", ^tag, activity.data)
237 defp restrict_tag(query, _), do: query
239 defp restrict_recipients(query, [], _user), do: query
241 defp restrict_recipients(query, recipients, nil) do
242 from(activity in query, where: fragment("? && ?", ^recipients, activity.recipients))
245 defp restrict_recipients(query, recipients, user) do
248 where: fragment("? && ?", ^recipients, activity.recipients),
249 or_where: activity.actor == ^user.ap_id
253 defp restrict_limit(query, %{"limit" => limit}) do
254 from(activity in query, limit: ^limit)
257 defp restrict_limit(query, _), do: query
259 defp restrict_local(query, %{"local_only" => true}) do
260 from(activity in query, where: activity.local == true)
263 defp restrict_local(query, _), do: query
265 defp restrict_max(query, %{"max_id" => max_id}) do
266 from(activity in query, where: activity.id < ^max_id)
269 defp restrict_max(query, _), do: query
271 defp restrict_actor(query, %{"actor_id" => actor_id}) do
272 from(activity in query, where: activity.actor == ^actor_id)
275 defp restrict_actor(query, _), do: query
277 defp restrict_type(query, %{"type" => type}) when is_binary(type) do
278 restrict_type(query, %{"type" => [type]})
281 defp restrict_type(query, %{"type" => type}) do
282 from(activity in query, where: fragment("?->>'type' = ANY(?)", activity.data, ^type))
285 defp restrict_type(query, _), do: query
287 defp restrict_favorited_by(query, %{"favorited_by" => ap_id}) do
290 where: fragment("? <@ (? #> '{\"object\",\"likes\"}')", ^ap_id, activity.data)
294 defp restrict_favorited_by(query, _), do: query
296 defp restrict_media(query, %{"only_media" => val}) when val == "true" or val == "1" do
299 where: fragment("not (? #> '{\"object\",\"attachment\"}' = ?)", activity.data, ^[])
303 defp restrict_media(query, _), do: query
305 # Only search through last 100_000 activities by default
306 defp restrict_recent(query, %{"whole_db" => true}), do: query
308 defp restrict_recent(query, _) do
309 since = (Repo.aggregate(Activity, :max, :id) || 0) - 100_000
311 from(activity in query, where: activity.id > ^since)
314 defp restrict_blocked(query, %{"blocking_user" => %User{info: info}}) do
315 blocks = info["blocks"] || []
319 where: fragment("not (? = ANY(?))", activity.actor, ^blocks),
320 where: fragment("not (?->'to' \\?| ?)", activity.data, ^blocks)
324 defp restrict_blocked(query, _), do: query
326 def fetch_activities_query(recipients, opts \\ %{}) do
329 activity in Activity,
331 order_by: [fragment("? desc nulls last", activity.id)]
335 |> restrict_recipients(recipients, opts["user"])
336 |> restrict_tag(opts)
337 |> restrict_since(opts)
338 |> restrict_local(opts)
339 |> restrict_limit(opts)
340 |> restrict_max(opts)
341 |> restrict_actor(opts)
342 |> restrict_type(opts)
343 |> restrict_favorited_by(opts)
344 |> restrict_recent(opts)
345 |> restrict_blocked(opts)
346 |> restrict_media(opts)
349 def fetch_activities(recipients, opts \\ %{}) do
350 fetch_activities_query(recipients, opts)
356 data = Upload.store(file)
357 Repo.insert(%Object{data: data})
360 def user_data_from_user_object(data) do
362 data["icon"]["url"] &&
365 "url" => [%{"href" => data["icon"]["url"]}]
369 data["image"]["url"] &&
372 "url" => [%{"href" => data["image"]["url"]}]
378 "ap_enabled" => true,
379 "source_data" => data,
383 nickname: "#{data["preferredUsername"]}@#{URI.parse(data["id"]).host}",
385 follower_address: data["followers"],
392 def fetch_and_prepare_user_from_ap_id(ap_id) do
393 with {:ok, %{status_code: 200, body: body}} <-
394 @httpoison.get(ap_id, Accept: "application/activity+json"),
395 {:ok, data} <- Jason.decode(body) do
396 user_data_from_user_object(data)
398 e -> Logger.error("Could not decode user at fetch #{ap_id}, #{inspect(e)}")
402 def make_user_from_ap_id(ap_id) do
403 if _user = User.get_by_ap_id(ap_id) do
404 Transmogrifier.upgrade_user_from_ap_id(ap_id)
406 with {:ok, data} <- fetch_and_prepare_user_from_ap_id(ap_id) do
407 User.insert_or_update_user(data)
414 def make_user_from_nickname(nickname) do
415 with {:ok, %{"ap_id" => ap_id}} when not is_nil(ap_id) <- WebFinger.finger(nickname) do
416 make_user_from_ap_id(ap_id)
418 _e -> {:error, "No AP id in WebFinger"}
422 def publish(actor, activity) do
424 if actor.follower_address in activity.recipients do
425 {:ok, followers} = User.get_followers(actor)
426 followers |> Enum.filter(&(!&1.local))
432 (Pleroma.Web.Salmon.remote_users(activity) ++ followers)
433 |> Enum.filter(fn user -> User.ap_enabled?(user) end)
434 |> Enum.map(fn %{info: %{"source_data" => data}} ->
435 (data["endpoints"] && data["endpoints"]["sharedInbox"]) || data["inbox"]
439 {:ok, data} = Transmogrifier.prepare_outgoing(activity.data)
440 json = Jason.encode!(data)
442 Enum.each(remote_inboxes, fn inbox ->
443 Federator.enqueue(:publish_single_ap, %{
447 id: activity.data["id"]
452 def publish_one(%{inbox: inbox, json: json, actor: actor, id: id}) do
453 Logger.info("Federating #{id} to #{inbox}")
454 host = URI.parse(inbox).host
457 Pleroma.Web.HTTPSignatures.sign(actor, %{host: host, "content-length": byte_size(json)})
462 [{"Content-Type", "application/activity+json"}, {"signature", signature}],
463 hackney: [pool: :default]
468 # This will create a Create activity, which we need internally at the moment.
469 def fetch_object_from_id(id) do
470 if object = Object.get_cached_by_ap_id(id) do
473 Logger.info("Fetching #{id} via AP")
475 with true <- String.starts_with?(id, "http"),
476 {:ok, %{body: body, status_code: code}} when code in 200..299 <-
479 [Accept: "application/activity+json"],
480 follow_redirect: true,
484 {:ok, data} <- Jason.decode(body),
485 nil <- Object.get_by_ap_id(data["id"]),
490 "actor" => data["attributedTo"],
493 {:ok, activity} <- Transmogrifier.handle_incoming(params) do
494 {:ok, Object.get_by_ap_id(activity.data["object"]["id"])}
496 object = %Object{} ->
500 Logger.info("Couldn't get object via AP, trying out OStatus fetching...")
502 case OStatus.fetch_activity_from_url(id) do
503 {:ok, [activity | _]} -> {:ok, Object.get_by_ap_id(activity.data["object"]["id"])}
510 def is_public?(activity) do
511 "https://www.w3.org/ns/activitystreams#Public" in (activity.data["to"] ++
512 (activity.data["cc"] || []))
515 def visible_for_user?(activity, nil) do
519 def visible_for_user?(activity, user) do
520 x = [user.ap_id | user.following]
521 y = activity.data["to"] ++ (activity.data["cc"] || [])
522 visible_for_user?(activity, nil) || Enum.any?(x, &(&1 in y))