d54dc224da5c1b677273f9c41f7b445ffdd12b76
[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, MRF}
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
15 def get_recipients(data) do
16 (data["to"] || []) ++ (data["cc"] || [])
17 end
18
19 defp check_actor_is_active(actor) do
20 if not is_nil(actor) do
21 with user <- User.get_cached_by_ap_id(actor),
22 nil <- user.info["deactivated"] do
23 :ok
24 else
25 _e -> :reject
26 end
27 else
28 :ok
29 end
30 end
31
32 def insert(map, local \\ true) when is_map(map) do
33 with nil <- Activity.get_by_ap_id(map["id"]),
34 map <- lazy_put_activity_defaults(map),
35 :ok <- check_actor_is_active(map["actor"]),
36 {:ok, map} <- MRF.filter(map),
37 :ok <- insert_full_object(map) do
38 {:ok, activity} =
39 Repo.insert(%Activity{
40 data: map,
41 local: local,
42 actor: map["actor"],
43 recipients: get_recipients(map)
44 })
45
46 Notification.create_notifications(activity)
47 stream_out(activity)
48 {:ok, activity}
49 else
50 %Activity{} = activity -> {:ok, activity}
51 error -> {:error, error}
52 end
53 end
54
55 def stream_out(activity) do
56 public = "https://www.w3.org/ns/activitystreams#Public"
57
58 if activity.data["type"] in ["Create", "Announce"] do
59 Pleroma.Web.Streamer.stream("user", activity)
60
61 if Enum.member?(activity.data["to"], public) do
62 Pleroma.Web.Streamer.stream("public", activity)
63
64 if activity.local do
65 Pleroma.Web.Streamer.stream("public:local", activity)
66 end
67 else
68 if !Enum.member?(activity.data["cc"] || [], public) &&
69 !Enum.member?(
70 activity.data["to"],
71 User.get_by_ap_id(activity.data["actor"]).follower_address
72 ),
73 do: Pleroma.Web.Streamer.stream("direct", activity)
74 end
75 end
76 end
77
78 def create(%{to: to, actor: actor, context: context, object: object} = params) do
79 additional = params[:additional] || %{}
80 # only accept false as false value
81 local = !(params[:local] == false)
82 published = params[:published]
83
84 with create_data <-
85 make_create_data(
86 %{to: to, actor: actor, published: published, context: context, object: object},
87 additional
88 ),
89 {:ok, activity} <- insert(create_data, local),
90 :ok <- maybe_federate(activity),
91 {:ok, _actor} <- User.increase_note_count(actor) do
92 {:ok, activity}
93 end
94 end
95
96 def accept(%{to: to, actor: actor, object: object} = params) do
97 # only accept false as false value
98 local = !(params[:local] == false)
99
100 with data <- %{"to" => to, "type" => "Accept", "actor" => actor, "object" => object},
101 {:ok, activity} <- insert(data, local),
102 :ok <- maybe_federate(activity) do
103 {:ok, activity}
104 end
105 end
106
107 def reject(%{to: to, actor: actor, object: object} = params) do
108 # only accept false as false value
109 local = !(params[:local] == false)
110
111 with data <- %{"to" => to, "type" => "Reject", "actor" => actor, "object" => object},
112 {:ok, activity} <- insert(data, local),
113 :ok <- maybe_federate(activity) do
114 {:ok, activity}
115 end
116 end
117
118 def update(%{to: to, cc: cc, actor: actor, object: object} = params) do
119 # only accept false as false value
120 local = !(params[:local] == false)
121
122 with data <- %{
123 "to" => to,
124 "cc" => cc,
125 "type" => "Update",
126 "actor" => actor,
127 "object" => object
128 },
129 {:ok, activity} <- insert(data, local),
130 :ok <- maybe_federate(activity) do
131 {:ok, activity}
132 end
133 end
134
135 # TODO: This is weird, maybe we shouldn't check here if we can make the activity.
136 def like(
137 %User{ap_id: ap_id} = user,
138 %Object{data: %{"id" => _}} = object,
139 activity_id \\ nil,
140 local \\ true
141 ) do
142 with nil <- get_existing_like(ap_id, object),
143 like_data <- make_like_data(user, object, activity_id),
144 {:ok, activity} <- insert(like_data, local),
145 {:ok, object} <- add_like_to_object(activity, object),
146 :ok <- maybe_federate(activity) do
147 {:ok, activity, object}
148 else
149 %Activity{} = activity -> {:ok, activity, object}
150 error -> {:error, error}
151 end
152 end
153
154 def unlike(
155 %User{} = actor,
156 %Object{} = object,
157 activity_id \\ nil,
158 local \\ true
159 ) do
160 with %Activity{} = like_activity <- get_existing_like(actor.ap_id, object),
161 unlike_data <- make_unlike_data(actor, like_activity, activity_id),
162 {:ok, unlike_activity} <- insert(unlike_data, local),
163 {:ok, _activity} <- Repo.delete(like_activity),
164 {:ok, object} <- remove_like_from_object(like_activity, object),
165 :ok <- maybe_federate(unlike_activity) do
166 {:ok, unlike_activity, like_activity, object}
167 else
168 _e -> {:ok, object}
169 end
170 end
171
172 def announce(
173 %User{ap_id: _} = user,
174 %Object{data: %{"id" => _}} = object,
175 activity_id \\ nil,
176 local \\ true
177 ) do
178 with true <- is_public?(object),
179 announce_data <- make_announce_data(user, object, activity_id),
180 {:ok, activity} <- insert(announce_data, local),
181 {:ok, object} <- add_announce_to_object(activity, object),
182 :ok <- maybe_federate(activity) do
183 {:ok, activity, object}
184 else
185 error -> {:error, error}
186 end
187 end
188
189 def unannounce(
190 %User{} = actor,
191 %Object{} = object,
192 activity_id \\ nil,
193 local \\ true
194 ) do
195 with %Activity{} = announce_activity <- get_existing_announce(actor.ap_id, object),
196 unannounce_data <- make_unannounce_data(actor, announce_activity, activity_id),
197 {:ok, unannounce_activity} <- insert(unannounce_data, local),
198 :ok <- maybe_federate(unannounce_activity),
199 {:ok, _activity} <- Repo.delete(announce_activity),
200 {:ok, object} <- remove_announce_from_object(announce_activity, object) do
201 {:ok, unannounce_activity, announce_activity, object}
202 else
203 _e -> {:ok, object}
204 end
205 end
206
207 def follow(follower, followed, activity_id \\ nil, local \\ true) do
208 with data <- make_follow_data(follower, followed, activity_id),
209 {:ok, activity} <- insert(data, local),
210 :ok <- maybe_federate(activity) do
211 {:ok, activity}
212 end
213 end
214
215 def unfollow(follower, followed, activity_id \\ nil, local \\ true) do
216 with %Activity{} = follow_activity <- fetch_latest_follow(follower, followed),
217 unfollow_data <- make_unfollow_data(follower, followed, follow_activity, activity_id),
218 {:ok, activity} <- insert(unfollow_data, local),
219 :ok <- maybe_federate(activity) do
220 {:ok, activity}
221 end
222 end
223
224 def delete(%Object{data: %{"id" => id, "actor" => actor}} = object, local \\ true) do
225 user = User.get_cached_by_ap_id(actor)
226
227 data = %{
228 "type" => "Delete",
229 "actor" => actor,
230 "object" => id,
231 "to" => [user.follower_address, "https://www.w3.org/ns/activitystreams#Public"]
232 }
233
234 with Repo.delete(object),
235 Repo.delete_all(Activity.all_non_create_by_object_ap_id_q(id)),
236 {:ok, activity} <- insert(data, local),
237 :ok <- maybe_federate(activity),
238 {:ok, _actor} <- User.decrease_note_count(user) do
239 {:ok, activity}
240 end
241 end
242
243 def block(blocker, blocked, activity_id \\ nil, local \\ true) do
244 follow_activity = fetch_latest_follow(blocker, blocked)
245
246 if follow_activity do
247 unfollow(blocker, blocked, nil, local)
248 end
249
250 with block_data <- make_block_data(blocker, blocked, activity_id),
251 {:ok, activity} <- insert(block_data, local),
252 :ok <- maybe_federate(activity) do
253 {:ok, activity}
254 end
255 end
256
257 def unblock(blocker, blocked, activity_id \\ nil, local \\ true) do
258 with %Activity{} = block_activity <- fetch_latest_block(blocker, blocked),
259 unblock_data <- make_unblock_data(blocker, blocked, block_activity, activity_id),
260 {:ok, activity} <- insert(unblock_data, local),
261 :ok <- maybe_federate(activity) do
262 {:ok, activity}
263 end
264 end
265
266 def fetch_activities_for_context(context, opts \\ %{}) do
267 public = ["https://www.w3.org/ns/activitystreams#Public"]
268
269 recipients =
270 if opts["user"], do: [opts["user"].ap_id | opts["user"].following] ++ public, else: public
271
272 query = from(activity in Activity)
273
274 query =
275 query
276 |> restrict_blocked(opts)
277 |> restrict_recipients(recipients, opts["user"])
278
279 query =
280 from(
281 activity in query,
282 where:
283 fragment(
284 "?->>'type' = ? and ?->>'context' = ?",
285 activity.data,
286 "Create",
287 activity.data,
288 ^context
289 ),
290 order_by: [desc: :id]
291 )
292
293 Repo.all(query)
294 end
295
296 def fetch_public_activities(opts \\ %{}) do
297 q = fetch_activities_query(["https://www.w3.org/ns/activitystreams#Public"], opts)
298
299 q
300 |> restrict_unlisted()
301 |> Repo.all()
302 |> Enum.reverse()
303 end
304
305 @valid_visibilities ~w[direct unlisted public private]
306
307 defp restrict_visibility(query, %{visibility: "direct"}) do
308 public = "https://www.w3.org/ns/activitystreams#Public"
309
310 from(
311 activity in query,
312 join: sender in User,
313 on: sender.ap_id == activity.actor,
314 # Are non-direct statuses with no to/cc possible?
315 where:
316 fragment("not coalesce(data->'to' \\? ?, false)", ^public) and
317 fragment("not coalesce(data->'cc' \\? ?, false)", ^public) and
318 fragment("not coalesce(data->'to' \\? ?, false)", sender.follower_address)
319 )
320 end
321
322 defp restrict_visibility(_query, %{visibility: visibility})
323 when visibility not in @valid_visibilities do
324 Logger.error("Could not restrict visibility to #{visibility}")
325 end
326
327 defp restrict_visibility(query, _visibility), do: query
328
329 def fetch_user_activities(user, reading_user, params \\ %{}) do
330 params =
331 params
332 |> Map.put("type", ["Create", "Announce"])
333 |> Map.put("actor_id", user.ap_id)
334 |> Map.put("whole_db", true)
335
336 recipients =
337 if reading_user do
338 ["https://www.w3.org/ns/activitystreams#Public"] ++
339 [reading_user.ap_id | reading_user.following]
340 else
341 ["https://www.w3.org/ns/activitystreams#Public"]
342 end
343
344 fetch_activities(recipients, params)
345 |> Enum.reverse()
346 end
347
348 defp restrict_since(query, %{"since_id" => since_id}) do
349 from(activity in query, where: activity.id > ^since_id)
350 end
351
352 defp restrict_since(query, _), do: query
353
354 defp restrict_tag(query, %{"tag" => tag}) do
355 from(
356 activity in query,
357 where: fragment("? <@ (? #> '{\"object\",\"tag\"}')", ^tag, activity.data)
358 )
359 end
360
361 defp restrict_tag(query, _), do: query
362
363 defp restrict_recipients(query, [], _user), do: query
364
365 defp restrict_recipients(query, recipients, nil) do
366 from(activity in query, where: fragment("? && ?", ^recipients, activity.recipients))
367 end
368
369 defp restrict_recipients(query, recipients, user) do
370 from(
371 activity in query,
372 where: fragment("? && ?", ^recipients, activity.recipients),
373 or_where: activity.actor == ^user.ap_id
374 )
375 end
376
377 defp restrict_limit(query, %{"limit" => limit}) do
378 from(activity in query, limit: ^limit)
379 end
380
381 defp restrict_limit(query, _), do: query
382
383 defp restrict_local(query, %{"local_only" => true}) do
384 from(activity in query, where: activity.local == true)
385 end
386
387 defp restrict_local(query, _), do: query
388
389 defp restrict_max(query, %{"max_id" => max_id}) do
390 from(activity in query, where: activity.id < ^max_id)
391 end
392
393 defp restrict_max(query, _), do: query
394
395 defp restrict_actor(query, %{"actor_id" => actor_id}) do
396 from(activity in query, where: activity.actor == ^actor_id)
397 end
398
399 defp restrict_actor(query, _), do: query
400
401 defp restrict_type(query, %{"type" => type}) when is_binary(type) do
402 restrict_type(query, %{"type" => [type]})
403 end
404
405 defp restrict_type(query, %{"type" => type}) do
406 from(activity in query, where: fragment("?->>'type' = ANY(?)", activity.data, ^type))
407 end
408
409 defp restrict_type(query, _), do: query
410
411 defp restrict_favorited_by(query, %{"favorited_by" => ap_id}) do
412 from(
413 activity in query,
414 where: fragment("? <@ (? #> '{\"object\",\"likes\"}')", ^ap_id, activity.data)
415 )
416 end
417
418 defp restrict_favorited_by(query, _), do: query
419
420 defp restrict_media(query, %{"only_media" => val}) when val == "true" or val == "1" do
421 from(
422 activity in query,
423 where: fragment("not (? #> '{\"object\",\"attachment\"}' = ?)", activity.data, ^[])
424 )
425 end
426
427 defp restrict_media(query, _), do: query
428
429 # Only search through last 100_000 activities by default
430 defp restrict_recent(query, %{"whole_db" => true}), do: query
431
432 defp restrict_recent(query, _) do
433 since = (Repo.aggregate(Activity, :max, :id) || 0) - 100_000
434
435 from(activity in query, where: activity.id > ^since)
436 end
437
438 defp restrict_blocked(query, %{"blocking_user" => %User{info: info}}) do
439 blocks = info["blocks"] || []
440
441 from(
442 activity in query,
443 where: fragment("not (? = ANY(?))", activity.actor, ^blocks),
444 where: fragment("not (?->'to' \\?| ?)", activity.data, ^blocks)
445 )
446 end
447
448 defp restrict_blocked(query, _), do: query
449
450 defp restrict_unlisted(query) do
451 from(
452 activity in query,
453 where:
454 fragment(
455 "not (coalesce(?->'cc', '{}'::jsonb) \\?| ?)",
456 activity.data,
457 ^["https://www.w3.org/ns/activitystreams#Public"]
458 )
459 )
460 end
461
462 def fetch_activities_query(recipients, opts \\ %{}) do
463 base_query =
464 from(
465 activity in Activity,
466 limit: 20,
467 order_by: [fragment("? desc nulls last", activity.id)]
468 )
469
470 base_query
471 |> restrict_recipients(recipients, opts["user"])
472 |> restrict_tag(opts)
473 |> restrict_since(opts)
474 |> restrict_local(opts)
475 |> restrict_limit(opts)
476 |> restrict_max(opts)
477 |> restrict_actor(opts)
478 |> restrict_type(opts)
479 |> restrict_favorited_by(opts)
480 |> restrict_recent(opts)
481 |> restrict_blocked(opts)
482 |> restrict_media(opts)
483 |> restrict_visibility(opts)
484 end
485
486 def fetch_activities(recipients, opts \\ %{}) do
487 fetch_activities_query(recipients, opts)
488 |> Repo.all()
489 |> Enum.reverse()
490 end
491
492 def upload(file) do
493 data = Upload.store(file)
494 Repo.insert(%Object{data: data})
495 end
496
497 def user_data_from_user_object(data) do
498 avatar =
499 data["icon"]["url"] &&
500 %{
501 "type" => "Image",
502 "url" => [%{"href" => data["icon"]["url"]}]
503 }
504
505 banner =
506 data["image"]["url"] &&
507 %{
508 "type" => "Image",
509 "url" => [%{"href" => data["image"]["url"]}]
510 }
511
512 locked = data["manuallyApprovesFollowers"] || false
513 data = Transmogrifier.maybe_fix_user_object(data)
514
515 user_data = %{
516 ap_id: data["id"],
517 info: %{
518 "ap_enabled" => true,
519 "source_data" => data,
520 "banner" => banner,
521 "locked" => locked
522 },
523 avatar: avatar,
524 nickname: "#{data["preferredUsername"]}@#{URI.parse(data["id"]).host}",
525 name: data["name"],
526 follower_address: data["followers"],
527 bio: data["summary"]
528 }
529
530 {:ok, user_data}
531 end
532
533 def fetch_and_prepare_user_from_ap_id(ap_id) do
534 with {:ok, %{status_code: 200, body: body}} <-
535 @httpoison.get(ap_id, Accept: "application/activity+json"),
536 {:ok, data} <- Jason.decode(body) do
537 user_data_from_user_object(data)
538 else
539 e -> Logger.error("Could not decode user at fetch #{ap_id}, #{inspect(e)}")
540 end
541 end
542
543 def make_user_from_ap_id(ap_id) do
544 if _user = User.get_by_ap_id(ap_id) do
545 Transmogrifier.upgrade_user_from_ap_id(ap_id)
546 else
547 with {:ok, data} <- fetch_and_prepare_user_from_ap_id(ap_id) do
548 User.insert_or_update_user(data)
549 else
550 e -> {:error, e}
551 end
552 end
553 end
554
555 def make_user_from_nickname(nickname) do
556 with {:ok, %{"ap_id" => ap_id}} when not is_nil(ap_id) <- WebFinger.finger(nickname) do
557 make_user_from_ap_id(ap_id)
558 else
559 _e -> {:error, "No AP id in WebFinger"}
560 end
561 end
562
563 def publish(actor, activity) do
564 followers =
565 if actor.follower_address in activity.recipients do
566 {:ok, followers} = User.get_followers(actor)
567 followers |> Enum.filter(&(!&1.local))
568 else
569 []
570 end
571
572 remote_inboxes =
573 (Pleroma.Web.Salmon.remote_users(activity) ++ followers)
574 |> Enum.filter(fn user -> User.ap_enabled?(user) end)
575 |> Enum.map(fn %{info: %{"source_data" => data}} ->
576 (data["endpoints"] && data["endpoints"]["sharedInbox"]) || data["inbox"]
577 end)
578 |> Enum.uniq()
579
580 {:ok, data} = Transmogrifier.prepare_outgoing(activity.data)
581 json = Jason.encode!(data)
582
583 Enum.each(remote_inboxes, fn inbox ->
584 Federator.enqueue(:publish_single_ap, %{
585 inbox: inbox,
586 json: json,
587 actor: actor,
588 id: activity.data["id"]
589 })
590 end)
591 end
592
593 def publish_one(%{inbox: inbox, json: json, actor: actor, id: id}) do
594 Logger.info("Federating #{id} to #{inbox}")
595 host = URI.parse(inbox).host
596
597 signature =
598 Pleroma.Web.HTTPSignatures.sign(actor, %{host: host, "content-length": byte_size(json)})
599
600 @httpoison.post(
601 inbox,
602 json,
603 [{"Content-Type", "application/activity+json"}, {"signature", signature}],
604 hackney: [pool: :default]
605 )
606 end
607
608 # TODO:
609 # This will create a Create activity, which we need internally at the moment.
610 def fetch_object_from_id(id) do
611 if object = Object.get_cached_by_ap_id(id) do
612 {:ok, object}
613 else
614 Logger.info("Fetching #{id} via AP")
615
616 with true <- String.starts_with?(id, "http"),
617 {:ok, %{body: body, status_code: code}} when code in 200..299 <-
618 @httpoison.get(
619 id,
620 [Accept: "application/activity+json"],
621 follow_redirect: true,
622 timeout: 10000,
623 recv_timeout: 20000
624 ),
625 {:ok, data} <- Jason.decode(body),
626 nil <- Object.get_by_ap_id(data["id"]),
627 params <- %{
628 "type" => "Create",
629 "to" => data["to"],
630 "cc" => data["cc"],
631 "actor" => data["attributedTo"],
632 "object" => data
633 },
634 {:ok, activity} <- Transmogrifier.handle_incoming(params) do
635 {:ok, Object.get_by_ap_id(activity.data["object"]["id"])}
636 else
637 object = %Object{} ->
638 {:ok, object}
639
640 _e ->
641 Logger.info("Couldn't get object via AP, trying out OStatus fetching...")
642
643 case OStatus.fetch_activity_from_url(id) do
644 {:ok, [activity | _]} -> {:ok, Object.get_by_ap_id(activity.data["object"]["id"])}
645 e -> e
646 end
647 end
648 end
649 end
650
651 def is_public?(activity) do
652 "https://www.w3.org/ns/activitystreams#Public" in (activity.data["to"] ++
653 (activity.data["cc"] || []))
654 end
655
656 def visible_for_user?(activity, nil) do
657 is_public?(activity)
658 end
659
660 def visible_for_user?(activity, user) do
661 x = [user.ap_id | user.following]
662 y = activity.data["to"] ++ (activity.data["cc"] || [])
663 visible_for_user?(activity, nil) || Enum.any?(x, &(&1 in y))
664 end
665 end