ActivityPub: implement MRF core hook and baseline noop policy object
[akkoma] / lib / pleroma / web / activity_pub / activity_pub.ex
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
7 import Ecto.Query
8 import Pleroma.Web.ActivityPub.Utils
9 require Logger
10
11 @httpoison Application.get_env(:pleroma, :httpoison)
12
13 @instance Application.get_env(:pleroma, :instance)
14 @rewrite_policy Keyword.get(@instance, :rewrite_policy)
15
16 def get_recipients(data) do
17 (data["to"] || []) ++ (data["cc"] || [])
18 end
19
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 <- insert_full_object(map),
24 {:ok, map} <- @rewrite_policy.filter(map) do
25 {:ok, activity} =
26 Repo.insert(%Activity{
27 data: map,
28 local: local,
29 actor: map["actor"],
30 recipients: get_recipients(map)
31 })
32
33 Notification.create_notifications(activity)
34 stream_out(activity)
35 {:ok, activity}
36 else
37 %Activity{} = activity -> {:ok, activity}
38 error -> {:error, error}
39 end
40 end
41
42 def stream_out(activity) do
43 if activity.data["type"] in ["Create", "Announce"] do
44 Pleroma.Web.Streamer.stream("user", activity)
45
46 if Enum.member?(activity.data["to"], "https://www.w3.org/ns/activitystreams#Public") do
47 Pleroma.Web.Streamer.stream("public", activity)
48
49 if activity.local do
50 Pleroma.Web.Streamer.stream("public:local", activity)
51 end
52 end
53 end
54 end
55
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]
61
62 with create_data <-
63 make_create_data(
64 %{to: to, actor: actor, published: published, context: context, object: object},
65 additional
66 ),
67 {:ok, activity} <- insert(create_data, local),
68 :ok <- maybe_federate(activity) do
69 {:ok, activity}
70 end
71 end
72
73 def accept(%{to: to, actor: actor, object: object} = params) do
74 # only accept false as false value
75 local = !(params[:local] == false)
76
77 with data <- %{"to" => to, "type" => "Accept", "actor" => actor, "object" => object},
78 {:ok, activity} <- insert(data, local),
79 :ok <- maybe_federate(activity) do
80 {:ok, activity}
81 end
82 end
83
84 def update(%{to: to, cc: cc, actor: actor, object: object} = params) do
85 # only accept false as false value
86 local = !(params[:local] == false)
87
88 with data <- %{
89 "to" => to,
90 "cc" => cc,
91 "type" => "Update",
92 "actor" => actor,
93 "object" => object
94 },
95 {:ok, activity} <- insert(data, local),
96 :ok <- maybe_federate(activity) do
97 {:ok, activity}
98 end
99 end
100
101 # TODO: This is weird, maybe we shouldn't check here if we can make the activity.
102 def like(
103 %User{ap_id: ap_id} = user,
104 %Object{data: %{"id" => _}} = object,
105 activity_id \\ nil,
106 local \\ true
107 ) do
108 with nil <- get_existing_like(ap_id, object),
109 like_data <- make_like_data(user, object, activity_id),
110 {:ok, activity} <- insert(like_data, local),
111 {:ok, object} <- add_like_to_object(activity, object),
112 :ok <- maybe_federate(activity) do
113 {:ok, activity, object}
114 else
115 %Activity{} = activity -> {:ok, activity, object}
116 error -> {:error, error}
117 end
118 end
119
120 def unlike(%User{} = actor, %Object{} = object) do
121 with %Activity{} = activity <- get_existing_like(actor.ap_id, object),
122 {:ok, _activity} <- Repo.delete(activity),
123 {:ok, object} <- remove_like_from_object(activity, object) do
124 {:ok, object}
125 else
126 _e -> {:ok, object}
127 end
128 end
129
130 def announce(
131 %User{ap_id: _} = user,
132 %Object{data: %{"id" => _}} = object,
133 activity_id \\ nil,
134 local \\ true
135 ) do
136 with true <- is_public?(object),
137 announce_data <- make_announce_data(user, object, activity_id),
138 {:ok, activity} <- insert(announce_data, local),
139 {:ok, object} <- add_announce_to_object(activity, object),
140 :ok <- maybe_federate(activity) do
141 {:ok, activity, object}
142 else
143 error -> {:error, error}
144 end
145 end
146
147 def follow(follower, followed, activity_id \\ nil, local \\ true) do
148 with data <- make_follow_data(follower, followed, activity_id),
149 {:ok, activity} <- insert(data, local),
150 :ok <- maybe_federate(activity) do
151 {:ok, activity}
152 end
153 end
154
155 def unfollow(follower, followed, local \\ true) do
156 with %Activity{} = follow_activity <- fetch_latest_follow(follower, followed),
157 unfollow_data <- make_unfollow_data(follower, followed, follow_activity),
158 {:ok, activity} <- insert(unfollow_data, local),
159 :ok,
160 maybe_federate(activity) do
161 {:ok, activity}
162 end
163 end
164
165 def delete(%Object{data: %{"id" => id, "actor" => actor}} = object, local \\ true) do
166 user = User.get_cached_by_ap_id(actor)
167
168 data = %{
169 "type" => "Delete",
170 "actor" => actor,
171 "object" => id,
172 "to" => [user.follower_address, "https://www.w3.org/ns/activitystreams#Public"]
173 }
174
175 with Repo.delete(object),
176 Repo.delete_all(Activity.all_non_create_by_object_ap_id_q(id)),
177 {:ok, activity} <- insert(data, local),
178 :ok <- maybe_federate(activity) do
179 {:ok, activity}
180 end
181 end
182
183 def fetch_activities_for_context(context, opts \\ %{}) do
184 public = ["https://www.w3.org/ns/activitystreams#Public"]
185
186 recipients =
187 if opts["user"], do: [opts["user"].ap_id | opts["user"].following] ++ public, else: public
188
189 query = from(activity in Activity)
190
191 query =
192 query
193 |> restrict_blocked(opts)
194 |> restrict_recipients(recipients, opts["user"])
195
196 query =
197 from(
198 activity in query,
199 where:
200 fragment(
201 "?->>'type' = ? and ?->>'context' = ?",
202 activity.data,
203 "Create",
204 activity.data,
205 ^context
206 ),
207 order_by: [desc: :id]
208 )
209
210 Repo.all(query)
211 end
212
213 # TODO: Make this work properly with unlisted.
214 def fetch_public_activities(opts \\ %{}) do
215 q = fetch_activities_query(["https://www.w3.org/ns/activitystreams#Public"], opts)
216
217 q
218 |> Repo.all()
219 |> Enum.reverse()
220 end
221
222 defp restrict_since(query, %{"since_id" => since_id}) do
223 from(activity in query, where: activity.id > ^since_id)
224 end
225
226 defp restrict_since(query, _), do: query
227
228 defp restrict_tag(query, %{"tag" => tag}) do
229 from(
230 activity in query,
231 where: fragment("? <@ (? #> '{\"object\",\"tag\"}')", ^tag, activity.data)
232 )
233 end
234
235 defp restrict_tag(query, _), do: query
236
237 defp restrict_recipients(query, [], user), do: query
238
239 defp restrict_recipients(query, recipients, nil) do
240 from(activity in query, where: fragment("? && ?", ^recipients, activity.recipients))
241 end
242
243 defp restrict_recipients(query, recipients, user) do
244 from(
245 activity in query,
246 where: fragment("? && ?", ^recipients, activity.recipients),
247 or_where: activity.actor == ^user.ap_id
248 )
249 end
250
251 defp restrict_limit(query, %{"limit" => limit}) do
252 from(activity in query, limit: ^limit)
253 end
254
255 defp restrict_limit(query, _), do: query
256
257 defp restrict_local(query, %{"local_only" => true}) do
258 from(activity in query, where: activity.local == true)
259 end
260
261 defp restrict_local(query, _), do: query
262
263 defp restrict_max(query, %{"max_id" => max_id}) do
264 from(activity in query, where: activity.id < ^max_id)
265 end
266
267 defp restrict_max(query, _), do: query
268
269 defp restrict_actor(query, %{"actor_id" => actor_id}) do
270 from(activity in query, where: activity.actor == ^actor_id)
271 end
272
273 defp restrict_actor(query, _), do: query
274
275 defp restrict_type(query, %{"type" => type}) when is_binary(type) do
276 restrict_type(query, %{"type" => [type]})
277 end
278
279 defp restrict_type(query, %{"type" => type}) do
280 from(activity in query, where: fragment("?->>'type' = ANY(?)", activity.data, ^type))
281 end
282
283 defp restrict_type(query, _), do: query
284
285 defp restrict_favorited_by(query, %{"favorited_by" => ap_id}) do
286 from(
287 activity in query,
288 where: fragment("? <@ (? #> '{\"object\",\"likes\"}')", ^ap_id, activity.data)
289 )
290 end
291
292 defp restrict_favorited_by(query, _), do: query
293
294 defp restrict_media(query, %{"only_media" => val}) when val == "true" or val == "1" do
295 from(
296 activity in query,
297 where: fragment("not (? #> '{\"object\",\"attachment\"}' = ?)", activity.data, ^[])
298 )
299 end
300
301 defp restrict_media(query, _), do: query
302
303 # Only search through last 100_000 activities by default
304 defp restrict_recent(query, %{"whole_db" => true}), do: query
305
306 defp restrict_recent(query, _) do
307 since = (Repo.aggregate(Activity, :max, :id) || 0) - 100_000
308
309 from(activity in query, where: activity.id > ^since)
310 end
311
312 defp restrict_blocked(query, %{"blocking_user" => %User{info: info}}) do
313 blocks = info["blocks"] || []
314 from(activity in query, where: fragment("not (? = ANY(?))", activity.actor, ^blocks))
315 end
316
317 defp restrict_blocked(query, _), do: query
318
319 def fetch_activities_query(recipients, opts \\ %{}) do
320 base_query =
321 from(
322 activity in Activity,
323 limit: 20,
324 order_by: [fragment("? desc nulls last", activity.id)]
325 )
326
327 base_query
328 |> restrict_recipients(recipients, opts["user"])
329 |> restrict_tag(opts)
330 |> restrict_since(opts)
331 |> restrict_local(opts)
332 |> restrict_limit(opts)
333 |> restrict_max(opts)
334 |> restrict_actor(opts)
335 |> restrict_type(opts)
336 |> restrict_favorited_by(opts)
337 |> restrict_recent(opts)
338 |> restrict_blocked(opts)
339 |> restrict_media(opts)
340 end
341
342 def fetch_activities(recipients, opts \\ %{}) do
343 fetch_activities_query(recipients, opts)
344 |> Repo.all()
345 |> Enum.reverse()
346 end
347
348 def upload(file) do
349 data = Upload.store(file)
350 Repo.insert(%Object{data: data})
351 end
352
353 def user_data_from_user_object(data) do
354 avatar =
355 data["icon"]["url"] &&
356 %{
357 "type" => "Image",
358 "url" => [%{"href" => data["icon"]["url"]}]
359 }
360
361 banner =
362 data["image"]["url"] &&
363 %{
364 "type" => "Image",
365 "url" => [%{"href" => data["image"]["url"]}]
366 }
367
368 user_data = %{
369 ap_id: data["id"],
370 info: %{
371 "ap_enabled" => true,
372 "source_data" => data,
373 "banner" => banner
374 },
375 avatar: avatar,
376 nickname: "#{data["preferredUsername"]}@#{URI.parse(data["id"]).host}",
377 name: data["name"],
378 follower_address: data["followers"],
379 bio: data["summary"]
380 }
381
382 {:ok, user_data}
383 end
384
385 def fetch_and_prepare_user_from_ap_id(ap_id) do
386 with {:ok, %{status_code: 200, body: body}} <-
387 @httpoison.get(ap_id, Accept: "application/activity+json"),
388 {:ok, data} <- Jason.decode(body) do
389 user_data_from_user_object(data)
390 else
391 e -> Logger.error("Could not decode user at fetch #{ap_id}, #{inspect(e)}")
392 end
393 end
394
395 def make_user_from_ap_id(ap_id) do
396 if user = User.get_by_ap_id(ap_id) do
397 Transmogrifier.upgrade_user_from_ap_id(ap_id)
398 else
399 with {:ok, data} <- fetch_and_prepare_user_from_ap_id(ap_id) do
400 User.insert_or_update_user(data)
401 else
402 e -> {:error, e}
403 end
404 end
405 end
406
407 def make_user_from_nickname(nickname) do
408 with {:ok, %{"ap_id" => ap_id}} when not is_nil(ap_id) <- WebFinger.finger(nickname) do
409 make_user_from_ap_id(ap_id)
410 else
411 _e -> {:error, "No AP id in WebFinger"}
412 end
413 end
414
415 def publish(actor, activity) do
416 followers =
417 if actor.follower_address in activity.recipients do
418 {:ok, followers} = User.get_followers(actor)
419 followers |> Enum.filter(&(!&1.local))
420 else
421 []
422 end
423
424 remote_inboxes =
425 (Pleroma.Web.Salmon.remote_users(activity) ++ followers)
426 |> Enum.filter(fn user -> User.ap_enabled?(user) end)
427 |> Enum.map(fn %{info: %{"source_data" => data}} ->
428 (data["endpoints"] && data["endpoints"]["sharedInbox"]) || data["inbox"]
429 end)
430 |> Enum.uniq()
431
432 {:ok, data} = Transmogrifier.prepare_outgoing(activity.data)
433 json = Jason.encode!(data)
434
435 Enum.each(remote_inboxes, fn inbox ->
436 Federator.enqueue(:publish_single_ap, %{
437 inbox: inbox,
438 json: json,
439 actor: actor,
440 id: activity.data["id"]
441 })
442 end)
443 end
444
445 def publish_one(%{inbox: inbox, json: json, actor: actor, id: id}) do
446 Logger.info("Federating #{id} to #{inbox}")
447 host = URI.parse(inbox).host
448
449 signature =
450 Pleroma.Web.HTTPSignatures.sign(actor, %{host: host, "content-length": byte_size(json)})
451
452 @httpoison.post(
453 inbox,
454 json,
455 [{"Content-Type", "application/activity+json"}, {"signature", signature}],
456 hackney: [pool: :default]
457 )
458 end
459
460 # TODO:
461 # This will create a Create activity, which we need internally at the moment.
462 def fetch_object_from_id(id) do
463 if object = Object.get_cached_by_ap_id(id) do
464 {:ok, object}
465 else
466 Logger.info("Fetching #{id} via AP")
467
468 with true <- String.starts_with?(id, "http"),
469 {:ok, %{body: body, status_code: code}} when code in 200..299 <-
470 @httpoison.get(
471 id,
472 [Accept: "application/activity+json"],
473 follow_redirect: true,
474 timeout: 10000,
475 recv_timeout: 20000
476 ),
477 {:ok, data} <- Jason.decode(body),
478 nil <- Object.get_by_ap_id(data["id"]),
479 params <- %{
480 "type" => "Create",
481 "to" => data["to"],
482 "cc" => data["cc"],
483 "actor" => data["attributedTo"],
484 "object" => data
485 },
486 {:ok, activity} <- Transmogrifier.handle_incoming(params) do
487 {:ok, Object.get_by_ap_id(activity.data["object"]["id"])}
488 else
489 object = %Object{} ->
490 {:ok, object}
491
492 e ->
493 Logger.info("Couldn't get object via AP, trying out OStatus fetching...")
494
495 case OStatus.fetch_activity_from_url(id) do
496 {:ok, [activity | _]} -> {:ok, Object.get_by_ap_id(activity.data["object"]["id"])}
497 e -> e
498 end
499 end
500 end
501 end
502
503 def is_public?(activity) do
504 "https://www.w3.org/ns/activitystreams#Public" in (activity.data["to"] ++
505 (activity.data["cc"] || []))
506 end
507
508 def visible_for_user?(activity, nil) do
509 is_public?(activity)
510 end
511
512 def visible_for_user?(activity, user) do
513 x = [user.ap_id | user.following]
514 y = activity.data["to"] ++ (activity.data["cc"] || [])
515 visible_for_user?(activity, nil) || Enum.any?(x, &(&1 in y))
516 end
517 end