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