ChatMessagesHandling: Strip HTML of incoming messages.
[akkoma] / lib / pleroma / web / activity_pub / activity_pub.ex
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2020 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
7 alias Pleroma.Activity.Ir.Topics
8 alias Pleroma.Config
9 alias Pleroma.Constants
10 alias Pleroma.Conversation
11 alias Pleroma.Conversation.Participation
12 alias Pleroma.Notification
13 alias Pleroma.Object
14 alias Pleroma.Object.Containment
15 alias Pleroma.Object.Fetcher
16 alias Pleroma.Pagination
17 alias Pleroma.Repo
18 alias Pleroma.Upload
19 alias Pleroma.User
20 alias Pleroma.Web.ActivityPub.MRF
21 alias Pleroma.Web.ActivityPub.Transmogrifier
22 alias Pleroma.Web.ActivityPub.Utils
23 alias Pleroma.Web.Streamer
24 alias Pleroma.Web.WebFinger
25 alias Pleroma.Workers.BackgroundWorker
26
27 import Ecto.Query
28 import Pleroma.Web.ActivityPub.Utils
29 import Pleroma.Web.ActivityPub.Visibility
30
31 require Logger
32 require Pleroma.Constants
33
34 # For Announce activities, we filter the recipients based on following status for any actors
35 # that match actual users. See issue #164 for more information about why this is necessary.
36 defp get_recipients(%{"type" => "Announce"} = data) do
37 to = Map.get(data, "to", [])
38 cc = Map.get(data, "cc", [])
39 bcc = Map.get(data, "bcc", [])
40 actor = User.get_cached_by_ap_id(data["actor"])
41
42 recipients =
43 Enum.filter(Enum.concat([to, cc, bcc]), fn recipient ->
44 case User.get_cached_by_ap_id(recipient) do
45 nil -> true
46 user -> User.following?(user, actor)
47 end
48 end)
49
50 {recipients, to, cc}
51 end
52
53 defp get_recipients(%{"type" => "Create"} = data) do
54 to = Map.get(data, "to", [])
55 cc = Map.get(data, "cc", [])
56 bcc = Map.get(data, "bcc", [])
57 actor = Map.get(data, "actor", [])
58 recipients = [to, cc, bcc, [actor]] |> Enum.concat() |> Enum.uniq()
59 {recipients, to, cc}
60 end
61
62 defp get_recipients(data) do
63 to = Map.get(data, "to", [])
64 cc = Map.get(data, "cc", [])
65 bcc = Map.get(data, "bcc", [])
66 recipients = Enum.concat([to, cc, bcc])
67 {recipients, to, cc}
68 end
69
70 defp check_actor_is_active(actor) do
71 if not is_nil(actor) do
72 with user <- User.get_cached_by_ap_id(actor),
73 false <- user.deactivated do
74 true
75 else
76 _e -> false
77 end
78 else
79 true
80 end
81 end
82
83 defp check_remote_limit(%{"object" => %{"content" => content}}) when not is_nil(content) do
84 limit = Config.get([:instance, :remote_limit])
85 String.length(content) <= limit
86 end
87
88 defp check_remote_limit(_), do: true
89
90 def increase_note_count_if_public(actor, object) do
91 if is_public?(object), do: User.increase_note_count(actor), else: {:ok, actor}
92 end
93
94 def decrease_note_count_if_public(actor, object) do
95 if is_public?(object), do: User.decrease_note_count(actor), else: {:ok, actor}
96 end
97
98 def increase_replies_count_if_reply(%{
99 "object" => %{"inReplyTo" => reply_ap_id} = object,
100 "type" => "Create"
101 }) do
102 if is_public?(object) do
103 Object.increase_replies_count(reply_ap_id)
104 end
105 end
106
107 def increase_replies_count_if_reply(_create_data), do: :noop
108
109 def decrease_replies_count_if_reply(%Object{
110 data: %{"inReplyTo" => reply_ap_id} = object
111 }) do
112 if is_public?(object) do
113 Object.decrease_replies_count(reply_ap_id)
114 end
115 end
116
117 def decrease_replies_count_if_reply(_object), do: :noop
118
119 def increase_poll_votes_if_vote(%{
120 "object" => %{"inReplyTo" => reply_ap_id, "name" => name},
121 "type" => "Create"
122 }) do
123 Object.increase_vote_count(reply_ap_id, name)
124 end
125
126 def increase_poll_votes_if_vote(_create_data), do: :noop
127
128 @spec persist(map(), keyword()) :: {:ok, Activity.t() | Object.t()}
129 def persist(object, meta) do
130 with local <- Keyword.fetch!(meta, :local),
131 {recipients, _, _} <- get_recipients(object),
132 {:ok, activity} <-
133 Repo.insert(%Activity{
134 data: object,
135 local: local,
136 recipients: recipients,
137 actor: object["actor"]
138 }) do
139 {:ok, activity, meta}
140 end
141 end
142
143 @spec insert(map(), boolean(), boolean(), boolean()) :: {:ok, Activity.t()} | {:error, any()}
144 def insert(map, local \\ true, fake \\ false, bypass_actor_check \\ false) when is_map(map) do
145 with nil <- Activity.normalize(map),
146 map <- lazy_put_activity_defaults(map, fake),
147 true <- bypass_actor_check || check_actor_is_active(map["actor"]),
148 {_, true} <- {:remote_limit_error, check_remote_limit(map)},
149 {:ok, map} <- MRF.filter(map),
150 {recipients, _, _} = get_recipients(map),
151 {:fake, false, map, recipients} <- {:fake, fake, map, recipients},
152 {:containment, :ok} <- {:containment, Containment.contain_child(map)},
153 {:ok, map, object} <- insert_full_object(map) do
154 {:ok, activity} =
155 Repo.insert(%Activity{
156 data: map,
157 local: local,
158 actor: map["actor"],
159 recipients: recipients
160 })
161
162 # Splice in the child object if we have one.
163 activity =
164 if not is_nil(object) do
165 Map.put(activity, :object, object)
166 else
167 activity
168 end
169
170 BackgroundWorker.enqueue("fetch_data_for_activity", %{"activity_id" => activity.id})
171
172 Notification.create_notifications(activity)
173
174 conversation = create_or_bump_conversation(activity, map["actor"])
175 participations = get_participations(conversation)
176 stream_out(activity)
177 stream_out_participations(participations)
178 {:ok, activity}
179 else
180 %Activity{} = activity ->
181 {:ok, activity}
182
183 {:fake, true, map, recipients} ->
184 activity = %Activity{
185 data: map,
186 local: local,
187 actor: map["actor"],
188 recipients: recipients,
189 id: "pleroma:fakeid"
190 }
191
192 Pleroma.Web.RichMedia.Helpers.fetch_data_for_activity(activity)
193 {:ok, activity}
194
195 error ->
196 {:error, error}
197 end
198 end
199
200 defp create_or_bump_conversation(activity, actor) do
201 with {:ok, conversation} <- Conversation.create_or_bump_for(activity),
202 %User{} = user <- User.get_cached_by_ap_id(actor),
203 Participation.mark_as_read(user, conversation) do
204 {:ok, conversation}
205 end
206 end
207
208 defp get_participations({:ok, conversation}) do
209 conversation
210 |> Repo.preload(:participations, force: true)
211 |> Map.get(:participations)
212 end
213
214 defp get_participations(_), do: []
215
216 def stream_out_participations(participations) do
217 participations =
218 participations
219 |> Repo.preload(:user)
220
221 Streamer.stream("participation", participations)
222 end
223
224 def stream_out_participations(%Object{data: %{"context" => context}}, user) do
225 with %Conversation{} = conversation <- Conversation.get_for_ap_id(context),
226 conversation = Repo.preload(conversation, :participations),
227 last_activity_id =
228 fetch_latest_activity_id_for_context(conversation.ap_id, %{
229 "user" => user,
230 "blocking_user" => user
231 }) do
232 if last_activity_id do
233 stream_out_participations(conversation.participations)
234 end
235 end
236 end
237
238 def stream_out_participations(_, _), do: :noop
239
240 def stream_out(%Activity{data: %{"type" => data_type}} = activity)
241 when data_type in ["Create", "Announce", "Delete"] do
242 activity
243 |> Topics.get_activity_topics()
244 |> Streamer.stream(activity)
245 end
246
247 def stream_out(_activity) do
248 :noop
249 end
250
251 @spec create(map(), boolean()) :: {:ok, Activity.t()} | {:error, any()}
252 def create(params, fake \\ false) do
253 with {:ok, result} <- Repo.transaction(fn -> do_create(params, fake) end) do
254 result
255 end
256 end
257
258 defp do_create(%{to: to, actor: actor, context: context, object: object} = params, fake) do
259 additional = params[:additional] || %{}
260 # only accept false as false value
261 local = !(params[:local] == false)
262 published = params[:published]
263 quick_insert? = Config.get([:env]) == :benchmark
264
265 with create_data <-
266 make_create_data(
267 %{to: to, actor: actor, published: published, context: context, object: object},
268 additional
269 ),
270 {:ok, activity} <- insert(create_data, local, fake),
271 {:fake, false, activity} <- {:fake, fake, activity},
272 _ <- increase_replies_count_if_reply(create_data),
273 _ <- increase_poll_votes_if_vote(create_data),
274 {:quick_insert, false, activity} <- {:quick_insert, quick_insert?, activity},
275 {:ok, _actor} <- increase_note_count_if_public(actor, activity),
276 :ok <- maybe_federate(activity) do
277 {:ok, activity}
278 else
279 {:quick_insert, true, activity} ->
280 {:ok, activity}
281
282 {:fake, true, activity} ->
283 {:ok, activity}
284
285 {:error, message} ->
286 Repo.rollback(message)
287 end
288 end
289
290 @spec listen(map()) :: {:ok, Activity.t()} | {:error, any()}
291 def listen(%{to: to, actor: actor, context: context, object: object} = params) do
292 additional = params[:additional] || %{}
293 # only accept false as false value
294 local = !(params[:local] == false)
295 published = params[:published]
296
297 with listen_data <-
298 make_listen_data(
299 %{to: to, actor: actor, published: published, context: context, object: object},
300 additional
301 ),
302 {:ok, activity} <- insert(listen_data, local),
303 :ok <- maybe_federate(activity) do
304 {:ok, activity}
305 end
306 end
307
308 @spec accept(map()) :: {:ok, Activity.t()} | {:error, any()}
309 def accept(params) do
310 accept_or_reject("Accept", params)
311 end
312
313 @spec reject(map()) :: {:ok, Activity.t()} | {:error, any()}
314 def reject(params) do
315 accept_or_reject("Reject", params)
316 end
317
318 @spec accept_or_reject(String.t(), map()) :: {:ok, Activity.t()} | {:error, any()}
319 def accept_or_reject(type, %{to: to, actor: actor, object: object} = params) do
320 local = Map.get(params, :local, true)
321 activity_id = Map.get(params, :activity_id, nil)
322
323 with data <-
324 %{"to" => to, "type" => type, "actor" => actor.ap_id, "object" => object}
325 |> Utils.maybe_put("id", activity_id),
326 {:ok, activity} <- insert(data, local),
327 :ok <- maybe_federate(activity) do
328 {:ok, activity}
329 end
330 end
331
332 @spec update(map()) :: {:ok, Activity.t()} | {:error, any()}
333 def update(%{to: to, cc: cc, actor: actor, object: object} = params) do
334 local = !(params[:local] == false)
335 activity_id = params[:activity_id]
336
337 with data <- %{
338 "to" => to,
339 "cc" => cc,
340 "type" => "Update",
341 "actor" => actor,
342 "object" => object
343 },
344 data <- Utils.maybe_put(data, "id", activity_id),
345 {:ok, activity} <- insert(data, local),
346 :ok <- maybe_federate(activity) do
347 {:ok, activity}
348 end
349 end
350
351 @spec react_with_emoji(User.t(), Object.t(), String.t(), keyword()) ::
352 {:ok, Activity.t(), Object.t()} | {:error, any()}
353 def react_with_emoji(user, object, emoji, options \\ []) do
354 with {:ok, result} <-
355 Repo.transaction(fn -> do_react_with_emoji(user, object, emoji, options) end) do
356 result
357 end
358 end
359
360 defp do_react_with_emoji(user, object, emoji, options) do
361 with local <- Keyword.get(options, :local, true),
362 activity_id <- Keyword.get(options, :activity_id, nil),
363 true <- Pleroma.Emoji.is_unicode_emoji?(emoji),
364 reaction_data <- make_emoji_reaction_data(user, object, emoji, activity_id),
365 {:ok, activity} <- insert(reaction_data, local),
366 {:ok, object} <- add_emoji_reaction_to_object(activity, object),
367 :ok <- maybe_federate(activity) do
368 {:ok, activity, object}
369 else
370 false -> {:error, false}
371 {:error, error} -> Repo.rollback(error)
372 end
373 end
374
375 @spec unreact_with_emoji(User.t(), String.t(), keyword()) ::
376 {:ok, Activity.t(), Object.t()} | {:error, any()}
377 def unreact_with_emoji(user, reaction_id, options \\ []) do
378 with {:ok, result} <-
379 Repo.transaction(fn -> do_unreact_with_emoji(user, reaction_id, options) end) do
380 result
381 end
382 end
383
384 defp do_unreact_with_emoji(user, reaction_id, options) do
385 with local <- Keyword.get(options, :local, true),
386 activity_id <- Keyword.get(options, :activity_id, nil),
387 user_ap_id <- user.ap_id,
388 %Activity{actor: ^user_ap_id} = reaction_activity <- Activity.get_by_ap_id(reaction_id),
389 object <- Object.normalize(reaction_activity),
390 unreact_data <- make_undo_data(user, reaction_activity, activity_id),
391 {:ok, activity} <- insert(unreact_data, local),
392 {:ok, object} <- remove_emoji_reaction_from_object(reaction_activity, object),
393 :ok <- maybe_federate(activity) do
394 {:ok, activity, object}
395 else
396 {:error, error} -> Repo.rollback(error)
397 end
398 end
399
400 # TODO: Is this even used now?
401 # TODO: This is weird, maybe we shouldn't check here if we can make the activity.
402 @spec like(User.t(), Object.t(), String.t() | nil, boolean()) ::
403 {:ok, Activity.t(), Object.t()} | {:error, any()}
404 def like(user, object, activity_id \\ nil, local \\ true) do
405 with {:ok, result} <- Repo.transaction(fn -> do_like(user, object, activity_id, local) end) do
406 result
407 end
408 end
409
410 defp do_like(
411 %User{ap_id: ap_id} = user,
412 %Object{data: %{"id" => _}} = object,
413 activity_id,
414 local
415 ) do
416 with nil <- get_existing_like(ap_id, object),
417 like_data <- make_like_data(user, object, activity_id),
418 {:ok, activity} <- insert(like_data, local),
419 {:ok, object} <- add_like_to_object(activity, object),
420 :ok <- maybe_federate(activity) do
421 {:ok, activity, object}
422 else
423 %Activity{} = activity ->
424 {:ok, activity, object}
425
426 {:error, error} ->
427 Repo.rollback(error)
428 end
429 end
430
431 @spec unlike(User.t(), Object.t(), String.t() | nil, boolean()) ::
432 {:ok, Activity.t(), Activity.t(), Object.t()} | {:ok, Object.t()} | {:error, any()}
433 def unlike(%User{} = actor, %Object{} = object, activity_id \\ nil, local \\ true) do
434 with {:ok, result} <-
435 Repo.transaction(fn -> do_unlike(actor, object, activity_id, local) end) do
436 result
437 end
438 end
439
440 defp do_unlike(actor, object, activity_id, local) do
441 with %Activity{} = like_activity <- get_existing_like(actor.ap_id, object),
442 unlike_data <- make_unlike_data(actor, like_activity, activity_id),
443 {:ok, unlike_activity} <- insert(unlike_data, local),
444 {:ok, _activity} <- Repo.delete(like_activity),
445 {:ok, object} <- remove_like_from_object(like_activity, object),
446 :ok <- maybe_federate(unlike_activity) do
447 {:ok, unlike_activity, like_activity, object}
448 else
449 nil -> {:ok, object}
450 {:error, error} -> Repo.rollback(error)
451 end
452 end
453
454 @spec announce(User.t(), Object.t(), String.t() | nil, boolean(), boolean()) ::
455 {:ok, Activity.t(), Object.t()} | {:error, any()}
456 def announce(
457 %User{ap_id: _} = user,
458 %Object{data: %{"id" => _}} = object,
459 activity_id \\ nil,
460 local \\ true,
461 public \\ true
462 ) do
463 with {:ok, result} <-
464 Repo.transaction(fn -> do_announce(user, object, activity_id, local, public) end) do
465 result
466 end
467 end
468
469 defp do_announce(user, object, activity_id, local, public) do
470 with true <- is_announceable?(object, user, public),
471 announce_data <- make_announce_data(user, object, activity_id, public),
472 {:ok, activity} <- insert(announce_data, local),
473 {:ok, object} <- add_announce_to_object(activity, object),
474 :ok <- maybe_federate(activity) do
475 {:ok, activity, object}
476 else
477 false -> {:error, false}
478 {:error, error} -> Repo.rollback(error)
479 end
480 end
481
482 @spec unannounce(User.t(), Object.t(), String.t() | nil, boolean()) ::
483 {:ok, Activity.t(), Object.t()} | {:ok, Object.t()} | {:error, any()}
484 def unannounce(
485 %User{} = actor,
486 %Object{} = object,
487 activity_id \\ nil,
488 local \\ true
489 ) do
490 with {:ok, result} <-
491 Repo.transaction(fn -> do_unannounce(actor, object, activity_id, local) end) do
492 result
493 end
494 end
495
496 defp do_unannounce(actor, object, activity_id, local) do
497 with %Activity{} = announce_activity <- get_existing_announce(actor.ap_id, object),
498 unannounce_data <- make_unannounce_data(actor, announce_activity, activity_id),
499 {:ok, unannounce_activity} <- insert(unannounce_data, local),
500 :ok <- maybe_federate(unannounce_activity),
501 {:ok, _activity} <- Repo.delete(announce_activity),
502 {:ok, object} <- remove_announce_from_object(announce_activity, object) do
503 {:ok, unannounce_activity, object}
504 else
505 nil -> {:ok, object}
506 {:error, error} -> Repo.rollback(error)
507 end
508 end
509
510 @spec follow(User.t(), User.t(), String.t() | nil, boolean()) ::
511 {:ok, Activity.t()} | {:error, any()}
512 def follow(follower, followed, activity_id \\ nil, local \\ true) do
513 with {:ok, result} <-
514 Repo.transaction(fn -> do_follow(follower, followed, activity_id, local) end) do
515 result
516 end
517 end
518
519 defp do_follow(follower, followed, activity_id, local) do
520 with data <- make_follow_data(follower, followed, activity_id),
521 {:ok, activity} <- insert(data, local),
522 :ok <- maybe_federate(activity) do
523 {:ok, activity}
524 else
525 {:error, error} -> Repo.rollback(error)
526 end
527 end
528
529 @spec unfollow(User.t(), User.t(), String.t() | nil, boolean()) ::
530 {:ok, Activity.t()} | nil | {:error, any()}
531 def unfollow(follower, followed, activity_id \\ nil, local \\ true) do
532 with {:ok, result} <-
533 Repo.transaction(fn -> do_unfollow(follower, followed, activity_id, local) end) do
534 result
535 end
536 end
537
538 defp do_unfollow(follower, followed, activity_id, local) do
539 with %Activity{} = follow_activity <- fetch_latest_follow(follower, followed),
540 {:ok, follow_activity} <- update_follow_state(follow_activity, "cancelled"),
541 unfollow_data <- make_unfollow_data(follower, followed, follow_activity, activity_id),
542 {:ok, activity} <- insert(unfollow_data, local),
543 :ok <- maybe_federate(activity) do
544 {:ok, activity}
545 else
546 nil -> nil
547 {:error, error} -> Repo.rollback(error)
548 end
549 end
550
551 @spec delete(User.t() | Object.t(), keyword()) :: {:ok, User.t() | Object.t()} | {:error, any()}
552 def delete(entity, options \\ []) do
553 with {:ok, result} <- Repo.transaction(fn -> do_delete(entity, options) end) do
554 result
555 end
556 end
557
558 defp do_delete(%User{ap_id: ap_id, follower_address: follower_address} = user, _) do
559 with data <- %{
560 "to" => [follower_address],
561 "type" => "Delete",
562 "actor" => ap_id,
563 "object" => %{"type" => "Person", "id" => ap_id}
564 },
565 {:ok, activity} <- insert(data, true, true, true),
566 :ok <- maybe_federate(activity) do
567 {:ok, user}
568 end
569 end
570
571 defp do_delete(%Object{data: %{"id" => id, "actor" => actor}} = object, options) do
572 local = Keyword.get(options, :local, true)
573 activity_id = Keyword.get(options, :activity_id, nil)
574 actor = Keyword.get(options, :actor, actor)
575
576 user = User.get_cached_by_ap_id(actor)
577 to = (object.data["to"] || []) ++ (object.data["cc"] || [])
578
579 with create_activity <- Activity.get_create_by_object_ap_id(id),
580 data <-
581 %{
582 "type" => "Delete",
583 "actor" => actor,
584 "object" => id,
585 "to" => to,
586 "deleted_activity_id" => create_activity && create_activity.id
587 }
588 |> maybe_put("id", activity_id),
589 {:ok, activity} <- insert(data, local, false),
590 {:ok, object, _create_activity} <- Object.delete(object),
591 stream_out_participations(object, user),
592 _ <- decrease_replies_count_if_reply(object),
593 {:ok, _actor} <- decrease_note_count_if_public(user, object),
594 :ok <- maybe_federate(activity) do
595 {:ok, activity}
596 else
597 {:error, error} ->
598 Repo.rollback(error)
599 end
600 end
601
602 defp do_delete(%Object{data: %{"type" => "Tombstone", "id" => ap_id}}, _) do
603 activity =
604 ap_id
605 |> Activity.Queries.by_object_id()
606 |> Activity.Queries.by_type("Delete")
607 |> Repo.one()
608
609 {:ok, activity}
610 end
611
612 @spec block(User.t(), User.t(), String.t() | nil, boolean()) ::
613 {:ok, Activity.t()} | {:error, any()}
614 def block(blocker, blocked, activity_id \\ nil, local \\ true) do
615 with {:ok, result} <-
616 Repo.transaction(fn -> do_block(blocker, blocked, activity_id, local) end) do
617 result
618 end
619 end
620
621 defp do_block(blocker, blocked, activity_id, local) do
622 outgoing_blocks = Config.get([:activitypub, :outgoing_blocks])
623 unfollow_blocked = Config.get([:activitypub, :unfollow_blocked])
624
625 if unfollow_blocked do
626 follow_activity = fetch_latest_follow(blocker, blocked)
627 if follow_activity, do: unfollow(blocker, blocked, nil, local)
628 end
629
630 with true <- outgoing_blocks,
631 block_data <- make_block_data(blocker, blocked, activity_id),
632 {:ok, activity} <- insert(block_data, local),
633 :ok <- maybe_federate(activity) do
634 {:ok, activity}
635 else
636 {:error, error} -> Repo.rollback(error)
637 end
638 end
639
640 @spec unblock(User.t(), User.t(), String.t() | nil, boolean()) ::
641 {:ok, Activity.t()} | {:error, any()} | nil
642 def unblock(blocker, blocked, activity_id \\ nil, local \\ true) do
643 with {:ok, result} <-
644 Repo.transaction(fn -> do_unblock(blocker, blocked, activity_id, local) end) do
645 result
646 end
647 end
648
649 defp do_unblock(blocker, blocked, activity_id, local) do
650 with %Activity{} = block_activity <- fetch_latest_block(blocker, blocked),
651 unblock_data <- make_unblock_data(blocker, blocked, block_activity, activity_id),
652 {:ok, activity} <- insert(unblock_data, local),
653 :ok <- maybe_federate(activity) do
654 {:ok, activity}
655 else
656 nil -> nil
657 {:error, error} -> Repo.rollback(error)
658 end
659 end
660
661 @spec flag(map()) :: {:ok, Activity.t()} | {:error, any()}
662 def flag(
663 %{
664 actor: actor,
665 context: _context,
666 account: account,
667 statuses: statuses,
668 content: content
669 } = params
670 ) do
671 # only accept false as false value
672 local = !(params[:local] == false)
673 forward = !(params[:forward] == false)
674
675 additional = params[:additional] || %{}
676
677 additional =
678 if forward do
679 Map.merge(additional, %{"to" => [], "cc" => [account.ap_id]})
680 else
681 Map.merge(additional, %{"to" => [], "cc" => []})
682 end
683
684 with flag_data <- make_flag_data(params, additional),
685 {:ok, activity} <- insert(flag_data, local),
686 {:ok, stripped_activity} <- strip_report_status_data(activity),
687 :ok <- maybe_federate(stripped_activity) do
688 User.all_superusers()
689 |> Enum.filter(fn user -> not is_nil(user.email) end)
690 |> Enum.each(fn superuser ->
691 superuser
692 |> Pleroma.Emails.AdminEmail.report(actor, account, statuses, content)
693 |> Pleroma.Emails.Mailer.deliver_async()
694 end)
695
696 {:ok, activity}
697 end
698 end
699
700 @spec move(User.t(), User.t(), boolean()) :: {:ok, Activity.t()} | {:error, any()}
701 def move(%User{} = origin, %User{} = target, local \\ true) do
702 params = %{
703 "type" => "Move",
704 "actor" => origin.ap_id,
705 "object" => origin.ap_id,
706 "target" => target.ap_id
707 }
708
709 with true <- origin.ap_id in target.also_known_as,
710 {:ok, activity} <- insert(params, local) do
711 maybe_federate(activity)
712
713 BackgroundWorker.enqueue("move_following", %{
714 "origin_id" => origin.id,
715 "target_id" => target.id
716 })
717
718 {:ok, activity}
719 else
720 false -> {:error, "Target account must have the origin in `alsoKnownAs`"}
721 err -> err
722 end
723 end
724
725 def fetch_activities_for_context_query(context, opts) do
726 public = [Constants.as_public()]
727
728 recipients =
729 if opts["user"],
730 do: [opts["user"].ap_id | User.following(opts["user"])] ++ public,
731 else: public
732
733 from(activity in Activity)
734 |> maybe_preload_objects(opts)
735 |> maybe_preload_bookmarks(opts)
736 |> maybe_set_thread_muted_field(opts)
737 |> restrict_blocked(opts)
738 |> restrict_recipients(recipients, opts["user"])
739 |> where(
740 [activity],
741 fragment(
742 "?->>'type' = ? and ?->>'context' = ?",
743 activity.data,
744 "Create",
745 activity.data,
746 ^context
747 )
748 )
749 |> exclude_poll_votes(opts)
750 |> exclude_id(opts)
751 |> order_by([activity], desc: activity.id)
752 end
753
754 @spec fetch_activities_for_context(String.t(), keyword() | map()) :: [Activity.t()]
755 def fetch_activities_for_context(context, opts \\ %{}) do
756 context
757 |> fetch_activities_for_context_query(opts)
758 |> Repo.all()
759 end
760
761 @spec fetch_latest_activity_id_for_context(String.t(), keyword() | map()) ::
762 FlakeId.Ecto.CompatType.t() | nil
763 def fetch_latest_activity_id_for_context(context, opts \\ %{}) do
764 context
765 |> fetch_activities_for_context_query(Map.merge(%{"skip_preload" => true}, opts))
766 |> limit(1)
767 |> select([a], a.id)
768 |> Repo.one()
769 end
770
771 @spec fetch_public_activities(map(), Pagination.type()) :: [Activity.t()]
772 def fetch_public_activities(opts \\ %{}, pagination \\ :keyset) do
773 opts = Map.drop(opts, ["user"])
774
775 [Constants.as_public()]
776 |> fetch_activities_query(opts)
777 |> restrict_unlisted()
778 |> Pagination.fetch_paginated(opts, pagination)
779 end
780
781 @valid_visibilities ~w[direct unlisted public private]
782
783 defp restrict_visibility(query, %{visibility: visibility})
784 when is_list(visibility) do
785 if Enum.all?(visibility, &(&1 in @valid_visibilities)) do
786 query =
787 from(
788 a in query,
789 where:
790 fragment(
791 "activity_visibility(?, ?, ?) = ANY (?)",
792 a.actor,
793 a.recipients,
794 a.data,
795 ^visibility
796 )
797 )
798
799 query
800 else
801 Logger.error("Could not restrict visibility to #{visibility}")
802 end
803 end
804
805 defp restrict_visibility(query, %{visibility: visibility})
806 when visibility in @valid_visibilities do
807 from(
808 a in query,
809 where:
810 fragment("activity_visibility(?, ?, ?) = ?", a.actor, a.recipients, a.data, ^visibility)
811 )
812 end
813
814 defp restrict_visibility(_query, %{visibility: visibility})
815 when visibility not in @valid_visibilities do
816 Logger.error("Could not restrict visibility to #{visibility}")
817 end
818
819 defp restrict_visibility(query, _visibility), do: query
820
821 defp exclude_visibility(query, %{"exclude_visibilities" => visibility})
822 when is_list(visibility) do
823 if Enum.all?(visibility, &(&1 in @valid_visibilities)) do
824 from(
825 a in query,
826 where:
827 not fragment(
828 "activity_visibility(?, ?, ?) = ANY (?)",
829 a.actor,
830 a.recipients,
831 a.data,
832 ^visibility
833 )
834 )
835 else
836 Logger.error("Could not exclude visibility to #{visibility}")
837 query
838 end
839 end
840
841 defp exclude_visibility(query, %{"exclude_visibilities" => visibility})
842 when visibility in @valid_visibilities do
843 from(
844 a in query,
845 where:
846 not fragment(
847 "activity_visibility(?, ?, ?) = ?",
848 a.actor,
849 a.recipients,
850 a.data,
851 ^visibility
852 )
853 )
854 end
855
856 defp exclude_visibility(query, %{"exclude_visibilities" => visibility})
857 when visibility not in @valid_visibilities do
858 Logger.error("Could not exclude visibility to #{visibility}")
859 query
860 end
861
862 defp exclude_visibility(query, _visibility), do: query
863
864 defp restrict_thread_visibility(query, _, %{skip_thread_containment: true} = _),
865 do: query
866
867 defp restrict_thread_visibility(
868 query,
869 %{"user" => %User{skip_thread_containment: true}},
870 _
871 ),
872 do: query
873
874 defp restrict_thread_visibility(query, %{"user" => %User{ap_id: ap_id}}, _) do
875 from(
876 a in query,
877 where: fragment("thread_visibility(?, (?)->>'id') = true", ^ap_id, a.data)
878 )
879 end
880
881 defp restrict_thread_visibility(query, _, _), do: query
882
883 def fetch_user_abstract_activities(user, reading_user, params \\ %{}) do
884 params =
885 params
886 |> Map.put("user", reading_user)
887 |> Map.put("actor_id", user.ap_id)
888
889 recipients =
890 user_activities_recipients(%{
891 "godmode" => params["godmode"],
892 "reading_user" => reading_user
893 })
894
895 fetch_activities(recipients, params)
896 |> Enum.reverse()
897 end
898
899 def fetch_user_activities(user, reading_user, params \\ %{}) do
900 params =
901 params
902 |> Map.put("type", ["Create", "Announce"])
903 |> Map.put("user", reading_user)
904 |> Map.put("actor_id", user.ap_id)
905 |> Map.put("pinned_activity_ids", user.pinned_activities)
906
907 params =
908 if User.blocks?(reading_user, user) do
909 params
910 else
911 params
912 |> Map.put("blocking_user", reading_user)
913 |> Map.put("muting_user", reading_user)
914 end
915
916 recipients =
917 user_activities_recipients(%{
918 "godmode" => params["godmode"],
919 "reading_user" => reading_user
920 })
921
922 fetch_activities(recipients, params)
923 |> Enum.reverse()
924 end
925
926 def fetch_statuses(reading_user, params) do
927 params =
928 params
929 |> Map.put("type", ["Create", "Announce"])
930
931 recipients =
932 user_activities_recipients(%{
933 "godmode" => params["godmode"],
934 "reading_user" => reading_user
935 })
936
937 fetch_activities(recipients, params, :offset)
938 |> Enum.reverse()
939 end
940
941 defp user_activities_recipients(%{"godmode" => true}) do
942 []
943 end
944
945 defp user_activities_recipients(%{"reading_user" => reading_user}) do
946 if reading_user do
947 [Constants.as_public()] ++ [reading_user.ap_id | User.following(reading_user)]
948 else
949 [Constants.as_public()]
950 end
951 end
952
953 defp restrict_since(query, %{"since_id" => ""}), do: query
954
955 defp restrict_since(query, %{"since_id" => since_id}) do
956 from(activity in query, where: activity.id > ^since_id)
957 end
958
959 defp restrict_since(query, _), do: query
960
961 defp restrict_tag_reject(_query, %{"tag_reject" => _tag_reject, "skip_preload" => true}) do
962 raise "Can't use the child object without preloading!"
963 end
964
965 defp restrict_tag_reject(query, %{"tag_reject" => tag_reject})
966 when is_list(tag_reject) and tag_reject != [] do
967 from(
968 [_activity, object] in query,
969 where: fragment("not (?)->'tag' \\?| (?)", object.data, ^tag_reject)
970 )
971 end
972
973 defp restrict_tag_reject(query, _), do: query
974
975 defp restrict_tag_all(_query, %{"tag_all" => _tag_all, "skip_preload" => true}) do
976 raise "Can't use the child object without preloading!"
977 end
978
979 defp restrict_tag_all(query, %{"tag_all" => tag_all})
980 when is_list(tag_all) and tag_all != [] do
981 from(
982 [_activity, object] in query,
983 where: fragment("(?)->'tag' \\?& (?)", object.data, ^tag_all)
984 )
985 end
986
987 defp restrict_tag_all(query, _), do: query
988
989 defp restrict_tag(_query, %{"tag" => _tag, "skip_preload" => true}) do
990 raise "Can't use the child object without preloading!"
991 end
992
993 defp restrict_tag(query, %{"tag" => tag}) when is_list(tag) do
994 from(
995 [_activity, object] in query,
996 where: fragment("(?)->'tag' \\?| (?)", object.data, ^tag)
997 )
998 end
999
1000 defp restrict_tag(query, %{"tag" => tag}) when is_binary(tag) do
1001 from(
1002 [_activity, object] in query,
1003 where: fragment("(?)->'tag' \\? (?)", object.data, ^tag)
1004 )
1005 end
1006
1007 defp restrict_tag(query, _), do: query
1008
1009 defp restrict_recipients(query, [], _user), do: query
1010
1011 defp restrict_recipients(query, recipients, nil) do
1012 from(activity in query, where: fragment("? && ?", ^recipients, activity.recipients))
1013 end
1014
1015 defp restrict_recipients(query, recipients, user) do
1016 from(
1017 activity in query,
1018 where: fragment("? && ?", ^recipients, activity.recipients),
1019 or_where: activity.actor == ^user.ap_id
1020 )
1021 end
1022
1023 defp restrict_local(query, %{"local_only" => true}) do
1024 from(activity in query, where: activity.local == true)
1025 end
1026
1027 defp restrict_local(query, _), do: query
1028
1029 defp restrict_actor(query, %{"actor_id" => actor_id}) do
1030 from(activity in query, where: activity.actor == ^actor_id)
1031 end
1032
1033 defp restrict_actor(query, _), do: query
1034
1035 defp restrict_type(query, %{"type" => type}) when is_binary(type) do
1036 from(activity in query, where: fragment("?->>'type' = ?", activity.data, ^type))
1037 end
1038
1039 defp restrict_type(query, %{"type" => type}) do
1040 from(activity in query, where: fragment("?->>'type' = ANY(?)", activity.data, ^type))
1041 end
1042
1043 defp restrict_type(query, _), do: query
1044
1045 defp restrict_state(query, %{"state" => state}) do
1046 from(activity in query, where: fragment("?->>'state' = ?", activity.data, ^state))
1047 end
1048
1049 defp restrict_state(query, _), do: query
1050
1051 defp restrict_favorited_by(query, %{"favorited_by" => ap_id}) do
1052 from(
1053 [_activity, object] in query,
1054 where: fragment("(?)->'likes' \\? (?)", object.data, ^ap_id)
1055 )
1056 end
1057
1058 defp restrict_favorited_by(query, _), do: query
1059
1060 defp restrict_media(_query, %{"only_media" => _val, "skip_preload" => true}) do
1061 raise "Can't use the child object without preloading!"
1062 end
1063
1064 defp restrict_media(query, %{"only_media" => val}) when val == "true" or val == "1" do
1065 from(
1066 [_activity, object] in query,
1067 where: fragment("not (?)->'attachment' = (?)", object.data, ^[])
1068 )
1069 end
1070
1071 defp restrict_media(query, _), do: query
1072
1073 defp restrict_replies(query, %{"exclude_replies" => val}) when val == "true" or val == "1" do
1074 from(
1075 [_activity, object] in query,
1076 where: fragment("?->>'inReplyTo' is null", object.data)
1077 )
1078 end
1079
1080 defp restrict_replies(query, _), do: query
1081
1082 defp restrict_reblogs(query, %{"exclude_reblogs" => val}) when val == "true" or val == "1" do
1083 from(activity in query, where: fragment("?->>'type' != 'Announce'", activity.data))
1084 end
1085
1086 defp restrict_reblogs(query, _), do: query
1087
1088 defp restrict_muted(query, %{"with_muted" => val}) when val in [true, "true", "1"], do: query
1089
1090 defp restrict_muted(query, %{"muting_user" => %User{} = user} = opts) do
1091 mutes = opts["muted_users_ap_ids"] || User.muted_users_ap_ids(user)
1092
1093 query =
1094 from([activity] in query,
1095 where: fragment("not (? = ANY(?))", activity.actor, ^mutes),
1096 where: fragment("not (?->'to' \\?| ?)", activity.data, ^mutes)
1097 )
1098
1099 unless opts["skip_preload"] do
1100 from([thread_mute: tm] in query, where: is_nil(tm.user_id))
1101 else
1102 query
1103 end
1104 end
1105
1106 defp restrict_muted(query, _), do: query
1107
1108 defp restrict_blocked(query, %{"blocking_user" => %User{} = user} = opts) do
1109 blocked_ap_ids = opts["blocked_users_ap_ids"] || User.blocked_users_ap_ids(user)
1110 domain_blocks = user.domain_blocks || []
1111
1112 following_ap_ids = User.get_friends_ap_ids(user)
1113
1114 query =
1115 if has_named_binding?(query, :object), do: query, else: Activity.with_joined_object(query)
1116
1117 from(
1118 [activity, object: o] in query,
1119 where: fragment("not (? = ANY(?))", activity.actor, ^blocked_ap_ids),
1120 where: fragment("not (? && ?)", activity.recipients, ^blocked_ap_ids),
1121 where:
1122 fragment(
1123 "not (?->>'type' = 'Announce' and ?->'to' \\?| ?)",
1124 activity.data,
1125 activity.data,
1126 ^blocked_ap_ids
1127 ),
1128 where:
1129 fragment(
1130 "(not (split_part(?, '/', 3) = ANY(?))) or ? = ANY(?)",
1131 activity.actor,
1132 ^domain_blocks,
1133 activity.actor,
1134 ^following_ap_ids
1135 ),
1136 where:
1137 fragment(
1138 "(not (split_part(?->>'actor', '/', 3) = ANY(?))) or (?->>'actor') = ANY(?)",
1139 o.data,
1140 ^domain_blocks,
1141 o.data,
1142 ^following_ap_ids
1143 )
1144 )
1145 end
1146
1147 defp restrict_blocked(query, _), do: query
1148
1149 defp restrict_unlisted(query) do
1150 from(
1151 activity in query,
1152 where:
1153 fragment(
1154 "not (coalesce(?->'cc', '{}'::jsonb) \\?| ?)",
1155 activity.data,
1156 ^[Constants.as_public()]
1157 )
1158 )
1159 end
1160
1161 defp restrict_pinned(query, %{"pinned" => "true", "pinned_activity_ids" => ids}) do
1162 from(activity in query, where: activity.id in ^ids)
1163 end
1164
1165 defp restrict_pinned(query, _), do: query
1166
1167 defp restrict_muted_reblogs(query, %{"muting_user" => %User{} = user} = opts) do
1168 muted_reblogs = opts["reblog_muted_users_ap_ids"] || User.reblog_muted_users_ap_ids(user)
1169
1170 from(
1171 activity in query,
1172 where:
1173 fragment(
1174 "not ( ?->>'type' = 'Announce' and ? = ANY(?))",
1175 activity.data,
1176 activity.actor,
1177 ^muted_reblogs
1178 )
1179 )
1180 end
1181
1182 defp restrict_muted_reblogs(query, _), do: query
1183
1184 defp restrict_instance(query, %{"instance" => instance}) do
1185 users =
1186 from(
1187 u in User,
1188 select: u.ap_id,
1189 where: fragment("? LIKE ?", u.nickname, ^"%@#{instance}")
1190 )
1191 |> Repo.all()
1192
1193 from(activity in query, where: activity.actor in ^users)
1194 end
1195
1196 defp restrict_instance(query, _), do: query
1197
1198 defp exclude_poll_votes(query, %{"include_poll_votes" => true}), do: query
1199
1200 defp exclude_poll_votes(query, _) do
1201 if has_named_binding?(query, :object) do
1202 from([activity, object: o] in query,
1203 where: fragment("not(?->>'type' = ?)", o.data, "Answer")
1204 )
1205 else
1206 query
1207 end
1208 end
1209
1210 defp exclude_chat_messages(query, %{"include_chat_messages" => true}), do: query
1211
1212 defp exclude_chat_messages(query, _) do
1213 if has_named_binding?(query, :object) do
1214 from([activity, object: o] in query,
1215 where: fragment("not(?->>'type' = ?)", o.data, "ChatMessage")
1216 )
1217 else
1218 query
1219 end
1220 end
1221
1222 defp exclude_id(query, %{"exclude_id" => id}) when is_binary(id) do
1223 from(activity in query, where: activity.id != ^id)
1224 end
1225
1226 defp exclude_id(query, _), do: query
1227
1228 defp maybe_preload_objects(query, %{"skip_preload" => true}), do: query
1229
1230 defp maybe_preload_objects(query, _) do
1231 query
1232 |> Activity.with_preloaded_object()
1233 end
1234
1235 defp maybe_preload_bookmarks(query, %{"skip_preload" => true}), do: query
1236
1237 defp maybe_preload_bookmarks(query, opts) do
1238 query
1239 |> Activity.with_preloaded_bookmark(opts["user"])
1240 end
1241
1242 defp maybe_preload_report_notes(query, %{"preload_report_notes" => true}) do
1243 query
1244 |> Activity.with_preloaded_report_notes()
1245 end
1246
1247 defp maybe_preload_report_notes(query, _), do: query
1248
1249 defp maybe_set_thread_muted_field(query, %{"skip_preload" => true}), do: query
1250
1251 defp maybe_set_thread_muted_field(query, opts) do
1252 query
1253 |> Activity.with_set_thread_muted_field(opts["muting_user"] || opts["user"])
1254 end
1255
1256 defp maybe_order(query, %{order: :desc}) do
1257 query
1258 |> order_by(desc: :id)
1259 end
1260
1261 defp maybe_order(query, %{order: :asc}) do
1262 query
1263 |> order_by(asc: :id)
1264 end
1265
1266 defp maybe_order(query, _), do: query
1267
1268 defp fetch_activities_query_ap_ids_ops(opts) do
1269 source_user = opts["muting_user"]
1270 ap_id_relationships = if source_user, do: [:mute, :reblog_mute], else: []
1271
1272 ap_id_relationships =
1273 ap_id_relationships ++
1274 if opts["blocking_user"] && opts["blocking_user"] == source_user do
1275 [:block]
1276 else
1277 []
1278 end
1279
1280 preloaded_ap_ids = User.outgoing_relationships_ap_ids(source_user, ap_id_relationships)
1281
1282 restrict_blocked_opts = Map.merge(%{"blocked_users_ap_ids" => preloaded_ap_ids[:block]}, opts)
1283 restrict_muted_opts = Map.merge(%{"muted_users_ap_ids" => preloaded_ap_ids[:mute]}, opts)
1284
1285 restrict_muted_reblogs_opts =
1286 Map.merge(%{"reblog_muted_users_ap_ids" => preloaded_ap_ids[:reblog_mute]}, opts)
1287
1288 {restrict_blocked_opts, restrict_muted_opts, restrict_muted_reblogs_opts}
1289 end
1290
1291 def fetch_activities_query(recipients, opts \\ %{}) do
1292 {restrict_blocked_opts, restrict_muted_opts, restrict_muted_reblogs_opts} =
1293 fetch_activities_query_ap_ids_ops(opts)
1294
1295 config = %{
1296 skip_thread_containment: Config.get([:instance, :skip_thread_containment])
1297 }
1298
1299 Activity
1300 |> maybe_preload_objects(opts)
1301 |> maybe_preload_bookmarks(opts)
1302 |> maybe_preload_report_notes(opts)
1303 |> maybe_set_thread_muted_field(opts)
1304 |> maybe_order(opts)
1305 |> restrict_recipients(recipients, opts["user"])
1306 |> restrict_tag(opts)
1307 |> restrict_tag_reject(opts)
1308 |> restrict_tag_all(opts)
1309 |> restrict_since(opts)
1310 |> restrict_local(opts)
1311 |> restrict_actor(opts)
1312 |> restrict_type(opts)
1313 |> restrict_state(opts)
1314 |> restrict_favorited_by(opts)
1315 |> restrict_blocked(restrict_blocked_opts)
1316 |> restrict_muted(restrict_muted_opts)
1317 |> restrict_media(opts)
1318 |> restrict_visibility(opts)
1319 |> restrict_thread_visibility(opts, config)
1320 |> restrict_replies(opts)
1321 |> restrict_reblogs(opts)
1322 |> restrict_pinned(opts)
1323 |> restrict_muted_reblogs(restrict_muted_reblogs_opts)
1324 |> restrict_instance(opts)
1325 |> Activity.restrict_deactivated_users()
1326 |> exclude_poll_votes(opts)
1327 |> exclude_chat_messages(opts)
1328 |> exclude_visibility(opts)
1329 end
1330
1331 def fetch_activities(recipients, opts \\ %{}, pagination \\ :keyset) do
1332 list_memberships = Pleroma.List.memberships(opts["user"])
1333
1334 fetch_activities_query(recipients ++ list_memberships, opts)
1335 |> Pagination.fetch_paginated(opts, pagination)
1336 |> Enum.reverse()
1337 |> maybe_update_cc(list_memberships, opts["user"])
1338 end
1339
1340 @doc """
1341 Fetch favorites activities of user with order by sort adds to favorites
1342 """
1343 @spec fetch_favourites(User.t(), map(), Pagination.type()) :: list(Activity.t())
1344 def fetch_favourites(user, params \\ %{}, pagination \\ :keyset) do
1345 user.ap_id
1346 |> Activity.Queries.by_actor()
1347 |> Activity.Queries.by_type("Like")
1348 |> Activity.with_joined_object()
1349 |> Object.with_joined_activity()
1350 |> select([_like, object, activity], %{activity | object: object})
1351 |> order_by([like, _, _], desc: like.id)
1352 |> Pagination.fetch_paginated(
1353 Map.merge(params, %{"skip_order" => true}),
1354 pagination,
1355 :object_activity
1356 )
1357 end
1358
1359 defp maybe_update_cc(activities, list_memberships, %User{ap_id: user_ap_id})
1360 when is_list(list_memberships) and length(list_memberships) > 0 do
1361 Enum.map(activities, fn
1362 %{data: %{"bcc" => bcc}} = activity when is_list(bcc) and length(bcc) > 0 ->
1363 if Enum.any?(bcc, &(&1 in list_memberships)) do
1364 update_in(activity.data["cc"], &[user_ap_id | &1])
1365 else
1366 activity
1367 end
1368
1369 activity ->
1370 activity
1371 end)
1372 end
1373
1374 defp maybe_update_cc(activities, _, _), do: activities
1375
1376 def fetch_activities_bounded_query(query, recipients, recipients_with_public) do
1377 from(activity in query,
1378 where:
1379 fragment("? && ?", activity.recipients, ^recipients) or
1380 (fragment("? && ?", activity.recipients, ^recipients_with_public) and
1381 ^Constants.as_public() in activity.recipients)
1382 )
1383 end
1384
1385 def fetch_activities_bounded(
1386 recipients,
1387 recipients_with_public,
1388 opts \\ %{},
1389 pagination \\ :keyset
1390 ) do
1391 fetch_activities_query([], opts)
1392 |> fetch_activities_bounded_query(recipients, recipients_with_public)
1393 |> Pagination.fetch_paginated(opts, pagination)
1394 |> Enum.reverse()
1395 end
1396
1397 @spec upload(Upload.source(), keyword()) :: {:ok, Object.t()} | {:error, any()}
1398 def upload(file, opts \\ []) do
1399 with {:ok, data} <- Upload.store(file, opts) do
1400 obj_data =
1401 if opts[:actor] do
1402 Map.put(data, "actor", opts[:actor])
1403 else
1404 data
1405 end
1406
1407 Repo.insert(%Object{data: obj_data})
1408 end
1409 end
1410
1411 @spec get_actor_url(any()) :: binary() | nil
1412 defp get_actor_url(url) when is_binary(url), do: url
1413 defp get_actor_url(%{"href" => href}) when is_binary(href), do: href
1414
1415 defp get_actor_url(url) when is_list(url) do
1416 url
1417 |> List.first()
1418 |> get_actor_url()
1419 end
1420
1421 defp get_actor_url(_url), do: nil
1422
1423 defp object_to_user_data(data) do
1424 avatar =
1425 data["icon"]["url"] &&
1426 %{
1427 "type" => "Image",
1428 "url" => [%{"href" => data["icon"]["url"]}]
1429 }
1430
1431 banner =
1432 data["image"]["url"] &&
1433 %{
1434 "type" => "Image",
1435 "url" => [%{"href" => data["image"]["url"]}]
1436 }
1437
1438 fields =
1439 data
1440 |> Map.get("attachment", [])
1441 |> Enum.filter(fn %{"type" => t} -> t == "PropertyValue" end)
1442 |> Enum.map(fn fields -> Map.take(fields, ["name", "value"]) end)
1443
1444 locked = data["manuallyApprovesFollowers"] || false
1445 data = Transmogrifier.maybe_fix_user_object(data)
1446 discoverable = data["discoverable"] || false
1447 invisible = data["invisible"] || false
1448 actor_type = data["type"] || "Person"
1449
1450 user_data = %{
1451 ap_id: data["id"],
1452 uri: get_actor_url(data["url"]),
1453 ap_enabled: true,
1454 source_data: data,
1455 banner: banner,
1456 fields: fields,
1457 locked: locked,
1458 discoverable: discoverable,
1459 invisible: invisible,
1460 avatar: avatar,
1461 name: data["name"],
1462 follower_address: data["followers"],
1463 following_address: data["following"],
1464 bio: data["summary"],
1465 actor_type: actor_type,
1466 also_known_as: Map.get(data, "alsoKnownAs", [])
1467 }
1468
1469 # nickname can be nil because of virtual actors
1470 user_data =
1471 if data["preferredUsername"] do
1472 Map.put(
1473 user_data,
1474 :nickname,
1475 "#{data["preferredUsername"]}@#{URI.parse(data["id"]).host}"
1476 )
1477 else
1478 Map.put(user_data, :nickname, nil)
1479 end
1480
1481 {:ok, user_data}
1482 end
1483
1484 def fetch_follow_information_for_user(user) do
1485 with {:ok, following_data} <-
1486 Fetcher.fetch_and_contain_remote_object_from_id(user.following_address),
1487 {:ok, hide_follows} <- collection_private(following_data),
1488 {:ok, followers_data} <-
1489 Fetcher.fetch_and_contain_remote_object_from_id(user.follower_address),
1490 {:ok, hide_followers} <- collection_private(followers_data) do
1491 {:ok,
1492 %{
1493 hide_follows: hide_follows,
1494 follower_count: normalize_counter(followers_data["totalItems"]),
1495 following_count: normalize_counter(following_data["totalItems"]),
1496 hide_followers: hide_followers
1497 }}
1498 else
1499 {:error, _} = e -> e
1500 e -> {:error, e}
1501 end
1502 end
1503
1504 defp normalize_counter(counter) when is_integer(counter), do: counter
1505 defp normalize_counter(_), do: 0
1506
1507 defp maybe_update_follow_information(data) do
1508 with {:enabled, true} <- {:enabled, Config.get([:instance, :external_user_synchronization])},
1509 {:ok, info} <- fetch_follow_information_for_user(data) do
1510 info = Map.merge(data[:info] || %{}, info)
1511 Map.put(data, :info, info)
1512 else
1513 {:enabled, false} ->
1514 data
1515
1516 e ->
1517 Logger.error(
1518 "Follower/Following counter update for #{data.ap_id} failed.\n" <> inspect(e)
1519 )
1520
1521 data
1522 end
1523 end
1524
1525 defp collection_private(%{"first" => %{"type" => type}})
1526 when type in ["CollectionPage", "OrderedCollectionPage"],
1527 do: {:ok, false}
1528
1529 defp collection_private(%{"first" => first}) do
1530 with {:ok, %{"type" => type}} when type in ["CollectionPage", "OrderedCollectionPage"] <-
1531 Fetcher.fetch_and_contain_remote_object_from_id(first) do
1532 {:ok, false}
1533 else
1534 {:error, {:ok, %{status: code}}} when code in [401, 403] -> {:ok, true}
1535 {:error, _} = e -> e
1536 e -> {:error, e}
1537 end
1538 end
1539
1540 defp collection_private(_data), do: {:ok, true}
1541
1542 def user_data_from_user_object(data) do
1543 with {:ok, data} <- MRF.filter(data),
1544 {:ok, data} <- object_to_user_data(data) do
1545 {:ok, data}
1546 else
1547 e -> {:error, e}
1548 end
1549 end
1550
1551 def fetch_and_prepare_user_from_ap_id(ap_id) do
1552 with {:ok, data} <- Fetcher.fetch_and_contain_remote_object_from_id(ap_id),
1553 {:ok, data} <- user_data_from_user_object(data),
1554 data <- maybe_update_follow_information(data) do
1555 {:ok, data}
1556 else
1557 {:error, "Object has been deleted"} = e ->
1558 Logger.debug("Could not decode user at fetch #{ap_id}, #{inspect(e)}")
1559 {:error, e}
1560
1561 e ->
1562 Logger.error("Could not decode user at fetch #{ap_id}, #{inspect(e)}")
1563 {:error, e}
1564 end
1565 end
1566
1567 def make_user_from_ap_id(ap_id) do
1568 if _user = User.get_cached_by_ap_id(ap_id) do
1569 Transmogrifier.upgrade_user_from_ap_id(ap_id)
1570 else
1571 with {:ok, data} <- fetch_and_prepare_user_from_ap_id(ap_id) do
1572 User.insert_or_update_user(data)
1573 else
1574 e -> {:error, e}
1575 end
1576 end
1577 end
1578
1579 def make_user_from_nickname(nickname) do
1580 with {:ok, %{"ap_id" => ap_id}} when not is_nil(ap_id) <- WebFinger.finger(nickname) do
1581 make_user_from_ap_id(ap_id)
1582 else
1583 _e -> {:error, "No AP id in WebFinger"}
1584 end
1585 end
1586
1587 # filter out broken threads
1588 def contain_broken_threads(%Activity{} = activity, %User{} = user) do
1589 entire_thread_visible_for_user?(activity, user)
1590 end
1591
1592 # do post-processing on a specific activity
1593 def contain_activity(%Activity{} = activity, %User{} = user) do
1594 contain_broken_threads(activity, user)
1595 end
1596
1597 def fetch_direct_messages_query do
1598 Activity
1599 |> restrict_type(%{"type" => "Create"})
1600 |> restrict_visibility(%{visibility: "direct"})
1601 |> order_by([activity], asc: activity.id)
1602 end
1603 end