re f83bae7c: remove unnecessary filter
[akkoma] / lib / pleroma / web / activity_pub / transmogrifier.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.Transmogrifier do
6 @moduledoc """
7 A module to handle coding from internal to wire ActivityPub and back.
8 """
9 alias Pleroma.User
10 alias Pleroma.Object
11 alias Pleroma.Activity
12 alias Pleroma.Repo
13 alias Pleroma.Web.ActivityPub.ActivityPub
14 alias Pleroma.Web.ActivityPub.Utils
15
16 import Ecto.Query
17
18 require Logger
19
20 def get_actor(%{"actor" => actor}) when is_binary(actor) do
21 actor
22 end
23
24 def get_actor(%{"actor" => actor}) when is_list(actor) do
25 if is_binary(Enum.at(actor, 0)) do
26 Enum.at(actor, 0)
27 else
28 Enum.find(actor, fn %{"type" => type} -> type in ["Person", "Service", "Application"] end)
29 |> Map.get("id")
30 end
31 end
32
33 def get_actor(%{"actor" => %{"id" => id}}) when is_bitstring(id) do
34 id
35 end
36
37 def get_actor(%{"actor" => nil, "attributedTo" => actor}) when not is_nil(actor) do
38 get_actor(%{"actor" => actor})
39 end
40
41 @doc """
42 Checks that an imported AP object's actor matches the domain it came from.
43 """
44 def contain_origin(_id, %{"actor" => nil}), do: :error
45
46 def contain_origin(id, %{"actor" => _actor} = params) do
47 id_uri = URI.parse(id)
48 actor_uri = URI.parse(get_actor(params))
49
50 if id_uri.host == actor_uri.host do
51 :ok
52 else
53 :error
54 end
55 end
56
57 def contain_origin_from_id(_id, %{"id" => nil}), do: :error
58
59 def contain_origin_from_id(id, %{"id" => other_id} = _params) do
60 id_uri = URI.parse(id)
61 other_uri = URI.parse(other_id)
62
63 if id_uri.host == other_uri.host do
64 :ok
65 else
66 :error
67 end
68 end
69
70 @doc """
71 Modifies an incoming AP object (mastodon format) to our internal format.
72 """
73 def fix_object(object) do
74 object
75 |> fix_actor
76 |> fix_url
77 |> fix_attachments
78 |> fix_context
79 |> fix_in_reply_to
80 |> fix_emoji
81 |> fix_tag
82 |> fix_content_map
83 |> fix_likes
84 |> fix_addressing
85 end
86
87 def fix_addressing_list(map, field) do
88 if is_binary(map[field]) do
89 map
90 |> Map.put(field, [map[field]])
91 else
92 map
93 end
94 end
95
96 def fix_explicit_addressing(%{"to" => to, "cc" => cc} = object, explicit_mentions) do
97 explicit_to =
98 to
99 |> Enum.filter(fn x -> x in explicit_mentions end)
100
101 explicit_cc =
102 to
103 |> Enum.filter(fn x -> x not in explicit_mentions end)
104
105 final_cc =
106 (cc ++ explicit_cc)
107 |> Enum.uniq()
108
109 object
110 |> Map.put("to", explicit_to)
111 |> Map.put("cc", final_cc)
112 end
113
114 def fix_explicit_addressing(object, _explicit_mentions), do: object
115
116 # if directMessage flag is set to true, leave the addressing alone
117 def fix_explicit_addressing(%{"directMessage" => true} = object), do: object
118
119 def fix_explicit_addressing(object) do
120 explicit_mentions =
121 object
122 |> Utils.determine_explicit_mentions()
123
124 explicit_mentions = explicit_mentions ++ ["https://www.w3.org/ns/activitystreams#Public"]
125
126 object
127 |> fix_explicit_addressing(explicit_mentions)
128 end
129
130 def fix_addressing(object) do
131 object
132 |> fix_addressing_list("to")
133 |> fix_addressing_list("cc")
134 |> fix_addressing_list("bto")
135 |> fix_addressing_list("bcc")
136 |> fix_explicit_addressing
137 end
138
139 def fix_actor(%{"attributedTo" => actor} = object) do
140 object
141 |> Map.put("actor", get_actor(%{"actor" => actor}))
142 end
143
144 def fix_likes(%{"likes" => likes} = object)
145 when is_bitstring(likes) do
146 # Check for standardisation
147 # This is what Peertube does
148 # curl -H 'Accept: application/activity+json' $likes | jq .totalItems
149 object
150 |> Map.put("likes", [])
151 |> Map.put("like_count", 0)
152 end
153
154 def fix_likes(object) do
155 object
156 end
157
158 def fix_in_reply_to(%{"inReplyTo" => in_reply_to} = object)
159 when not is_nil(in_reply_to) do
160 in_reply_to_id =
161 cond do
162 is_bitstring(in_reply_to) ->
163 in_reply_to
164
165 is_map(in_reply_to) && is_bitstring(in_reply_to["id"]) ->
166 in_reply_to["id"]
167
168 is_list(in_reply_to) && is_bitstring(Enum.at(in_reply_to, 0)) ->
169 Enum.at(in_reply_to, 0)
170
171 # Maybe I should output an error too?
172 true ->
173 ""
174 end
175
176 case fetch_obj_helper(in_reply_to_id) do
177 {:ok, replied_object} ->
178 with %Activity{} = activity <-
179 Activity.get_create_by_object_ap_id(replied_object.data["id"]) do
180 object
181 |> Map.put("inReplyTo", replied_object.data["id"])
182 |> Map.put("inReplyToAtomUri", object["inReplyToAtomUri"] || in_reply_to_id)
183 |> Map.put("inReplyToStatusId", activity.id)
184 |> Map.put("conversation", replied_object.data["context"] || object["conversation"])
185 |> Map.put("context", replied_object.data["context"] || object["conversation"])
186 else
187 e ->
188 Logger.error("Couldn't fetch \"#{inspect(in_reply_to_id)}\", error: #{inspect(e)}")
189 object
190 end
191
192 e ->
193 Logger.error("Couldn't fetch \"#{inspect(in_reply_to_id)}\", error: #{inspect(e)}")
194 object
195 end
196 end
197
198 def fix_in_reply_to(object), do: object
199
200 def fix_context(object) do
201 context = object["context"] || object["conversation"] || Utils.generate_context_id()
202
203 object
204 |> Map.put("context", context)
205 |> Map.put("conversation", context)
206 end
207
208 def fix_attachments(%{"attachment" => attachment} = object) when is_list(attachment) do
209 attachments =
210 attachment
211 |> Enum.map(fn data ->
212 media_type = data["mediaType"] || data["mimeType"]
213 href = data["url"] || data["href"]
214
215 url = [%{"type" => "Link", "mediaType" => media_type, "href" => href}]
216
217 data
218 |> Map.put("mediaType", media_type)
219 |> Map.put("url", url)
220 end)
221
222 object
223 |> Map.put("attachment", attachments)
224 end
225
226 def fix_attachments(%{"attachment" => attachment} = object) when is_map(attachment) do
227 Map.put(object, "attachment", [attachment])
228 |> fix_attachments()
229 end
230
231 def fix_attachments(object), do: object
232
233 def fix_url(%{"url" => url} = object) when is_map(url) do
234 object
235 |> Map.put("url", url["href"])
236 end
237
238 def fix_url(%{"type" => "Video", "url" => url} = object) when is_list(url) do
239 first_element = Enum.at(url, 0)
240
241 link_element =
242 url
243 |> Enum.filter(fn x -> is_map(x) end)
244 |> Enum.filter(fn x -> x["mimeType"] == "text/html" end)
245 |> Enum.at(0)
246
247 object
248 |> Map.put("attachment", [first_element])
249 |> Map.put("url", link_element["href"])
250 end
251
252 def fix_url(%{"type" => object_type, "url" => url} = object)
253 when object_type != "Video" and is_list(url) do
254 first_element = Enum.at(url, 0)
255
256 url_string =
257 cond do
258 is_bitstring(first_element) -> first_element
259 is_map(first_element) -> first_element["href"] || ""
260 true -> ""
261 end
262
263 object
264 |> Map.put("url", url_string)
265 end
266
267 def fix_url(object), do: object
268
269 def fix_emoji(%{"tag" => tags} = object) when is_list(tags) do
270 emoji = tags |> Enum.filter(fn data -> data["type"] == "Emoji" and data["icon"] end)
271
272 emoji =
273 emoji
274 |> Enum.reduce(%{}, fn data, mapping ->
275 name = String.trim(data["name"], ":")
276
277 mapping |> Map.put(name, data["icon"]["url"])
278 end)
279
280 # we merge mastodon and pleroma emoji into a single mapping, to allow for both wire formats
281 emoji = Map.merge(object["emoji"] || %{}, emoji)
282
283 object
284 |> Map.put("emoji", emoji)
285 end
286
287 def fix_emoji(%{"tag" => %{"type" => "Emoji"} = tag} = object) do
288 name = String.trim(tag["name"], ":")
289 emoji = %{name => tag["icon"]["url"]}
290
291 object
292 |> Map.put("emoji", emoji)
293 end
294
295 def fix_emoji(object), do: object
296
297 def fix_tag(%{"tag" => tag} = object) when is_list(tag) do
298 tags =
299 tag
300 |> Enum.filter(fn data -> data["type"] == "Hashtag" and data["name"] end)
301 |> Enum.map(fn data -> String.slice(data["name"], 1..-1) end)
302
303 combined = tag ++ tags
304
305 object
306 |> Map.put("tag", combined)
307 end
308
309 def fix_tag(%{"tag" => %{"type" => "Hashtag", "name" => hashtag} = tag} = object) do
310 combined = [tag, String.slice(hashtag, 1..-1)]
311
312 object
313 |> Map.put("tag", combined)
314 end
315
316 def fix_tag(object), do: object
317
318 # content map usually only has one language so this will do for now.
319 def fix_content_map(%{"contentMap" => content_map} = object) do
320 content_groups = Map.to_list(content_map)
321 {_, content} = Enum.at(content_groups, 0)
322
323 object
324 |> Map.put("content", content)
325 end
326
327 def fix_content_map(object), do: object
328
329 defp mastodon_follow_hack(%{"id" => id, "actor" => follower_id}, followed) do
330 with true <- id =~ "follows",
331 %User{local: true} = follower <- User.get_cached_by_ap_id(follower_id),
332 %Activity{} = activity <- Utils.fetch_latest_follow(follower, followed) do
333 {:ok, activity}
334 else
335 _ -> {:error, nil}
336 end
337 end
338
339 defp mastodon_follow_hack(_, _), do: {:error, nil}
340
341 defp get_follow_activity(follow_object, followed) do
342 with object_id when not is_nil(object_id) <- Utils.get_ap_id(follow_object),
343 {_, %Activity{} = activity} <- {:activity, Activity.get_by_ap_id(object_id)} do
344 {:ok, activity}
345 else
346 # Can't find the activity. This might a Mastodon 2.3 "Accept"
347 {:activity, nil} ->
348 mastodon_follow_hack(follow_object, followed)
349
350 _ ->
351 {:error, nil}
352 end
353 end
354
355 # disallow objects with bogus IDs
356 def handle_incoming(%{"id" => nil}), do: :error
357 def handle_incoming(%{"id" => ""}), do: :error
358 # length of https:// = 8, should validate better, but good enough for now.
359 def handle_incoming(%{"id" => id}) when not (is_binary(id) and length(id) > 8), do: :error
360
361 # TODO: validate those with a Ecto scheme
362 # - tags
363 # - emoji
364 def handle_incoming(%{"type" => "Create", "object" => %{"type" => objtype} = object} = data)
365 when objtype in ["Article", "Note", "Video", "Page"] do
366 actor = get_actor(data)
367
368 data =
369 Map.put(data, "actor", actor)
370 |> fix_addressing
371
372 with nil <- Activity.get_create_by_object_ap_id(object["id"]),
373 %User{} = user <- User.get_or_fetch_by_ap_id(data["actor"]) do
374 object = fix_object(data["object"])
375
376 params = %{
377 to: data["to"],
378 object: object,
379 actor: user,
380 context: object["conversation"],
381 local: false,
382 published: data["published"],
383 additional:
384 Map.take(data, [
385 "cc",
386 "directMessage",
387 "id"
388 ])
389 }
390
391 ActivityPub.create(params)
392 else
393 %Activity{} = activity -> {:ok, activity}
394 _e -> :error
395 end
396 end
397
398 def handle_incoming(
399 %{"type" => "Follow", "object" => followed, "actor" => follower, "id" => id} = data
400 ) do
401 with %User{local: true} = followed <- User.get_cached_by_ap_id(followed),
402 %User{} = follower <- User.get_or_fetch_by_ap_id(follower),
403 {:ok, activity} <- ActivityPub.follow(follower, followed, id, false) do
404 if not User.locked?(followed) do
405 ActivityPub.accept(%{
406 to: [follower.ap_id],
407 actor: followed.ap_id,
408 object: data,
409 local: true
410 })
411
412 User.follow(follower, followed)
413 end
414
415 {:ok, activity}
416 else
417 _e -> :error
418 end
419 end
420
421 def handle_incoming(
422 %{"type" => "Accept", "object" => follow_object, "actor" => _actor, "id" => _id} = data
423 ) do
424 with actor <- get_actor(data),
425 %User{} = followed <- User.get_or_fetch_by_ap_id(actor),
426 {:ok, follow_activity} <- get_follow_activity(follow_object, followed),
427 {:ok, follow_activity} <- Utils.update_follow_state(follow_activity, "accept"),
428 %User{local: true} = follower <- User.get_cached_by_ap_id(follow_activity.data["actor"]),
429 {:ok, activity} <-
430 ActivityPub.accept(%{
431 to: follow_activity.data["to"],
432 type: "Accept",
433 actor: followed.ap_id,
434 object: follow_activity.data["id"],
435 local: false
436 }) do
437 if not User.following?(follower, followed) do
438 {:ok, _follower} = User.follow(follower, followed)
439 end
440
441 {:ok, activity}
442 else
443 _e -> :error
444 end
445 end
446
447 def handle_incoming(
448 %{"type" => "Reject", "object" => follow_object, "actor" => _actor, "id" => _id} = data
449 ) do
450 with actor <- get_actor(data),
451 %User{} = followed <- User.get_or_fetch_by_ap_id(actor),
452 {:ok, follow_activity} <- get_follow_activity(follow_object, followed),
453 {:ok, follow_activity} <- Utils.update_follow_state(follow_activity, "reject"),
454 %User{local: true} = follower <- User.get_cached_by_ap_id(follow_activity.data["actor"]),
455 {:ok, activity} <-
456 ActivityPub.accept(%{
457 to: follow_activity.data["to"],
458 type: "Accept",
459 actor: followed.ap_id,
460 object: follow_activity.data["id"],
461 local: false
462 }) do
463 User.unfollow(follower, followed)
464
465 {:ok, activity}
466 else
467 _e -> :error
468 end
469 end
470
471 def handle_incoming(
472 %{"type" => "Like", "object" => object_id, "actor" => _actor, "id" => id} = data
473 ) do
474 with actor <- get_actor(data),
475 %User{} = actor <- User.get_or_fetch_by_ap_id(actor),
476 {:ok, object} <- get_obj_helper(object_id) || fetch_obj_helper(object_id),
477 {:ok, activity, _object} <- ActivityPub.like(actor, object, id, false) do
478 {:ok, activity}
479 else
480 _e -> :error
481 end
482 end
483
484 def handle_incoming(
485 %{"type" => "Announce", "object" => object_id, "actor" => _actor, "id" => id} = data
486 ) do
487 with actor <- get_actor(data),
488 %User{} = actor <- User.get_or_fetch_by_ap_id(actor),
489 {:ok, object} <- get_obj_helper(object_id) || fetch_obj_helper(object_id),
490 public <- ActivityPub.is_public?(data),
491 {:ok, activity, _object} <- ActivityPub.announce(actor, object, id, false, public) do
492 {:ok, activity}
493 else
494 _e -> :error
495 end
496 end
497
498 def handle_incoming(
499 %{"type" => "Update", "object" => %{"type" => object_type} = object, "actor" => actor_id} =
500 data
501 )
502 when object_type in ["Person", "Application", "Service", "Organization"] do
503 with %User{ap_id: ^actor_id} = actor <- User.get_by_ap_id(object["id"]) do
504 {:ok, new_user_data} = ActivityPub.user_data_from_user_object(object)
505
506 banner = new_user_data[:info]["banner"]
507 locked = new_user_data[:info]["locked"] || false
508
509 update_data =
510 new_user_data
511 |> Map.take([:name, :bio, :avatar])
512 |> Map.put(:info, %{"banner" => banner, "locked" => locked})
513
514 actor
515 |> User.upgrade_changeset(update_data)
516 |> User.update_and_set_cache()
517
518 ActivityPub.update(%{
519 local: false,
520 to: data["to"] || [],
521 cc: data["cc"] || [],
522 object: object,
523 actor: actor_id
524 })
525 else
526 e ->
527 Logger.error(e)
528 :error
529 end
530 end
531
532 # TODO: We presently assume that any actor on the same origin domain as the object being
533 # deleted has the rights to delete that object. A better way to validate whether or not
534 # the object should be deleted is to refetch the object URI, which should return either
535 # an error or a tombstone. This would allow us to verify that a deletion actually took
536 # place.
537 def handle_incoming(
538 %{"type" => "Delete", "object" => object_id, "actor" => _actor, "id" => _id} = data
539 ) do
540 object_id = Utils.get_ap_id(object_id)
541
542 with actor <- get_actor(data),
543 %User{} = actor <- User.get_or_fetch_by_ap_id(actor),
544 {:ok, object} <- get_obj_helper(object_id) || fetch_obj_helper(object_id),
545 :ok <- contain_origin(actor.ap_id, object.data),
546 {:ok, activity} <- ActivityPub.delete(object, false) do
547 {:ok, activity}
548 else
549 _e -> :error
550 end
551 end
552
553 def handle_incoming(
554 %{
555 "type" => "Undo",
556 "object" => %{"type" => "Announce", "object" => object_id},
557 "actor" => _actor,
558 "id" => id
559 } = data
560 ) do
561 with actor <- get_actor(data),
562 %User{} = actor <- User.get_or_fetch_by_ap_id(actor),
563 {:ok, object} <- get_obj_helper(object_id) || fetch_obj_helper(object_id),
564 {:ok, activity, _} <- ActivityPub.unannounce(actor, object, id, false) do
565 {:ok, activity}
566 else
567 _e -> :error
568 end
569 end
570
571 def handle_incoming(
572 %{
573 "type" => "Undo",
574 "object" => %{"type" => "Follow", "object" => followed},
575 "actor" => follower,
576 "id" => id
577 } = _data
578 ) do
579 with %User{local: true} = followed <- User.get_cached_by_ap_id(followed),
580 %User{} = follower <- User.get_or_fetch_by_ap_id(follower),
581 {:ok, activity} <- ActivityPub.unfollow(follower, followed, id, false) do
582 User.unfollow(follower, followed)
583 {:ok, activity}
584 else
585 _e -> :error
586 end
587 end
588
589 def handle_incoming(
590 %{
591 "type" => "Undo",
592 "object" => %{"type" => "Block", "object" => blocked},
593 "actor" => blocker,
594 "id" => id
595 } = _data
596 ) do
597 with true <- Pleroma.Config.get([:activitypub, :accept_blocks]),
598 %User{local: true} = blocked <- User.get_cached_by_ap_id(blocked),
599 %User{} = blocker <- User.get_or_fetch_by_ap_id(blocker),
600 {:ok, activity} <- ActivityPub.unblock(blocker, blocked, id, false) do
601 User.unblock(blocker, blocked)
602 {:ok, activity}
603 else
604 _e -> :error
605 end
606 end
607
608 def handle_incoming(
609 %{"type" => "Block", "object" => blocked, "actor" => blocker, "id" => id} = _data
610 ) do
611 with true <- Pleroma.Config.get([:activitypub, :accept_blocks]),
612 %User{local: true} = blocked = User.get_cached_by_ap_id(blocked),
613 %User{} = blocker = User.get_or_fetch_by_ap_id(blocker),
614 {:ok, activity} <- ActivityPub.block(blocker, blocked, id, false) do
615 User.unfollow(blocker, blocked)
616 User.block(blocker, blocked)
617 {:ok, activity}
618 else
619 _e -> :error
620 end
621 end
622
623 def handle_incoming(
624 %{
625 "type" => "Undo",
626 "object" => %{"type" => "Like", "object" => object_id},
627 "actor" => _actor,
628 "id" => id
629 } = data
630 ) do
631 with actor <- get_actor(data),
632 %User{} = actor <- User.get_or_fetch_by_ap_id(actor),
633 {:ok, object} <- get_obj_helper(object_id) || fetch_obj_helper(object_id),
634 {:ok, activity, _, _} <- ActivityPub.unlike(actor, object, id, false) do
635 {:ok, activity}
636 else
637 _e -> :error
638 end
639 end
640
641 def handle_incoming(_), do: :error
642
643 def fetch_obj_helper(id) when is_bitstring(id), do: ActivityPub.fetch_object_from_id(id)
644 def fetch_obj_helper(obj) when is_map(obj), do: ActivityPub.fetch_object_from_id(obj["id"])
645
646 def get_obj_helper(id) do
647 if object = Object.normalize(id), do: {:ok, object}, else: nil
648 end
649
650 def set_reply_to_uri(%{"inReplyTo" => inReplyTo} = object) do
651 with false <- String.starts_with?(inReplyTo, "http"),
652 {:ok, %{data: replied_to_object}} <- get_obj_helper(inReplyTo) do
653 Map.put(object, "inReplyTo", replied_to_object["external_url"] || inReplyTo)
654 else
655 _e -> object
656 end
657 end
658
659 def set_reply_to_uri(obj), do: obj
660
661 # Prepares the object of an outgoing create activity.
662 def prepare_object(object) do
663 object
664 |> set_sensitive
665 |> add_hashtags
666 |> add_mention_tags
667 |> add_emoji_tags
668 |> add_attributed_to
669 |> add_likes
670 |> prepare_attachments
671 |> set_conversation
672 |> set_reply_to_uri
673 |> strip_internal_fields
674 |> strip_internal_tags
675 end
676
677 # @doc
678 # """
679 # internal -> Mastodon
680 # """
681
682 def prepare_outgoing(%{"type" => "Create", "object" => object} = data) do
683 object =
684 object
685 |> prepare_object
686
687 data =
688 data
689 |> Map.put("object", object)
690 |> Map.merge(Utils.make_json_ld_header())
691
692 {:ok, data}
693 end
694
695 # Mastodon Accept/Reject requires a non-normalized object containing the actor URIs,
696 # because of course it does.
697 def prepare_outgoing(%{"type" => "Accept"} = data) do
698 with follow_activity <- Activity.normalize(data["object"]) do
699 object = %{
700 "actor" => follow_activity.actor,
701 "object" => follow_activity.data["object"],
702 "id" => follow_activity.data["id"],
703 "type" => "Follow"
704 }
705
706 data =
707 data
708 |> Map.put("object", object)
709 |> Map.merge(Utils.make_json_ld_header())
710
711 {:ok, data}
712 end
713 end
714
715 def prepare_outgoing(%{"type" => "Reject"} = data) do
716 with follow_activity <- Activity.normalize(data["object"]) do
717 object = %{
718 "actor" => follow_activity.actor,
719 "object" => follow_activity.data["object"],
720 "id" => follow_activity.data["id"],
721 "type" => "Follow"
722 }
723
724 data =
725 data
726 |> Map.put("object", object)
727 |> Map.merge(Utils.make_json_ld_header())
728
729 {:ok, data}
730 end
731 end
732
733 def prepare_outgoing(%{"type" => _type} = data) do
734 data =
735 data
736 |> maybe_fix_object_url
737 |> Map.merge(Utils.make_json_ld_header())
738
739 {:ok, data}
740 end
741
742 def maybe_fix_object_url(data) do
743 if is_binary(data["object"]) and not String.starts_with?(data["object"], "http") do
744 case fetch_obj_helper(data["object"]) do
745 {:ok, relative_object} ->
746 if relative_object.data["external_url"] do
747 _data =
748 data
749 |> Map.put("object", relative_object.data["external_url"])
750 else
751 data
752 end
753
754 e ->
755 Logger.error("Couldn't fetch #{data["object"]} #{inspect(e)}")
756 data
757 end
758 else
759 data
760 end
761 end
762
763 def add_hashtags(object) do
764 tags =
765 (object["tag"] || [])
766 |> Enum.map(fn tag ->
767 %{
768 "href" => Pleroma.Web.Endpoint.url() <> "/tags/#{tag}",
769 "name" => "##{tag}",
770 "type" => "Hashtag"
771 }
772 end)
773
774 object
775 |> Map.put("tag", tags)
776 end
777
778 def add_mention_tags(object) do
779 mentions =
780 object
781 |> Utils.get_notified_from_object()
782 |> Enum.map(fn user ->
783 %{"type" => "Mention", "href" => user.ap_id, "name" => "@#{user.nickname}"}
784 end)
785
786 tags = object["tag"] || []
787
788 object
789 |> Map.put("tag", tags ++ mentions)
790 end
791
792 # TODO: we should probably send mtime instead of unix epoch time for updated
793 def add_emoji_tags(object) do
794 tags = object["tag"] || []
795 emoji = object["emoji"] || []
796
797 out =
798 emoji
799 |> Enum.map(fn {name, url} ->
800 %{
801 "icon" => %{"url" => url, "type" => "Image"},
802 "name" => ":" <> name <> ":",
803 "type" => "Emoji",
804 "updated" => "1970-01-01T00:00:00Z",
805 "id" => url
806 }
807 end)
808
809 object
810 |> Map.put("tag", tags ++ out)
811 end
812
813 def set_conversation(object) do
814 Map.put(object, "conversation", object["context"])
815 end
816
817 def set_sensitive(object) do
818 tags = object["tag"] || []
819 Map.put(object, "sensitive", "nsfw" in tags)
820 end
821
822 def add_attributed_to(object) do
823 attributedTo = object["attributedTo"] || object["actor"]
824
825 object
826 |> Map.put("attributedTo", attributedTo)
827 end
828
829 def add_likes(%{"id" => id, "like_count" => likes} = object) do
830 likes = %{
831 "id" => "#{id}/likes",
832 "first" => "#{id}/likes?page=1",
833 "type" => "OrderedCollection",
834 "totalItems" => likes
835 }
836
837 object
838 |> Map.put("likes", likes)
839 end
840
841 def add_likes(object) do
842 object
843 end
844
845 def prepare_attachments(object) do
846 attachments =
847 (object["attachment"] || [])
848 |> Enum.map(fn data ->
849 [%{"mediaType" => media_type, "href" => href} | _] = data["url"]
850 %{"url" => href, "mediaType" => media_type, "name" => data["name"], "type" => "Document"}
851 end)
852
853 object
854 |> Map.put("attachment", attachments)
855 end
856
857 defp strip_internal_fields(object) do
858 object
859 |> Map.drop([
860 "like_count",
861 "announcements",
862 "announcement_count",
863 "emoji",
864 "context_id"
865 ])
866 end
867
868 defp strip_internal_tags(%{"tag" => tags} = object) do
869 tags =
870 tags
871 |> Enum.filter(fn x -> is_map(x) end)
872
873 object
874 |> Map.put("tag", tags)
875 end
876
877 defp strip_internal_tags(object), do: object
878
879 defp user_upgrade_task(user) do
880 old_follower_address = User.ap_followers(user)
881
882 q =
883 from(
884 u in User,
885 where: ^old_follower_address in u.following,
886 update: [
887 set: [
888 following:
889 fragment(
890 "array_replace(?,?,?)",
891 u.following,
892 ^old_follower_address,
893 ^user.follower_address
894 )
895 ]
896 ]
897 )
898
899 Repo.update_all(q, [])
900
901 maybe_retire_websub(user.ap_id)
902
903 q =
904 from(
905 a in Activity,
906 where: ^old_follower_address in a.recipients,
907 update: [
908 set: [
909 recipients:
910 fragment(
911 "array_replace(?,?,?)",
912 a.recipients,
913 ^old_follower_address,
914 ^user.follower_address
915 )
916 ]
917 ]
918 )
919
920 Repo.update_all(q, [])
921 end
922
923 def upgrade_user_from_ap_id(ap_id, async \\ true) do
924 with %User{local: false} = user <- User.get_by_ap_id(ap_id),
925 {:ok, data} <- ActivityPub.fetch_and_prepare_user_from_ap_id(ap_id) do
926 already_ap = User.ap_enabled?(user)
927
928 {:ok, user} =
929 User.upgrade_changeset(user, data)
930 |> Repo.update()
931
932 if !already_ap do
933 # This could potentially take a long time, do it in the background
934 if async do
935 Task.start(fn ->
936 user_upgrade_task(user)
937 end)
938 else
939 user_upgrade_task(user)
940 end
941 end
942
943 {:ok, user}
944 else
945 e -> e
946 end
947 end
948
949 def maybe_retire_websub(ap_id) do
950 # some sanity checks
951 if is_binary(ap_id) && String.length(ap_id) > 8 do
952 q =
953 from(
954 ws in Pleroma.Web.Websub.WebsubClientSubscription,
955 where: fragment("? like ?", ws.topic, ^"#{ap_id}%")
956 )
957
958 Repo.delete_all(q)
959 end
960 end
961
962 def maybe_fix_user_url(data) do
963 if is_map(data["url"]) do
964 Map.put(data, "url", data["url"]["href"])
965 else
966 data
967 end
968 end
969
970 def maybe_fix_user_object(data) do
971 data
972 |> maybe_fix_user_url
973 end
974 end