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
21 {:ok, activity} = Repo.insert(%Activity{data: map, local: local, actor: map["actor"], recipients: get_recipients(map)})
22 Notification.create_notifications(activity)
26 %Activity{} = activity -> {:ok, activity}
27 error -> {:error, error}
31 def stream_out(activity) do
32 if activity.data["type"] in ["Create", "Announce"] do
33 Pleroma.Web.Streamer.stream("user", activity)
34 if Enum.member?(activity.data["to"], "https://www.w3.org/ns/activitystreams#Public") do
35 Pleroma.Web.Streamer.stream("public", activity)
37 Pleroma.Web.Streamer.stream("public:local", activity)
43 def create(%{to: to, actor: actor, context: context, object: object} = params) do
44 additional = params[:additional] || %{}
45 local = !(params[:local] == false) # only accept false as false value
46 published = params[:published]
48 with create_data <- make_create_data(%{to: to, actor: actor, published: published, context: context, object: object}, additional),
49 {:ok, activity} <- insert(create_data, local),
50 :ok <- maybe_federate(activity) do
55 def accept(%{to: to, actor: actor, object: object} = params) do
56 local = !(params[:local] == false) # only accept false as false value
58 with data <- %{"to" => to, "type" => "Accept", "actor" => actor, "object" => object},
59 {:ok, activity} <- insert(data, local),
60 :ok <- maybe_federate(activity) do
65 def update(%{to: to, cc: cc, actor: actor, object: object} = params) do
66 local = !(params[:local] == false) # only accept false as false value
68 with data <- %{"to" => to, "cc" => cc, "type" => "Update", "actor" => actor, "object" => object},
69 {:ok, activity} <- insert(data, local),
70 :ok <- maybe_federate(activity) do
75 # TODO: This is weird, maybe we shouldn't check here if we can make the activity.
76 def like(%User{ap_id: ap_id} = user, %Object{data: %{"id" => _}} = object, activity_id \\ nil, local \\ true) do
77 with nil <- get_existing_like(ap_id, object),
78 like_data <- make_like_data(user, object, activity_id),
79 {:ok, activity} <- insert(like_data, local),
80 {:ok, object} <- add_like_to_object(activity, object),
81 :ok <- maybe_federate(activity) do
82 {:ok, activity, object}
84 %Activity{} = activity -> {:ok, activity, object}
85 error -> {:error, error}
89 def unlike(%User{} = actor, %Object{} = object) do
90 with %Activity{} = activity <- get_existing_like(actor.ap_id, object),
91 {:ok, _activity} <- Repo.delete(activity),
92 {:ok, object} <- remove_like_from_object(activity, object) do
94 else _e -> {:ok, object}
98 def announce(%User{ap_id: _} = user, %Object{data: %{"id" => _}} = object, activity_id \\ nil, local \\ true) do
99 with true <- is_public?(object),
100 announce_data <- make_announce_data(user, object, activity_id),
101 {:ok, activity} <- insert(announce_data, local),
102 {:ok, object} <- add_announce_to_object(activity, object),
103 :ok <- maybe_federate(activity) do
104 {:ok, activity, object}
106 error -> {:error, error}
110 def follow(follower, followed, activity_id \\ nil, local \\ true) do
111 with data <- make_follow_data(follower, followed, activity_id),
112 {:ok, activity} <- insert(data, local),
113 :ok <- maybe_federate(activity) do
118 def unfollow(follower, followed, local \\ true) do
119 with %Activity{} = follow_activity <- fetch_latest_follow(follower, followed),
120 unfollow_data <- make_unfollow_data(follower, followed, follow_activity),
121 {:ok, activity} <- insert(unfollow_data, local),
122 :ok, maybe_federate(activity) do
127 def delete(%Object{data: %{"id" => id, "actor" => actor}} = object, local \\ true) do
128 user = User.get_cached_by_ap_id(actor)
133 "to" => [user.follower_address, "https://www.w3.org/ns/activitystreams#Public"]
135 with Repo.delete(object),
136 Repo.delete_all(Activity.all_non_create_by_object_ap_id_q(id)),
137 {:ok, activity} <- insert(data, local),
138 :ok <- maybe_federate(activity) do
143 def fetch_activities_for_context(context, opts \\ %{}) do
144 public = ["https://www.w3.org/ns/activitystreams#Public"]
145 recipients = if opts["user"], do: [opts["user"].ap_id | opts["user"].following] ++ public, else: public
147 query = from activity in Activity
149 |> restrict_blocked(opts)
150 |> restrict_recipients(recipients, opts["user"])
152 query = from activity in query,
153 where: fragment("?->>'type' = ? and ?->>'context' = ?", activity.data, "Create", activity.data, ^context),
154 order_by: [desc: :id]
158 # TODO: Make this work properly with unlisted.
159 def fetch_public_activities(opts \\ %{}) do
160 q = fetch_activities_query(["https://www.w3.org/ns/activitystreams#Public"], opts)
166 defp restrict_since(query, %{"since_id" => since_id}) do
167 from activity in query, where: activity.id > ^since_id
169 defp restrict_since(query, _), do: query
171 defp restrict_tag(query, %{"tag" => tag}) do
172 from activity in query,
173 where: fragment("? <@ (? #> '{\"object\",\"tag\"}')", ^tag, activity.data)
175 defp restrict_tag(query, _), do: query
177 defp restrict_recipients(query, [], user), do: query
178 defp restrict_recipients(query, recipients, nil) do
179 from activity in query,
180 where: fragment("? && ?", ^recipients, activity.recipients)
182 defp restrict_recipients(query, recipients, user) do
183 from activity in query,
184 where: fragment("? && ?", ^recipients, activity.recipients),
185 or_where: activity.actor == ^user.ap_id
188 defp restrict_local(query, %{"local_only" => true}) do
189 from activity in query, where: activity.local == true
191 defp restrict_local(query, _), do: query
193 defp restrict_max(query, %{"max_id" => max_id}) do
194 from activity in query, where: activity.id < ^max_id
196 defp restrict_max(query, _), do: query
198 defp restrict_actor(query, %{"actor_id" => actor_id}) do
199 from activity in query,
200 where: activity.actor == ^actor_id
202 defp restrict_actor(query, _), do: query
204 defp restrict_type(query, %{"type" => type}) when is_binary(type) do
205 restrict_type(query, %{"type" => [type]})
207 defp restrict_type(query, %{"type" => type}) do
208 from activity in query,
209 where: fragment("?->>'type' = ANY(?)", activity.data, ^type)
211 defp restrict_type(query, _), do: query
213 defp restrict_favorited_by(query, %{"favorited_by" => ap_id}) do
214 from activity in query,
215 where: fragment("? <@ (? #> '{\"object\",\"likes\"}')", ^ap_id, activity.data)
217 defp restrict_favorited_by(query, _), do: query
219 defp restrict_media(query, %{"only_media" => val}) when val == "true" or val == "1" do
220 from activity in query,
221 where: fragment("not (? #> '{\"object\",\"attachment\"}' = ?)", activity.data, ^[])
223 defp restrict_media(query, _), do: query
225 # Only search through last 100_000 activities by default
226 defp restrict_recent(query, %{"whole_db" => true}), do: query
227 defp restrict_recent(query, _) do
228 since = (Repo.aggregate(Activity, :max, :id) || 0) - 100_000
230 from activity in query,
231 where: activity.id > ^since
234 defp restrict_blocked(query, %{"blocking_user" => %User{info: info}}) do
235 blocks = info["blocks"] || []
236 from activity in query,
237 where: fragment("not (? = ANY(?))", activity.actor, ^blocks)
239 defp restrict_blocked(query, _), do: query
241 def fetch_activities_query(recipients, opts \\ %{}) do
242 base_query = from activity in Activity,
244 order_by: [fragment("? desc nulls last", activity.id)]
247 |> restrict_recipients(recipients, opts["user"])
248 |> restrict_tag(opts)
249 |> restrict_since(opts)
250 |> restrict_local(opts)
251 |> restrict_max(opts)
252 |> restrict_actor(opts)
253 |> restrict_type(opts)
254 |> restrict_favorited_by(opts)
255 |> restrict_recent(opts)
256 |> restrict_blocked(opts)
257 |> restrict_media(opts)
260 def fetch_activities(recipients, opts \\ %{}) do
261 fetch_activities_query(recipients, opts)
267 data = Upload.store(file)
268 Repo.insert(%Object{data: data})
271 def user_data_from_user_object(data) do
272 avatar = data["icon"]["url"] && %{
274 "url" => [%{"href" => data["icon"]["url"]}]
277 banner = data["image"]["url"] && %{
279 "url" => [%{"href" => data["image"]["url"]}]
285 "ap_enabled" => true,
286 "source_data" => data,
290 nickname: "#{data["preferredUsername"]}@#{URI.parse(data["id"]).host}",
292 follower_address: data["followers"],
299 def fetch_and_prepare_user_from_ap_id(ap_id) do
300 with {:ok, %{status_code: 200, body: body}} <- @httpoison.get(ap_id, ["Accept": "application/activity+json"]),
301 {:ok, data} <- Poison.decode(body) do
302 user_data_from_user_object(data)
304 e -> Logger.error("Could not user at fetch #{ap_id}, #{inspect(e)}")
308 def make_user_from_ap_id(ap_id) do
309 if user = User.get_by_ap_id(ap_id) do
310 Transmogrifier.upgrade_user_from_ap_id(ap_id)
312 with {:ok, data} <- fetch_and_prepare_user_from_ap_id(ap_id) do
313 User.insert_or_update_user(data)
320 def make_user_from_nickname(nickname) do
321 with {:ok, %{"ap_id" => ap_id}} when not is_nil(ap_id) <- WebFinger.finger(nickname) do
322 make_user_from_ap_id(ap_id)
324 _e -> {:error, "No ap id in webfinger"}
328 def publish(actor, activity) do
329 followers = if actor.follower_address in activity.recipients do
330 {:ok, followers} = User.get_followers(actor)
331 followers |> Enum.filter(&(!&1.local))
336 remote_inboxes = (Pleroma.Web.Salmon.remote_users(activity) ++ followers)
337 |> Enum.filter(fn (user) -> User.ap_enabled?(user) end)
338 |> Enum.map(fn (%{info: %{"source_data" => data}}) ->
339 (data["endpoints"] && data["endpoints"]["sharedInbox"]) || data["inbox"]
343 {:ok, data} = Transmogrifier.prepare_outgoing(activity.data)
344 json = Poison.encode!(data)
345 Enum.each remote_inboxes, fn(inbox) ->
346 Federator.enqueue(:publish_single_ap, %{inbox: inbox, json: json, actor: actor, id: activity.data["id"]})
350 def publish_one(%{inbox: inbox, json: json, actor: actor, id: id}) do
351 Logger.info("Federating #{id} to #{inbox}")
352 host = URI.parse(inbox).host
353 signature = Pleroma.Web.HTTPSignatures.sign(actor, %{host: host, "content-length": byte_size(json)})
354 @httpoison.post(inbox, json, [{"Content-Type", "application/activity+json"}, {"signature", signature}])
358 # This will create a Create activity, which we need internally at the moment.
359 def fetch_object_from_id(id) do
360 if object = Object.get_cached_by_ap_id(id) do
363 Logger.info("Fetching #{id} via AP")
364 with {:ok, %{body: body, status_code: code}} when code in 200..299 <- @httpoison.get(id, [Accept: "application/activity+json"], follow_redirect: true, timeout: 10000, recv_timeout: 20000),
365 {:ok, data} <- Poison.decode(body),
366 nil <- Object.get_by_ap_id(data["id"]),
367 params <- %{"type" => "Create", "to" => data["to"], "cc" => data["cc"], "actor" => data["attributedTo"], "object" => data},
368 {:ok, activity} <- Transmogrifier.handle_incoming(params) do
369 {:ok, Object.get_by_ap_id(activity.data["object"]["id"])}
371 object = %Object{} -> {:ok, object}
373 Logger.info("Couldn't get object via AP, trying out OStatus fetching...")
374 case OStatus.fetch_activity_from_url(id) do
375 {:ok, [activity | _]} -> {:ok, Object.get_by_ap_id(activity.data["object"]["id"])}
382 def is_public?(activity) do
383 "https://www.w3.org/ns/activitystreams#Public" in (activity.data["to"] ++ (activity.data["cc"] || []))
386 def visible_for_user?(activity, nil) do
389 def visible_for_user?(activity, user) do
390 x = [user.ap_id | user.following]
391 y = (activity.data["to"] ++ (activity.data["cc"] || []))
392 visible_for_user?(activity, nil) || Enum.any?(x, &(&1 in y))