Remove recent activity restriction.
[akkoma] / lib / pleroma / web / activity_pub / activity_pub.ex
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2019 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
4
5 defmodule Pleroma.Web.ActivityPub.ActivityPub do
6 alias Pleroma.{Activity, Repo, Object, Upload, User, Notification}
7 alias Pleroma.Web.ActivityPub.{Transmogrifier, MRF}
8 alias Pleroma.Web.WebFinger
9 alias Pleroma.Web.Federator
10 alias Pleroma.Web.OStatus
11 import Ecto.Query
12 import Pleroma.Web.ActivityPub.Utils
13 require Logger
14
15 @httpoison Application.get_env(:pleroma, :httpoison)
16
17 # For Announce activities, we filter the recipients based on following status for any actors
18 # that match actual users. See issue #164 for more information about why this is necessary.
19 defp get_recipients(%{"type" => "Announce"} = data) do
20 to = data["to"] || []
21 cc = data["cc"] || []
22 recipients = to ++ cc
23 actor = User.get_cached_by_ap_id(data["actor"])
24
25 recipients
26 |> Enum.filter(fn recipient ->
27 case User.get_cached_by_ap_id(recipient) do
28 nil ->
29 true
30
31 user ->
32 User.following?(user, actor)
33 end
34 end)
35
36 {recipients, to, cc}
37 end
38
39 defp get_recipients(data) do
40 to = data["to"] || []
41 cc = data["cc"] || []
42 recipients = to ++ cc
43 {recipients, to, cc}
44 end
45
46 defp check_actor_is_active(actor) do
47 if not is_nil(actor) do
48 with user <- User.get_cached_by_ap_id(actor),
49 false <- user.info.deactivated do
50 :ok
51 else
52 _e -> :reject
53 end
54 else
55 :ok
56 end
57 end
58
59 defp check_remote_limit(%{"object" => %{"content" => content}}) do
60 limit = Pleroma.Config.get([:instance, :remote_limit])
61 String.length(content) <= limit
62 end
63
64 defp check_remote_limit(_), do: true
65
66 def insert(map, local \\ true) when is_map(map) do
67 with nil <- Activity.normalize(map),
68 map <- lazy_put_activity_defaults(map),
69 :ok <- check_actor_is_active(map["actor"]),
70 {_, true} <- {:remote_limit_error, check_remote_limit(map)},
71 {:ok, map} <- MRF.filter(map),
72 :ok <- insert_full_object(map) do
73 {recipients, _, _} = get_recipients(map)
74
75 {:ok, activity} =
76 Repo.insert(%Activity{
77 data: map,
78 local: local,
79 actor: map["actor"],
80 recipients: recipients
81 })
82
83 Notification.create_notifications(activity)
84 stream_out(activity)
85 {:ok, activity}
86 else
87 %Activity{} = activity -> {:ok, activity}
88 error -> {:error, error}
89 end
90 end
91
92 def stream_out(activity) do
93 public = "https://www.w3.org/ns/activitystreams#Public"
94
95 if activity.data["type"] in ["Create", "Announce"] do
96 Pleroma.Web.Streamer.stream("user", activity)
97 Pleroma.Web.Streamer.stream("list", activity)
98
99 if Enum.member?(activity.data["to"], public) do
100 Pleroma.Web.Streamer.stream("public", activity)
101
102 if activity.local do
103 Pleroma.Web.Streamer.stream("public:local", activity)
104 end
105
106 activity.data["object"]
107 |> Map.get("tag", [])
108 |> Enum.filter(fn tag -> is_bitstring(tag) end)
109 |> Enum.map(fn tag -> Pleroma.Web.Streamer.stream("hashtag:" <> tag, activity) end)
110
111 if activity.data["object"]["attachment"] != [] do
112 Pleroma.Web.Streamer.stream("public:media", activity)
113
114 if activity.local do
115 Pleroma.Web.Streamer.stream("public:local:media", activity)
116 end
117 end
118 else
119 if !Enum.member?(activity.data["cc"] || [], public) &&
120 !Enum.member?(
121 activity.data["to"],
122 User.get_by_ap_id(activity.data["actor"]).follower_address
123 ),
124 do: Pleroma.Web.Streamer.stream("direct", activity)
125 end
126 end
127 end
128
129 def create(%{to: to, actor: actor, context: context, object: object} = params) do
130 additional = params[:additional] || %{}
131 # only accept false as false value
132 local = !(params[:local] == false)
133 published = params[:published]
134
135 with create_data <-
136 make_create_data(
137 %{to: to, actor: actor, published: published, context: context, object: object},
138 additional
139 ),
140 {:ok, activity} <- insert(create_data, local),
141 :ok <- maybe_federate(activity),
142 {:ok, _actor} <- User.increase_note_count(actor) do
143 {:ok, activity}
144 end
145 end
146
147 def accept(%{to: to, actor: actor, object: object} = params) do
148 # only accept false as false value
149 local = !(params[:local] == false)
150
151 with data <- %{"to" => to, "type" => "Accept", "actor" => actor, "object" => object},
152 {:ok, activity} <- insert(data, local),
153 :ok <- maybe_federate(activity) do
154 {:ok, activity}
155 end
156 end
157
158 def reject(%{to: to, actor: actor, object: object} = params) do
159 # only accept false as false value
160 local = !(params[:local] == false)
161
162 with data <- %{"to" => to, "type" => "Reject", "actor" => actor, "object" => object},
163 {:ok, activity} <- insert(data, local),
164 :ok <- maybe_federate(activity) do
165 {:ok, activity}
166 end
167 end
168
169 def update(%{to: to, cc: cc, actor: actor, object: object} = params) do
170 # only accept false as false value
171 local = !(params[:local] == false)
172
173 with data <- %{
174 "to" => to,
175 "cc" => cc,
176 "type" => "Update",
177 "actor" => actor,
178 "object" => object
179 },
180 {:ok, activity} <- insert(data, local),
181 :ok <- maybe_federate(activity) do
182 {:ok, activity}
183 end
184 end
185
186 # TODO: This is weird, maybe we shouldn't check here if we can make the activity.
187 def like(
188 %User{ap_id: ap_id} = user,
189 %Object{data: %{"id" => _}} = object,
190 activity_id \\ nil,
191 local \\ true
192 ) do
193 with nil <- get_existing_like(ap_id, object),
194 like_data <- make_like_data(user, object, activity_id),
195 {:ok, activity} <- insert(like_data, local),
196 {:ok, object} <- add_like_to_object(activity, object),
197 :ok <- maybe_federate(activity) do
198 {:ok, activity, object}
199 else
200 %Activity{} = activity -> {:ok, activity, object}
201 error -> {:error, error}
202 end
203 end
204
205 def unlike(
206 %User{} = actor,
207 %Object{} = object,
208 activity_id \\ nil,
209 local \\ true
210 ) do
211 with %Activity{} = like_activity <- get_existing_like(actor.ap_id, object),
212 unlike_data <- make_unlike_data(actor, like_activity, activity_id),
213 {:ok, unlike_activity} <- insert(unlike_data, local),
214 {:ok, _activity} <- Repo.delete(like_activity),
215 {:ok, object} <- remove_like_from_object(like_activity, object),
216 :ok <- maybe_federate(unlike_activity) do
217 {:ok, unlike_activity, like_activity, object}
218 else
219 _e -> {:ok, object}
220 end
221 end
222
223 def announce(
224 %User{ap_id: _} = user,
225 %Object{data: %{"id" => _}} = object,
226 activity_id \\ nil,
227 local \\ true
228 ) do
229 with true <- is_public?(object),
230 announce_data <- make_announce_data(user, object, activity_id),
231 {:ok, activity} <- insert(announce_data, local),
232 {:ok, object} <- add_announce_to_object(activity, object),
233 :ok <- maybe_federate(activity) do
234 {:ok, activity, object}
235 else
236 error -> {:error, error}
237 end
238 end
239
240 def unannounce(
241 %User{} = actor,
242 %Object{} = object,
243 activity_id \\ nil,
244 local \\ true
245 ) do
246 with %Activity{} = announce_activity <- get_existing_announce(actor.ap_id, object),
247 unannounce_data <- make_unannounce_data(actor, announce_activity, activity_id),
248 {:ok, unannounce_activity} <- insert(unannounce_data, local),
249 :ok <- maybe_federate(unannounce_activity),
250 {:ok, _activity} <- Repo.delete(announce_activity),
251 {:ok, object} <- remove_announce_from_object(announce_activity, object) do
252 {:ok, unannounce_activity, object}
253 else
254 _e -> {:ok, object}
255 end
256 end
257
258 def follow(follower, followed, activity_id \\ nil, local \\ true) do
259 with data <- make_follow_data(follower, followed, activity_id),
260 {:ok, activity} <- insert(data, local),
261 :ok <- maybe_federate(activity) do
262 {:ok, activity}
263 end
264 end
265
266 def unfollow(follower, followed, activity_id \\ nil, local \\ true) do
267 with %Activity{} = follow_activity <- fetch_latest_follow(follower, followed),
268 {:ok, follow_activity} <- update_follow_state(follow_activity, "cancelled"),
269 unfollow_data <- make_unfollow_data(follower, followed, follow_activity, activity_id),
270 {:ok, activity} <- insert(unfollow_data, local),
271 :ok <- maybe_federate(activity) do
272 {:ok, activity}
273 end
274 end
275
276 def delete(%Object{data: %{"id" => id, "actor" => actor}} = object, local \\ true) do
277 user = User.get_cached_by_ap_id(actor)
278
279 data = %{
280 "type" => "Delete",
281 "actor" => actor,
282 "object" => id,
283 "to" => [user.follower_address, "https://www.w3.org/ns/activitystreams#Public"]
284 }
285
286 with {:ok, _} <- Object.delete(object),
287 {:ok, activity} <- insert(data, local),
288 :ok <- maybe_federate(activity),
289 {:ok, _actor} <- User.decrease_note_count(user) do
290 {:ok, activity}
291 end
292 end
293
294 def block(blocker, blocked, activity_id \\ nil, local \\ true) do
295 ap_config = Application.get_env(:pleroma, :activitypub)
296 unfollow_blocked = Keyword.get(ap_config, :unfollow_blocked)
297 outgoing_blocks = Keyword.get(ap_config, :outgoing_blocks)
298
299 with true <- unfollow_blocked do
300 follow_activity = fetch_latest_follow(blocker, blocked)
301
302 if follow_activity do
303 unfollow(blocker, blocked, nil, local)
304 end
305 end
306
307 with true <- outgoing_blocks,
308 block_data <- make_block_data(blocker, blocked, activity_id),
309 {:ok, activity} <- insert(block_data, local),
310 :ok <- maybe_federate(activity) do
311 {:ok, activity}
312 else
313 _e -> {:ok, nil}
314 end
315 end
316
317 def unblock(blocker, blocked, activity_id \\ nil, local \\ true) do
318 with %Activity{} = block_activity <- fetch_latest_block(blocker, blocked),
319 unblock_data <- make_unblock_data(blocker, blocked, block_activity, activity_id),
320 {:ok, activity} <- insert(unblock_data, local),
321 :ok <- maybe_federate(activity) do
322 {:ok, activity}
323 end
324 end
325
326 def fetch_activities_for_context(context, opts \\ %{}) do
327 public = ["https://www.w3.org/ns/activitystreams#Public"]
328
329 recipients =
330 if opts["user"], do: [opts["user"].ap_id | opts["user"].following] ++ public, else: public
331
332 query = from(activity in Activity)
333
334 query =
335 query
336 |> restrict_blocked(opts)
337 |> restrict_recipients(recipients, opts["user"])
338
339 query =
340 from(
341 activity in query,
342 where:
343 fragment(
344 "?->>'type' = ? and ?->>'context' = ?",
345 activity.data,
346 "Create",
347 activity.data,
348 ^context
349 ),
350 order_by: [desc: :id]
351 )
352
353 Repo.all(query)
354 end
355
356 def fetch_public_activities(opts \\ %{}) do
357 q = fetch_activities_query(["https://www.w3.org/ns/activitystreams#Public"], opts)
358
359 q
360 |> restrict_unlisted()
361 |> Repo.all()
362 |> Enum.reverse()
363 end
364
365 @valid_visibilities ~w[direct unlisted public private]
366
367 defp restrict_visibility(query, %{visibility: "direct"}) do
368 public = "https://www.w3.org/ns/activitystreams#Public"
369
370 from(
371 activity in query,
372 join: sender in User,
373 on: sender.ap_id == activity.actor,
374 # Are non-direct statuses with no to/cc possible?
375 where:
376 fragment(
377 "not (? && ?)",
378 [^public, sender.follower_address],
379 activity.recipients
380 )
381 )
382 end
383
384 defp restrict_visibility(_query, %{visibility: visibility})
385 when visibility not in @valid_visibilities do
386 Logger.error("Could not restrict visibility to #{visibility}")
387 end
388
389 defp restrict_visibility(query, _visibility), do: query
390
391 def fetch_user_activities(user, reading_user, params \\ %{}) do
392 params =
393 params
394 |> Map.put("type", ["Create", "Announce"])
395 |> Map.put("actor_id", user.ap_id)
396 |> Map.put("whole_db", true)
397
398 recipients =
399 if reading_user do
400 ["https://www.w3.org/ns/activitystreams#Public"] ++
401 [reading_user.ap_id | reading_user.following]
402 else
403 ["https://www.w3.org/ns/activitystreams#Public"]
404 end
405
406 fetch_activities(recipients, params)
407 |> Enum.reverse()
408 end
409
410 defp restrict_since(query, %{"since_id" => since_id}) do
411 from(activity in query, where: activity.id > ^since_id)
412 end
413
414 defp restrict_since(query, _), do: query
415
416 defp restrict_tag(query, %{"tag" => tag}) do
417 from(
418 activity in query,
419 where: fragment("? <@ (? #> '{\"object\",\"tag\"}')", ^tag, activity.data)
420 )
421 end
422
423 defp restrict_tag(query, _), do: query
424
425 defp restrict_to_cc(query, recipients_to, recipients_cc) do
426 from(
427 activity in query,
428 where:
429 fragment(
430 "(?->'to' \\?| ?) or (?->'cc' \\?| ?)",
431 activity.data,
432 ^recipients_to,
433 activity.data,
434 ^recipients_cc
435 )
436 )
437 end
438
439 defp restrict_recipients(query, [], _user), do: query
440
441 defp restrict_recipients(query, recipients, nil) do
442 from(activity in query, where: fragment("? && ?", ^recipients, activity.recipients))
443 end
444
445 defp restrict_recipients(query, recipients, user) do
446 from(
447 activity in query,
448 where: fragment("? && ?", ^recipients, activity.recipients),
449 or_where: activity.actor == ^user.ap_id
450 )
451 end
452
453 defp restrict_limit(query, %{"limit" => limit}) do
454 from(activity in query, limit: ^limit)
455 end
456
457 defp restrict_limit(query, _), do: query
458
459 defp restrict_local(query, %{"local_only" => true}) do
460 from(activity in query, where: activity.local == true)
461 end
462
463 defp restrict_local(query, _), do: query
464
465 defp restrict_max(query, %{"max_id" => max_id}) do
466 from(activity in query, where: activity.id < ^max_id)
467 end
468
469 defp restrict_max(query, _), do: query
470
471 defp restrict_actor(query, %{"actor_id" => actor_id}) do
472 from(activity in query, where: activity.actor == ^actor_id)
473 end
474
475 defp restrict_actor(query, _), do: query
476
477 defp restrict_type(query, %{"type" => type}) when is_binary(type) do
478 restrict_type(query, %{"type" => [type]})
479 end
480
481 defp restrict_type(query, %{"type" => type}) do
482 from(activity in query, where: fragment("?->>'type' = ANY(?)", activity.data, ^type))
483 end
484
485 defp restrict_type(query, _), do: query
486
487 defp restrict_favorited_by(query, %{"favorited_by" => ap_id}) do
488 from(
489 activity in query,
490 where: fragment("? <@ (? #> '{\"object\",\"likes\"}')", ^ap_id, activity.data)
491 )
492 end
493
494 defp restrict_favorited_by(query, _), do: query
495
496 defp restrict_media(query, %{"only_media" => val}) when val == "true" or val == "1" do
497 from(
498 activity in query,
499 where: fragment("not (? #> '{\"object\",\"attachment\"}' = ?)", activity.data, ^[])
500 )
501 end
502
503 defp restrict_media(query, _), do: query
504
505 defp restrict_replies(query, %{"exclude_replies" => val}) when val == "true" or val == "1" do
506 from(
507 activity in query,
508 where: fragment("?->'object'->>'inReplyTo' is null", activity.data)
509 )
510 end
511
512 defp restrict_replies(query, _), do: query
513
514 defp restrict_reblogs(query, %{"exclude_reblogs" => val}) when val == "true" or val == "1" do
515 from(activity in query, where: fragment("?->>'type' != 'Announce'", activity.data))
516 end
517
518 defp restrict_reblogs(query, _), do: query
519
520 defp restrict_blocked(query, %{"blocking_user" => %User{info: info}}) do
521 blocks = info.blocks || []
522 domain_blocks = info.domain_blocks || []
523
524 from(
525 activity in query,
526 where: fragment("not (? = ANY(?))", activity.actor, ^blocks),
527 where: fragment("not (?->'to' \\?| ?)", activity.data, ^blocks),
528 where: fragment("not (split_part(?, '/', 3) = ANY(?))", activity.actor, ^domain_blocks)
529 )
530 end
531
532 defp restrict_blocked(query, _), do: query
533
534 defp restrict_unlisted(query) do
535 from(
536 activity in query,
537 where:
538 fragment(
539 "not (coalesce(?->'cc', '{}'::jsonb) \\?| ?)",
540 activity.data,
541 ^["https://www.w3.org/ns/activitystreams#Public"]
542 )
543 )
544 end
545
546 def fetch_activities_query(recipients, opts \\ %{}) do
547 base_query =
548 from(
549 activity in Activity,
550 limit: 20,
551 order_by: [fragment("? desc nulls last", activity.id)]
552 )
553
554 base_query
555 |> restrict_recipients(recipients, opts["user"])
556 |> restrict_tag(opts)
557 |> restrict_since(opts)
558 |> restrict_local(opts)
559 |> restrict_limit(opts)
560 |> restrict_max(opts)
561 |> restrict_actor(opts)
562 |> restrict_type(opts)
563 |> restrict_favorited_by(opts)
564 |> restrict_blocked(opts)
565 |> restrict_media(opts)
566 |> restrict_visibility(opts)
567 |> restrict_replies(opts)
568 |> restrict_reblogs(opts)
569 end
570
571 def fetch_activities(recipients, opts \\ %{}) do
572 fetch_activities_query(recipients, opts)
573 |> Repo.all()
574 |> Enum.reverse()
575 end
576
577 def fetch_activities_bounded(recipients_to, recipients_cc, opts \\ %{}) do
578 fetch_activities_query([], opts)
579 |> restrict_to_cc(recipients_to, recipients_cc)
580 |> Repo.all()
581 |> Enum.reverse()
582 end
583
584 def upload(file, opts \\ []) do
585 with {:ok, data} <- Upload.store(file, opts) do
586 obj_data =
587 if opts[:actor] do
588 Map.put(data, "actor", opts[:actor])
589 else
590 data
591 end
592
593 Repo.insert(%Object{data: obj_data})
594 end
595 end
596
597 def user_data_from_user_object(data) do
598 avatar =
599 data["icon"]["url"] &&
600 %{
601 "type" => "Image",
602 "url" => [%{"href" => data["icon"]["url"]}]
603 }
604
605 banner =
606 data["image"]["url"] &&
607 %{
608 "type" => "Image",
609 "url" => [%{"href" => data["image"]["url"]}]
610 }
611
612 locked = data["manuallyApprovesFollowers"] || false
613 data = Transmogrifier.maybe_fix_user_object(data)
614
615 user_data = %{
616 ap_id: data["id"],
617 info: %{
618 "ap_enabled" => true,
619 "source_data" => data,
620 "banner" => banner,
621 "locked" => locked
622 },
623 avatar: avatar,
624 name: data["name"],
625 follower_address: data["followers"],
626 bio: data["summary"]
627 }
628
629 # nickname can be nil because of virtual actors
630 user_data =
631 if data["preferredUsername"] do
632 Map.put(
633 user_data,
634 :nickname,
635 "#{data["preferredUsername"]}@#{URI.parse(data["id"]).host}"
636 )
637 else
638 Map.put(user_data, :nickname, nil)
639 end
640
641 {:ok, user_data}
642 end
643
644 def fetch_and_prepare_user_from_ap_id(ap_id) do
645 with {:ok, data} <- fetch_and_contain_remote_object_from_id(ap_id) do
646 user_data_from_user_object(data)
647 else
648 e -> Logger.error("Could not decode user at fetch #{ap_id}, #{inspect(e)}")
649 end
650 end
651
652 def make_user_from_ap_id(ap_id) do
653 if _user = User.get_by_ap_id(ap_id) do
654 Transmogrifier.upgrade_user_from_ap_id(ap_id)
655 else
656 with {:ok, data} <- fetch_and_prepare_user_from_ap_id(ap_id) do
657 User.insert_or_update_user(data)
658 else
659 e -> {:error, e}
660 end
661 end
662 end
663
664 def make_user_from_nickname(nickname) do
665 with {:ok, %{"ap_id" => ap_id}} when not is_nil(ap_id) <- WebFinger.finger(nickname) do
666 make_user_from_ap_id(ap_id)
667 else
668 _e -> {:error, "No AP id in WebFinger"}
669 end
670 end
671
672 def should_federate?(inbox, public) do
673 if public do
674 true
675 else
676 inbox_info = URI.parse(inbox)
677 !Enum.member?(Pleroma.Config.get([:instance, :quarantined_instances], []), inbox_info.host)
678 end
679 end
680
681 def publish(actor, activity) do
682 followers =
683 if actor.follower_address in activity.recipients do
684 {:ok, followers} = User.get_followers(actor)
685 followers |> Enum.filter(&(!&1.local))
686 else
687 []
688 end
689
690 public = is_public?(activity)
691
692 remote_inboxes =
693 (Pleroma.Web.Salmon.remote_users(activity) ++ followers)
694 |> Enum.filter(fn user -> User.ap_enabled?(user) end)
695 |> Enum.map(fn %{info: %{source_data: data}} ->
696 (is_map(data["endpoints"]) && Map.get(data["endpoints"], "sharedInbox")) || data["inbox"]
697 end)
698 |> Enum.uniq()
699 |> Enum.filter(fn inbox -> should_federate?(inbox, public) end)
700
701 {:ok, data} = Transmogrifier.prepare_outgoing(activity.data)
702 json = Jason.encode!(data)
703
704 Enum.each(remote_inboxes, fn inbox ->
705 Federator.enqueue(:publish_single_ap, %{
706 inbox: inbox,
707 json: json,
708 actor: actor,
709 id: activity.data["id"]
710 })
711 end)
712 end
713
714 def publish_one(%{inbox: inbox, json: json, actor: actor, id: id}) do
715 Logger.info("Federating #{id} to #{inbox}")
716 host = URI.parse(inbox).host
717
718 digest = "SHA-256=" <> (:crypto.hash(:sha256, json) |> Base.encode64())
719
720 signature =
721 Pleroma.Web.HTTPSignatures.sign(actor, %{
722 host: host,
723 "content-length": byte_size(json),
724 digest: digest
725 })
726
727 @httpoison.post(
728 inbox,
729 json,
730 [
731 {"Content-Type", "application/activity+json"},
732 {"signature", signature},
733 {"digest", digest}
734 ]
735 )
736 end
737
738 # TODO:
739 # This will create a Create activity, which we need internally at the moment.
740 def fetch_object_from_id(id) do
741 if object = Object.get_cached_by_ap_id(id) do
742 {:ok, object}
743 else
744 Logger.info("Fetching #{id} via AP")
745
746 with {:ok, data} <- fetch_and_contain_remote_object_from_id(id),
747 nil <- Object.normalize(data),
748 params <- %{
749 "type" => "Create",
750 "to" => data["to"],
751 "cc" => data["cc"],
752 "actor" => data["actor"] || data["attributedTo"],
753 "object" => data
754 },
755 :ok <- Transmogrifier.contain_origin(id, params),
756 {:ok, activity} <- Transmogrifier.handle_incoming(params) do
757 {:ok, Object.normalize(activity.data["object"])}
758 else
759 {:error, {:reject, nil}} ->
760 {:reject, nil}
761
762 object = %Object{} ->
763 {:ok, object}
764
765 _e ->
766 Logger.info("Couldn't get object via AP, trying out OStatus fetching...")
767
768 case OStatus.fetch_activity_from_url(id) do
769 {:ok, [activity | _]} -> {:ok, Object.normalize(activity.data["object"])}
770 e -> e
771 end
772 end
773 end
774 end
775
776 def fetch_and_contain_remote_object_from_id(id) do
777 Logger.info("Fetching #{id} via AP")
778
779 with true <- String.starts_with?(id, "http"),
780 {:ok, %{body: body, status: code}} when code in 200..299 <-
781 @httpoison.get(
782 id,
783 [{:Accept, "application/activity+json"}]
784 ),
785 {:ok, data} <- Jason.decode(body),
786 :ok <- Transmogrifier.contain_origin_from_id(id, data) do
787 {:ok, data}
788 else
789 e ->
790 {:error, e}
791 end
792 end
793
794 def is_public?(%Object{data: %{"type" => "Tombstone"}}) do
795 false
796 end
797
798 def is_public?(activity) do
799 "https://www.w3.org/ns/activitystreams#Public" in (activity.data["to"] ++
800 (activity.data["cc"] || []))
801 end
802
803 def visible_for_user?(activity, nil) do
804 is_public?(activity)
805 end
806
807 def visible_for_user?(activity, user) do
808 x = [user.ap_id | user.following]
809 y = activity.data["to"] ++ (activity.data["cc"] || [])
810 visible_for_user?(activity, nil) || Enum.any?(x, &(&1 in y))
811 end
812
813 # guard
814 def entire_thread_visible_for_user?(nil, _user), do: false
815
816 # child
817 def entire_thread_visible_for_user?(
818 %Activity{data: %{"object" => %{"inReplyTo" => parent_id}}} = tail,
819 user
820 )
821 when is_binary(parent_id) do
822 parent = Activity.get_in_reply_to_activity(tail)
823 visible_for_user?(tail, user) && entire_thread_visible_for_user?(parent, user)
824 end
825
826 # root
827 def entire_thread_visible_for_user?(tail, user), do: visible_for_user?(tail, user)
828
829 # filter out broken threads
830 def contain_broken_threads(%Activity{} = activity, %User{} = user) do
831 entire_thread_visible_for_user?(activity, user)
832 end
833
834 # do post-processing on a specific activity
835 def contain_activity(%Activity{} = activity, %User{} = user) do
836 contain_broken_threads(activity, user)
837 end
838
839 # do post-processing on a timeline
840 def contain_timeline(timeline, user) do
841 timeline
842 |> Enum.filter(fn activity ->
843 contain_activity(activity, user)
844 end)
845 end
846 end