Merge branch 'develop' of git.pleroma.social:pleroma/pleroma into feature/pinned...
[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 |> Map.put("pinned_activity_ids", user.info.pinned_activities)
398
399 recipients =
400 if reading_user do
401 ["https://www.w3.org/ns/activitystreams#Public"] ++
402 [reading_user.ap_id | reading_user.following]
403 else
404 ["https://www.w3.org/ns/activitystreams#Public"]
405 end
406
407 fetch_activities(recipients, params)
408 |> Enum.reverse()
409 end
410
411 defp restrict_since(query, %{"since_id" => since_id}) do
412 from(activity in query, where: activity.id > ^since_id)
413 end
414
415 defp restrict_since(query, _), do: query
416
417 defp restrict_tag(query, %{"tag" => tag}) do
418 from(
419 activity in query,
420 where: fragment("? <@ (? #> '{\"object\",\"tag\"}')", ^tag, activity.data)
421 )
422 end
423
424 defp restrict_tag(query, _), do: query
425
426 defp restrict_to_cc(query, recipients_to, recipients_cc) do
427 from(
428 activity in query,
429 where:
430 fragment(
431 "(?->'to' \\?| ?) or (?->'cc' \\?| ?)",
432 activity.data,
433 ^recipients_to,
434 activity.data,
435 ^recipients_cc
436 )
437 )
438 end
439
440 defp restrict_recipients(query, [], _user), do: query
441
442 defp restrict_recipients(query, recipients, nil) do
443 from(activity in query, where: fragment("? && ?", ^recipients, activity.recipients))
444 end
445
446 defp restrict_recipients(query, recipients, user) do
447 from(
448 activity in query,
449 where: fragment("? && ?", ^recipients, activity.recipients),
450 or_where: activity.actor == ^user.ap_id
451 )
452 end
453
454 defp restrict_limit(query, %{"limit" => limit}) do
455 from(activity in query, limit: ^limit)
456 end
457
458 defp restrict_limit(query, _), do: query
459
460 defp restrict_local(query, %{"local_only" => true}) do
461 from(activity in query, where: activity.local == true)
462 end
463
464 defp restrict_local(query, _), do: query
465
466 defp restrict_max(query, %{"max_id" => max_id}) do
467 from(activity in query, where: activity.id < ^max_id)
468 end
469
470 defp restrict_max(query, _), do: query
471
472 defp restrict_actor(query, %{"actor_id" => actor_id}) do
473 from(activity in query, where: activity.actor == ^actor_id)
474 end
475
476 defp restrict_actor(query, _), do: query
477
478 defp restrict_type(query, %{"type" => type}) when is_binary(type) do
479 restrict_type(query, %{"type" => [type]})
480 end
481
482 defp restrict_type(query, %{"type" => type}) do
483 from(activity in query, where: fragment("?->>'type' = ANY(?)", activity.data, ^type))
484 end
485
486 defp restrict_type(query, _), do: query
487
488 defp restrict_favorited_by(query, %{"favorited_by" => ap_id}) do
489 from(
490 activity in query,
491 where: fragment("? <@ (? #> '{\"object\",\"likes\"}')", ^ap_id, activity.data)
492 )
493 end
494
495 defp restrict_favorited_by(query, _), do: query
496
497 defp restrict_media(query, %{"only_media" => val}) when val == "true" or val == "1" do
498 from(
499 activity in query,
500 where: fragment("not (? #> '{\"object\",\"attachment\"}' = ?)", activity.data, ^[])
501 )
502 end
503
504 defp restrict_media(query, _), do: query
505
506 defp restrict_replies(query, %{"exclude_replies" => val}) when val == "true" or val == "1" do
507 from(
508 activity in query,
509 where: fragment("?->'object'->>'inReplyTo' is null", activity.data)
510 )
511 end
512
513 defp restrict_replies(query, _), do: query
514
515 defp restrict_reblogs(query, %{"exclude_reblogs" => val}) when val == "true" or val == "1" do
516 from(activity in query, where: fragment("?->>'type' != 'Announce'", activity.data))
517 end
518
519 defp restrict_reblogs(query, _), do: query
520
521 # Only search through last 100_000 activities by default
522 defp restrict_recent(query, %{"whole_db" => true}), do: query
523
524 defp restrict_recent(query, _) do
525 since = (Repo.aggregate(Activity, :max, :id) || 0) - 100_000
526
527 from(activity in query, where: activity.id > ^since)
528 end
529
530 defp restrict_blocked(query, %{"blocking_user" => %User{info: info}}) do
531 blocks = info.blocks || []
532 domain_blocks = info.domain_blocks || []
533
534 from(
535 activity in query,
536 where: fragment("not (? = ANY(?))", activity.actor, ^blocks),
537 where: fragment("not (?->'to' \\?| ?)", activity.data, ^blocks),
538 where: fragment("not (split_part(?, '/', 3) = ANY(?))", activity.actor, ^domain_blocks)
539 )
540 end
541
542 defp restrict_blocked(query, _), do: query
543
544 defp restrict_unlisted(query) do
545 from(
546 activity in query,
547 where:
548 fragment(
549 "not (coalesce(?->'cc', '{}'::jsonb) \\?| ?)",
550 activity.data,
551 ^["https://www.w3.org/ns/activitystreams#Public"]
552 )
553 )
554 end
555
556 defp restrict_pinned(query, %{"pinned" => "true", "pinned_activity_ids" => ids}) do
557 from(activity in query, where: activity.id in ^ids)
558 end
559
560 defp restrict_pinned(query, _), do: query
561
562 def fetch_activities_query(recipients, opts \\ %{}) do
563 base_query =
564 from(
565 activity in Activity,
566 limit: 20,
567 order_by: [fragment("? desc nulls last", activity.id)]
568 )
569
570 base_query
571 |> restrict_recipients(recipients, opts["user"])
572 |> restrict_tag(opts)
573 |> restrict_since(opts)
574 |> restrict_local(opts)
575 |> restrict_limit(opts)
576 |> restrict_max(opts)
577 |> restrict_actor(opts)
578 |> restrict_type(opts)
579 |> restrict_favorited_by(opts)
580 |> restrict_recent(opts)
581 |> restrict_blocked(opts)
582 |> restrict_media(opts)
583 |> restrict_visibility(opts)
584 |> restrict_replies(opts)
585 |> restrict_reblogs(opts)
586 |> restrict_pinned(opts)
587 end
588
589 def fetch_activities(recipients, opts \\ %{}) do
590 fetch_activities_query(recipients, opts)
591 |> Repo.all()
592 |> Enum.reverse()
593 end
594
595 def fetch_activities_bounded(recipients_to, recipients_cc, opts \\ %{}) do
596 fetch_activities_query([], opts)
597 |> restrict_to_cc(recipients_to, recipients_cc)
598 |> Repo.all()
599 |> Enum.reverse()
600 end
601
602 def upload(file, opts \\ []) do
603 with {:ok, data} <- Upload.store(file, opts) do
604 obj_data =
605 if opts[:actor] do
606 Map.put(data, "actor", opts[:actor])
607 else
608 data
609 end
610
611 Repo.insert(%Object{data: obj_data})
612 end
613 end
614
615 def user_data_from_user_object(data) do
616 avatar =
617 data["icon"]["url"] &&
618 %{
619 "type" => "Image",
620 "url" => [%{"href" => data["icon"]["url"]}]
621 }
622
623 banner =
624 data["image"]["url"] &&
625 %{
626 "type" => "Image",
627 "url" => [%{"href" => data["image"]["url"]}]
628 }
629
630 locked = data["manuallyApprovesFollowers"] || false
631 data = Transmogrifier.maybe_fix_user_object(data)
632
633 user_data = %{
634 ap_id: data["id"],
635 info: %{
636 "ap_enabled" => true,
637 "source_data" => data,
638 "banner" => banner,
639 "locked" => locked
640 },
641 avatar: avatar,
642 name: data["name"],
643 follower_address: data["followers"],
644 bio: data["summary"]
645 }
646
647 # nickname can be nil because of virtual actors
648 user_data =
649 if data["preferredUsername"] do
650 Map.put(
651 user_data,
652 :nickname,
653 "#{data["preferredUsername"]}@#{URI.parse(data["id"]).host}"
654 )
655 else
656 Map.put(user_data, :nickname, nil)
657 end
658
659 {:ok, user_data}
660 end
661
662 def fetch_and_prepare_user_from_ap_id(ap_id) do
663 with {:ok, data} <- fetch_and_contain_remote_object_from_id(ap_id) do
664 user_data_from_user_object(data)
665 else
666 e -> Logger.error("Could not decode user at fetch #{ap_id}, #{inspect(e)}")
667 end
668 end
669
670 def make_user_from_ap_id(ap_id) do
671 if _user = User.get_by_ap_id(ap_id) do
672 Transmogrifier.upgrade_user_from_ap_id(ap_id)
673 else
674 with {:ok, data} <- fetch_and_prepare_user_from_ap_id(ap_id) do
675 User.insert_or_update_user(data)
676 else
677 e -> {:error, e}
678 end
679 end
680 end
681
682 def make_user_from_nickname(nickname) do
683 with {:ok, %{"ap_id" => ap_id}} when not is_nil(ap_id) <- WebFinger.finger(nickname) do
684 make_user_from_ap_id(ap_id)
685 else
686 _e -> {:error, "No AP id in WebFinger"}
687 end
688 end
689
690 def should_federate?(inbox, public) do
691 if public do
692 true
693 else
694 inbox_info = URI.parse(inbox)
695 !Enum.member?(Pleroma.Config.get([:instance, :quarantined_instances], []), inbox_info.host)
696 end
697 end
698
699 def publish(actor, activity) do
700 followers =
701 if actor.follower_address in activity.recipients do
702 {:ok, followers} = User.get_followers(actor)
703 followers |> Enum.filter(&(!&1.local))
704 else
705 []
706 end
707
708 public = is_public?(activity)
709
710 remote_inboxes =
711 (Pleroma.Web.Salmon.remote_users(activity) ++ followers)
712 |> Enum.filter(fn user -> User.ap_enabled?(user) end)
713 |> Enum.map(fn %{info: %{source_data: data}} ->
714 (is_map(data["endpoints"]) && Map.get(data["endpoints"], "sharedInbox")) || data["inbox"]
715 end)
716 |> Enum.uniq()
717 |> Enum.filter(fn inbox -> should_federate?(inbox, public) end)
718
719 {:ok, data} = Transmogrifier.prepare_outgoing(activity.data)
720 json = Jason.encode!(data)
721
722 Enum.each(remote_inboxes, fn inbox ->
723 Federator.enqueue(:publish_single_ap, %{
724 inbox: inbox,
725 json: json,
726 actor: actor,
727 id: activity.data["id"]
728 })
729 end)
730 end
731
732 def publish_one(%{inbox: inbox, json: json, actor: actor, id: id}) do
733 Logger.info("Federating #{id} to #{inbox}")
734 host = URI.parse(inbox).host
735
736 digest = "SHA-256=" <> (:crypto.hash(:sha256, json) |> Base.encode64())
737
738 signature =
739 Pleroma.Web.HTTPSignatures.sign(actor, %{
740 host: host,
741 "content-length": byte_size(json),
742 digest: digest
743 })
744
745 @httpoison.post(
746 inbox,
747 json,
748 [
749 {"Content-Type", "application/activity+json"},
750 {"signature", signature},
751 {"digest", digest}
752 ]
753 )
754 end
755
756 # TODO:
757 # This will create a Create activity, which we need internally at the moment.
758 def fetch_object_from_id(id) do
759 if object = Object.get_cached_by_ap_id(id) do
760 {:ok, object}
761 else
762 Logger.info("Fetching #{id} via AP")
763
764 with {:ok, data} <- fetch_and_contain_remote_object_from_id(id),
765 nil <- Object.normalize(data),
766 params <- %{
767 "type" => "Create",
768 "to" => data["to"],
769 "cc" => data["cc"],
770 "actor" => data["actor"] || data["attributedTo"],
771 "object" => data
772 },
773 :ok <- Transmogrifier.contain_origin(id, params),
774 {:ok, activity} <- Transmogrifier.handle_incoming(params) do
775 {:ok, Object.normalize(activity.data["object"])}
776 else
777 {:error, {:reject, nil}} ->
778 {:reject, nil}
779
780 object = %Object{} ->
781 {:ok, object}
782
783 _e ->
784 Logger.info("Couldn't get object via AP, trying out OStatus fetching...")
785
786 case OStatus.fetch_activity_from_url(id) do
787 {:ok, [activity | _]} -> {:ok, Object.normalize(activity.data["object"])}
788 e -> e
789 end
790 end
791 end
792 end
793
794 def fetch_and_contain_remote_object_from_id(id) do
795 Logger.info("Fetching #{id} via AP")
796
797 with true <- String.starts_with?(id, "http"),
798 {:ok, %{body: body, status: code}} when code in 200..299 <-
799 @httpoison.get(
800 id,
801 [{:Accept, "application/activity+json"}]
802 ),
803 {:ok, data} <- Jason.decode(body),
804 :ok <- Transmogrifier.contain_origin_from_id(id, data) do
805 {:ok, data}
806 else
807 e ->
808 {:error, e}
809 end
810 end
811
812 def is_public?(%Object{data: %{"type" => "Tombstone"}}) do
813 false
814 end
815
816 def is_public?(activity) do
817 "https://www.w3.org/ns/activitystreams#Public" in (activity.data["to"] ++
818 (activity.data["cc"] || []))
819 end
820
821 def visible_for_user?(activity, nil) do
822 is_public?(activity)
823 end
824
825 def visible_for_user?(activity, user) do
826 x = [user.ap_id | user.following]
827 y = activity.data["to"] ++ (activity.data["cc"] || [])
828 visible_for_user?(activity, nil) || Enum.any?(x, &(&1 in y))
829 end
830
831 # guard
832 def entire_thread_visible_for_user?(nil, _user), do: false
833
834 # child
835 def entire_thread_visible_for_user?(
836 %Activity{data: %{"object" => %{"inReplyTo" => parent_id}}} = tail,
837 user
838 )
839 when is_binary(parent_id) do
840 parent = Activity.get_in_reply_to_activity(tail)
841 visible_for_user?(tail, user) && entire_thread_visible_for_user?(parent, user)
842 end
843
844 # root
845 def entire_thread_visible_for_user?(tail, user), do: visible_for_user?(tail, user)
846
847 # filter out broken threads
848 def contain_broken_threads(%Activity{} = activity, %User{} = user) do
849 entire_thread_visible_for_user?(activity, user)
850 end
851
852 # do post-processing on a specific activity
853 def contain_activity(%Activity{} = activity, %User{} = user) do
854 contain_broken_threads(activity, user)
855 end
856
857 # do post-processing on a timeline
858 def contain_timeline(timeline, user) do
859 timeline
860 |> Enum.filter(fn activity ->
861 contain_activity(activity, user)
862 end)
863 end
864 end