Pipeline Ingestion: Note
[akkoma] / lib / pleroma / web / activity_pub / transmogrifier.ex
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2021 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.Activity
10 alias Pleroma.EctoType.ActivityPub.ObjectValidators
11 alias Pleroma.Maps
12 alias Pleroma.Object
13 alias Pleroma.Object.Containment
14 alias Pleroma.Repo
15 alias Pleroma.User
16 alias Pleroma.Web.ActivityPub.ActivityPub
17 alias Pleroma.Web.ActivityPub.Builder
18 alias Pleroma.Web.ActivityPub.ObjectValidator
19 alias Pleroma.Web.ActivityPub.Pipeline
20 alias Pleroma.Web.ActivityPub.Utils
21 alias Pleroma.Web.ActivityPub.Visibility
22 alias Pleroma.Web.Federator
23 alias Pleroma.Workers.TransmogrifierWorker
24
25 import Ecto.Query
26
27 require Logger
28 require Pleroma.Constants
29
30 @doc """
31 Modifies an incoming AP object (mastodon format) to our internal format.
32 """
33 def fix_object(object, options \\ []) do
34 object
35 |> strip_internal_fields()
36 |> fix_actor()
37 |> fix_url()
38 |> fix_attachments()
39 |> fix_context()
40 |> fix_in_reply_to(options)
41 |> fix_emoji()
42 |> fix_tag()
43 |> fix_content_map()
44 |> fix_addressing()
45 |> fix_summary()
46 |> fix_type(options)
47 end
48
49 def fix_summary(%{"summary" => nil} = object) do
50 Map.put(object, "summary", "")
51 end
52
53 def fix_summary(%{"summary" => _} = object) do
54 # summary is present, nothing to do
55 object
56 end
57
58 def fix_summary(object), do: Map.put(object, "summary", "")
59
60 def fix_addressing_list(map, field) do
61 addrs = map[field]
62
63 cond do
64 is_list(addrs) ->
65 Map.put(map, field, Enum.filter(addrs, &is_binary/1))
66
67 is_binary(addrs) ->
68 Map.put(map, field, [addrs])
69
70 true ->
71 Map.put(map, field, [])
72 end
73 end
74
75 # if directMessage flag is set to true, leave the addressing alone
76 def fix_explicit_addressing(%{"directMessage" => true} = object, _follower_collection),
77 do: object
78
79 def fix_explicit_addressing(%{"to" => to, "cc" => cc} = object, follower_collection) do
80 explicit_mentions =
81 Utils.determine_explicit_mentions(object) ++
82 [Pleroma.Constants.as_public(), follower_collection]
83
84 explicit_to = Enum.filter(to, fn x -> x in explicit_mentions end)
85 explicit_cc = Enum.filter(to, fn x -> x not in explicit_mentions end)
86
87 final_cc =
88 (cc ++ explicit_cc)
89 |> Enum.filter(& &1)
90 |> Enum.reject(fn x -> String.ends_with?(x, "/followers") and x != follower_collection end)
91 |> Enum.uniq()
92
93 object
94 |> Map.put("to", explicit_to)
95 |> Map.put("cc", final_cc)
96 end
97
98 # if as:Public is addressed, then make sure the followers collection is also addressed
99 # so that the activities will be delivered to local users.
100 def fix_implicit_addressing(%{"to" => to, "cc" => cc} = object, followers_collection) do
101 recipients = to ++ cc
102
103 if followers_collection not in recipients do
104 cond do
105 Pleroma.Constants.as_public() in cc ->
106 to = to ++ [followers_collection]
107 Map.put(object, "to", to)
108
109 Pleroma.Constants.as_public() in to ->
110 cc = cc ++ [followers_collection]
111 Map.put(object, "cc", cc)
112
113 true ->
114 object
115 end
116 else
117 object
118 end
119 end
120
121 def fix_addressing(object) do
122 {:ok, %User{follower_address: follower_collection}} =
123 object
124 |> Containment.get_actor()
125 |> User.get_or_fetch_by_ap_id()
126
127 object
128 |> fix_addressing_list("to")
129 |> fix_addressing_list("cc")
130 |> fix_addressing_list("bto")
131 |> fix_addressing_list("bcc")
132 |> fix_explicit_addressing(follower_collection)
133 |> fix_implicit_addressing(follower_collection)
134 end
135
136 def fix_actor(%{"attributedTo" => actor} = object) do
137 actor = Containment.get_actor(%{"actor" => actor})
138
139 # TODO: Remove actor field for Objects
140 object
141 |> Map.put("actor", actor)
142 |> Map.put("attributedTo", actor)
143 end
144
145 def fix_in_reply_to(object, options \\ [])
146
147 def fix_in_reply_to(%{"inReplyTo" => in_reply_to} = object, options)
148 when not is_nil(in_reply_to) do
149 in_reply_to_id = prepare_in_reply_to(in_reply_to)
150 depth = (options[:depth] || 0) + 1
151
152 if Federator.allowed_thread_distance?(depth) do
153 with {:ok, replied_object} <- get_obj_helper(in_reply_to_id, options),
154 %Activity{} <- Activity.get_create_by_object_ap_id(replied_object.data["id"]) do
155 object
156 |> Map.put("inReplyTo", replied_object.data["id"])
157 |> Map.put("context", replied_object.data["context"] || object["conversation"])
158 |> Map.drop(["conversation", "inReplyToAtomUri"])
159 else
160 e ->
161 Logger.warn("Couldn't fetch #{inspect(in_reply_to_id)}, error: #{inspect(e)}")
162 object
163 end
164 else
165 object
166 end
167 end
168
169 def fix_in_reply_to(object, _options), do: object
170
171 defp prepare_in_reply_to(in_reply_to) do
172 cond do
173 is_bitstring(in_reply_to) ->
174 in_reply_to
175
176 is_map(in_reply_to) && is_bitstring(in_reply_to["id"]) ->
177 in_reply_to["id"]
178
179 is_list(in_reply_to) && is_bitstring(Enum.at(in_reply_to, 0)) ->
180 Enum.at(in_reply_to, 0)
181
182 true ->
183 ""
184 end
185 end
186
187 def fix_context(object) do
188 context = object["context"] || object["conversation"] || Utils.generate_context_id()
189
190 object
191 |> Map.put("context", context)
192 |> Map.drop(["conversation"])
193 end
194
195 def fix_attachments(%{"attachment" => attachment} = object) when is_list(attachment) do
196 attachments =
197 Enum.map(attachment, fn data ->
198 url =
199 cond do
200 is_list(data["url"]) -> List.first(data["url"])
201 is_map(data["url"]) -> data["url"]
202 true -> nil
203 end
204
205 media_type =
206 cond do
207 is_map(url) && MIME.valid?(url["mediaType"]) -> url["mediaType"]
208 MIME.valid?(data["mediaType"]) -> data["mediaType"]
209 MIME.valid?(data["mimeType"]) -> data["mimeType"]
210 true -> nil
211 end
212
213 href =
214 cond do
215 is_map(url) && is_binary(url["href"]) -> url["href"]
216 is_binary(data["url"]) -> data["url"]
217 is_binary(data["href"]) -> data["href"]
218 true -> nil
219 end
220
221 if href do
222 attachment_url =
223 %{
224 "href" => href,
225 "type" => Map.get(url || %{}, "type", "Link")
226 }
227 |> Maps.put_if_present("mediaType", media_type)
228
229 %{
230 "url" => [attachment_url],
231 "type" => data["type"] || "Document"
232 }
233 |> Maps.put_if_present("mediaType", media_type)
234 |> Maps.put_if_present("name", data["name"])
235 |> Maps.put_if_present("blurhash", data["blurhash"])
236 else
237 nil
238 end
239 end)
240 |> Enum.filter(& &1)
241
242 Map.put(object, "attachment", attachments)
243 end
244
245 def fix_attachments(%{"attachment" => attachment} = object) when is_map(attachment) do
246 object
247 |> Map.put("attachment", [attachment])
248 |> fix_attachments()
249 end
250
251 def fix_attachments(object), do: object
252
253 def fix_url(%{"url" => url} = object) when is_map(url) do
254 Map.put(object, "url", url["href"])
255 end
256
257 def fix_url(%{"url" => url} = object) when is_list(url) do
258 first_element = Enum.at(url, 0)
259
260 url_string =
261 cond do
262 is_bitstring(first_element) -> first_element
263 is_map(first_element) -> first_element["href"] || ""
264 true -> ""
265 end
266
267 Map.put(object, "url", url_string)
268 end
269
270 def fix_url(object), do: object
271
272 def fix_emoji(%{"tag" => tags} = object) when is_list(tags) do
273 emoji =
274 tags
275 |> Enum.filter(fn data -> is_map(data) and data["type"] == "Emoji" and data["icon"] end)
276 |> Enum.reduce(%{}, fn data, mapping ->
277 name = String.trim(data["name"], ":")
278
279 Map.put(mapping, name, data["icon"]["url"])
280 end)
281
282 Map.put(object, "emoji", emoji)
283 end
284
285 def fix_emoji(%{"tag" => %{"type" => "Emoji"} = tag} = object) do
286 name = String.trim(tag["name"], ":")
287 emoji = %{name => tag["icon"]["url"]}
288
289 Map.put(object, "emoji", emoji)
290 end
291
292 def fix_emoji(object), do: object
293
294 def fix_tag(%{"tag" => tag} = object) when is_list(tag) do
295 tags =
296 tag
297 |> Enum.filter(fn data -> data["type"] == "Hashtag" and data["name"] end)
298 |> Enum.map(fn
299 %{"name" => "#" <> hashtag} -> String.downcase(hashtag)
300 %{"name" => hashtag} -> String.downcase(hashtag)
301 end)
302
303 Map.put(object, "tag", tag ++ tags)
304 end
305
306 def fix_tag(%{"tag" => %{} = tag} = object) do
307 object
308 |> Map.put("tag", [tag])
309 |> fix_tag
310 end
311
312 def fix_tag(object), do: object
313
314 # content map usually only has one language so this will do for now.
315 def fix_content_map(%{"contentMap" => content_map} = object) do
316 content_groups = Map.to_list(content_map)
317 {_, content} = Enum.at(content_groups, 0)
318
319 Map.put(object, "content", content)
320 end
321
322 def fix_content_map(object), do: object
323
324 def fix_type(object, options \\ [])
325
326 def fix_type(%{"inReplyTo" => reply_id, "name" => _} = object, options)
327 when is_binary(reply_id) do
328 with true <- Federator.allowed_thread_distance?(options[:depth]),
329 {:ok, %{data: %{"type" => "Question"} = _} = _} <- get_obj_helper(reply_id, options) do
330 Map.put(object, "type", "Answer")
331 else
332 _ -> object
333 end
334 end
335
336 def fix_type(object, _), do: object
337
338 # Reduce the object list to find the reported user.
339 defp get_reported(objects) do
340 Enum.reduce_while(objects, nil, fn ap_id, _ ->
341 with %User{} = user <- User.get_cached_by_ap_id(ap_id) do
342 {:halt, user}
343 else
344 _ -> {:cont, nil}
345 end
346 end)
347 end
348
349 # Compatibility wrapper for Mastodon votes
350 defp handle_create(%{"object" => %{"type" => "Answer"}} = data, _user) do
351 handle_incoming(data)
352 end
353
354 defp handle_create(%{"object" => object} = data, user) do
355 %{
356 to: data["to"],
357 object: object,
358 actor: user,
359 context: object["context"],
360 local: false,
361 published: data["published"],
362 additional:
363 Map.take(data, [
364 "cc",
365 "directMessage",
366 "id"
367 ])
368 }
369 |> ActivityPub.create()
370 end
371
372 def handle_incoming(data, options \\ [])
373
374 # Flag objects are placed ahead of the ID check because Mastodon 2.8 and earlier send them
375 # with nil ID.
376 def handle_incoming(%{"type" => "Flag", "object" => objects, "actor" => actor} = data, _options) do
377 with context <- data["context"] || Utils.generate_context_id(),
378 content <- data["content"] || "",
379 %User{} = actor <- User.get_cached_by_ap_id(actor),
380 # Reduce the object list to find the reported user.
381 %User{} = account <- get_reported(objects),
382 # Remove the reported user from the object list.
383 statuses <- Enum.filter(objects, fn ap_id -> ap_id != account.ap_id end) do
384 %{
385 actor: actor,
386 context: context,
387 account: account,
388 statuses: statuses,
389 content: content,
390 additional: %{"cc" => [account.ap_id]}
391 }
392 |> ActivityPub.flag()
393 end
394 end
395
396 # disallow objects with bogus IDs
397 def handle_incoming(%{"id" => nil}, _options), do: :error
398 def handle_incoming(%{"id" => ""}, _options), do: :error
399 # length of https:// = 8, should validate better, but good enough for now.
400 def handle_incoming(%{"id" => id}, _options) when is_binary(id) and byte_size(id) < 8,
401 do: :error
402
403 # TODO: validate those with a Ecto scheme
404 # - tags
405 # - emoji
406 def handle_incoming(
407 %{"type" => "Create", "object" => %{"type" => "Page"} = object} = data,
408 options
409 ) do
410 actor = Containment.get_actor(data)
411
412 with nil <- Activity.get_create_by_object_ap_id(object["id"]),
413 {:ok, %User{} = user} <- User.get_or_fetch_by_ap_id(actor) do
414 data =
415 data
416 |> Map.put("object", fix_object(object, options))
417 |> Map.put("actor", actor)
418 |> fix_addressing()
419
420 with {:ok, created_activity} <- handle_create(data, user) do
421 reply_depth = (options[:depth] || 0) + 1
422
423 if Federator.allowed_thread_distance?(reply_depth) do
424 for reply_id <- replies(object) do
425 Pleroma.Workers.RemoteFetcherWorker.enqueue("fetch_remote", %{
426 "id" => reply_id,
427 "depth" => reply_depth
428 })
429 end
430 end
431
432 {:ok, created_activity}
433 end
434 else
435 %Activity{} = activity -> {:ok, activity}
436 _e -> :error
437 end
438 end
439
440 def handle_incoming(
441 %{"type" => "Listen", "object" => %{"type" => "Audio"} = object} = data,
442 options
443 ) do
444 actor = Containment.get_actor(data)
445
446 data =
447 Map.put(data, "actor", actor)
448 |> fix_addressing
449
450 with {:ok, %User{} = user} <- User.get_or_fetch_by_ap_id(data["actor"]) do
451 reply_depth = (options[:depth] || 0) + 1
452 options = Keyword.put(options, :depth, reply_depth)
453 object = fix_object(object, options)
454
455 params = %{
456 to: data["to"],
457 object: object,
458 actor: user,
459 context: nil,
460 local: false,
461 published: data["published"],
462 additional: Map.take(data, ["cc", "id"])
463 }
464
465 ActivityPub.listen(params)
466 else
467 _e -> :error
468 end
469 end
470
471 @misskey_reactions %{
472 "like" => "👍",
473 "love" => "❤️",
474 "laugh" => "😆",
475 "hmm" => "🤔",
476 "surprise" => "😮",
477 "congrats" => "🎉",
478 "angry" => "💢",
479 "confused" => "😥",
480 "rip" => "😇",
481 "pudding" => "🍮",
482 "star" => "⭐"
483 }
484
485 @doc "Rewrite misskey likes into EmojiReacts"
486 def handle_incoming(
487 %{
488 "type" => "Like",
489 "_misskey_reaction" => reaction
490 } = data,
491 options
492 ) do
493 data
494 |> Map.put("type", "EmojiReact")
495 |> Map.put("content", @misskey_reactions[reaction] || reaction)
496 |> handle_incoming(options)
497 end
498
499 def handle_incoming(
500 %{"type" => "Create", "object" => %{"type" => objtype, "id" => obj_id}} = data,
501 options
502 )
503 when objtype in ~w{Question Answer ChatMessage Audio Video Event Article Note} do
504 data = Map.put(data, "object", strip_internal_fields(data["object"]))
505 options = Keyword.put(options, :local, false)
506
507 with {:ok, %User{}} <- ObjectValidator.fetch_actor(data),
508 nil <- Activity.get_create_by_object_ap_id(obj_id),
509 {:ok, activity, _} <- Pipeline.common_pipeline(data, options) do
510 {:ok, activity}
511 else
512 %Activity{} = activity -> {:ok, activity}
513 e -> e
514 end
515 end
516
517 def handle_incoming(%{"type" => type} = data, _options)
518 when type in ~w{Like EmojiReact Announce} do
519 with :ok <- ObjectValidator.fetch_actor_and_object(data),
520 {:ok, activity, _meta} <-
521 Pipeline.common_pipeline(data, local: false) do
522 {:ok, activity}
523 else
524 e -> {:error, e}
525 end
526 end
527
528 def handle_incoming(
529 %{"type" => type} = data,
530 _options
531 )
532 when type in ~w{Update Block Follow Accept Reject} do
533 with {:ok, %User{}} <- ObjectValidator.fetch_actor(data),
534 {:ok, activity, _} <-
535 Pipeline.common_pipeline(data, local: false) do
536 {:ok, activity}
537 end
538 end
539
540 def handle_incoming(
541 %{"type" => "Delete"} = data,
542 _options
543 ) do
544 with {:ok, activity, _} <-
545 Pipeline.common_pipeline(data, local: false) do
546 {:ok, activity}
547 else
548 {:error, {:validate, _}} = e ->
549 # Check if we have a create activity for this
550 with {:ok, object_id} <- ObjectValidators.ObjectID.cast(data["object"]),
551 %Activity{data: %{"actor" => actor}} <-
552 Activity.create_by_object_ap_id(object_id) |> Repo.one(),
553 # We have one, insert a tombstone and retry
554 {:ok, tombstone_data, _} <- Builder.tombstone(actor, object_id),
555 {:ok, _tombstone} <- Object.create(tombstone_data) do
556 handle_incoming(data)
557 else
558 _ -> e
559 end
560 end
561 end
562
563 def handle_incoming(
564 %{
565 "type" => "Undo",
566 "object" => %{"type" => "Follow", "object" => followed},
567 "actor" => follower,
568 "id" => id
569 } = _data,
570 _options
571 ) do
572 with %User{local: true} = followed <- User.get_cached_by_ap_id(followed),
573 {:ok, %User{} = follower} <- User.get_or_fetch_by_ap_id(follower),
574 {:ok, activity} <- ActivityPub.unfollow(follower, followed, id, false) do
575 User.unfollow(follower, followed)
576 {:ok, activity}
577 else
578 _e -> :error
579 end
580 end
581
582 def handle_incoming(
583 %{
584 "type" => "Undo",
585 "object" => %{"type" => type}
586 } = data,
587 _options
588 )
589 when type in ["Like", "EmojiReact", "Announce", "Block"] do
590 with {:ok, activity, _} <- Pipeline.common_pipeline(data, local: false) do
591 {:ok, activity}
592 end
593 end
594
595 # For Undos that don't have the complete object attached, try to find it in our database.
596 def handle_incoming(
597 %{
598 "type" => "Undo",
599 "object" => object
600 } = activity,
601 options
602 )
603 when is_binary(object) do
604 with %Activity{data: data} <- Activity.get_by_ap_id(object) do
605 activity
606 |> Map.put("object", data)
607 |> handle_incoming(options)
608 else
609 _e -> :error
610 end
611 end
612
613 def handle_incoming(
614 %{
615 "type" => "Move",
616 "actor" => origin_actor,
617 "object" => origin_actor,
618 "target" => target_actor
619 },
620 _options
621 ) do
622 with %User{} = origin_user <- User.get_cached_by_ap_id(origin_actor),
623 {:ok, %User{} = target_user} <- User.get_or_fetch_by_ap_id(target_actor),
624 true <- origin_actor in target_user.also_known_as do
625 ActivityPub.move(origin_user, target_user, false)
626 else
627 _e -> :error
628 end
629 end
630
631 def handle_incoming(_, _), do: :error
632
633 @spec get_obj_helper(String.t(), Keyword.t()) :: {:ok, Object.t()} | nil
634 def get_obj_helper(id, options \\ []) do
635 options = Keyword.put(options, :fetch, true)
636
637 case Object.normalize(id, options) do
638 %Object{} = object -> {:ok, object}
639 _ -> nil
640 end
641 end
642
643 @spec get_embedded_obj_helper(String.t() | Object.t(), User.t()) :: {:ok, Object.t()} | nil
644 def get_embedded_obj_helper(%{"attributedTo" => attributed_to, "id" => object_id} = data, %User{
645 ap_id: ap_id
646 })
647 when attributed_to == ap_id do
648 with {:ok, activity} <-
649 handle_incoming(%{
650 "type" => "Create",
651 "to" => data["to"],
652 "cc" => data["cc"],
653 "actor" => attributed_to,
654 "object" => data
655 }) do
656 {:ok, Object.normalize(activity, fetch: false)}
657 else
658 _ -> get_obj_helper(object_id)
659 end
660 end
661
662 def get_embedded_obj_helper(object_id, _) do
663 get_obj_helper(object_id)
664 end
665
666 def set_reply_to_uri(%{"inReplyTo" => in_reply_to} = object) when is_binary(in_reply_to) do
667 with false <- String.starts_with?(in_reply_to, "http"),
668 {:ok, %{data: replied_to_object}} <- get_obj_helper(in_reply_to) do
669 Map.put(object, "inReplyTo", replied_to_object["external_url"] || in_reply_to)
670 else
671 _e -> object
672 end
673 end
674
675 def set_reply_to_uri(obj), do: obj
676
677 @doc """
678 Serialized Mastodon-compatible `replies` collection containing _self-replies_.
679 Based on Mastodon's ActivityPub::NoteSerializer#replies.
680 """
681 def set_replies(obj_data) do
682 replies_uris =
683 with limit when limit > 0 <-
684 Pleroma.Config.get([:activitypub, :note_replies_output_limit], 0),
685 %Object{} = object <- Object.get_cached_by_ap_id(obj_data["id"]) do
686 object
687 |> Object.self_replies()
688 |> select([o], fragment("?->>'id'", o.data))
689 |> limit(^limit)
690 |> Repo.all()
691 else
692 _ -> []
693 end
694
695 set_replies(obj_data, replies_uris)
696 end
697
698 defp set_replies(obj, []) do
699 obj
700 end
701
702 defp set_replies(obj, replies_uris) do
703 replies_collection = %{
704 "type" => "Collection",
705 "items" => replies_uris
706 }
707
708 Map.merge(obj, %{"replies" => replies_collection})
709 end
710
711 def replies(%{"replies" => %{"first" => %{"items" => items}}}) when not is_nil(items) do
712 items
713 end
714
715 def replies(%{"replies" => %{"items" => items}}) when not is_nil(items) do
716 items
717 end
718
719 def replies(_), do: []
720
721 # Prepares the object of an outgoing create activity.
722 def prepare_object(object) do
723 object
724 |> add_hashtags
725 |> add_mention_tags
726 |> add_emoji_tags
727 |> add_attributed_to
728 |> prepare_attachments
729 |> set_conversation
730 |> set_reply_to_uri
731 |> set_replies
732 |> strip_internal_fields
733 |> strip_internal_tags
734 |> set_type
735 end
736
737 # @doc
738 # """
739 # internal -> Mastodon
740 # """
741
742 def prepare_outgoing(%{"type" => activity_type, "object" => object_id} = data)
743 when activity_type in ["Create", "Listen"] do
744 object =
745 object_id
746 |> Object.normalize(fetch: false)
747 |> Map.get(:data)
748 |> prepare_object
749
750 data =
751 data
752 |> Map.put("object", object)
753 |> Map.merge(Utils.make_json_ld_header())
754 |> Map.delete("bcc")
755
756 {:ok, data}
757 end
758
759 def prepare_outgoing(%{"type" => "Announce", "actor" => ap_id, "object" => object_id} = data) do
760 object =
761 object_id
762 |> Object.normalize(fetch: false)
763
764 data =
765 if Visibility.is_private?(object) && object.data["actor"] == ap_id do
766 data |> Map.put("object", object |> Map.get(:data) |> prepare_object)
767 else
768 data |> maybe_fix_object_url
769 end
770
771 data =
772 data
773 |> strip_internal_fields
774 |> Map.merge(Utils.make_json_ld_header())
775 |> Map.delete("bcc")
776
777 {:ok, data}
778 end
779
780 # Mastodon Accept/Reject requires a non-normalized object containing the actor URIs,
781 # because of course it does.
782 def prepare_outgoing(%{"type" => "Accept"} = data) do
783 with follow_activity <- Activity.normalize(data["object"]) do
784 object = %{
785 "actor" => follow_activity.actor,
786 "object" => follow_activity.data["object"],
787 "id" => follow_activity.data["id"],
788 "type" => "Follow"
789 }
790
791 data =
792 data
793 |> Map.put("object", object)
794 |> Map.merge(Utils.make_json_ld_header())
795
796 {:ok, data}
797 end
798 end
799
800 def prepare_outgoing(%{"type" => "Reject"} = data) do
801 with follow_activity <- Activity.normalize(data["object"]) do
802 object = %{
803 "actor" => follow_activity.actor,
804 "object" => follow_activity.data["object"],
805 "id" => follow_activity.data["id"],
806 "type" => "Follow"
807 }
808
809 data =
810 data
811 |> Map.put("object", object)
812 |> Map.merge(Utils.make_json_ld_header())
813
814 {:ok, data}
815 end
816 end
817
818 def prepare_outgoing(%{"type" => _type} = data) do
819 data =
820 data
821 |> strip_internal_fields
822 |> maybe_fix_object_url
823 |> Map.merge(Utils.make_json_ld_header())
824
825 {:ok, data}
826 end
827
828 def maybe_fix_object_url(%{"object" => object} = data) when is_binary(object) do
829 with false <- String.starts_with?(object, "http"),
830 {:fetch, {:ok, relative_object}} <- {:fetch, get_obj_helper(object)},
831 %{data: %{"external_url" => external_url}} when not is_nil(external_url) <-
832 relative_object do
833 Map.put(data, "object", external_url)
834 else
835 {:fetch, e} ->
836 Logger.error("Couldn't fetch #{object} #{inspect(e)}")
837 data
838
839 _ ->
840 data
841 end
842 end
843
844 def maybe_fix_object_url(data), do: data
845
846 def add_hashtags(object) do
847 tags =
848 (object["tag"] || [])
849 |> Enum.map(fn
850 # Expand internal representation tags into AS2 tags.
851 tag when is_binary(tag) ->
852 %{
853 "href" => Pleroma.Web.Endpoint.url() <> "/tags/#{tag}",
854 "name" => "##{tag}",
855 "type" => "Hashtag"
856 }
857
858 # Do not process tags which are already AS2 tag objects.
859 tag when is_map(tag) ->
860 tag
861 end)
862
863 Map.put(object, "tag", tags)
864 end
865
866 # TODO These should be added on our side on insertion, it doesn't make much
867 # sense to regenerate these all the time
868 def add_mention_tags(object) do
869 to = object["to"] || []
870 cc = object["cc"] || []
871 mentioned = User.get_users_from_set(to ++ cc, local_only: false)
872
873 mentions = Enum.map(mentioned, &build_mention_tag/1)
874
875 tags = object["tag"] || []
876 Map.put(object, "tag", tags ++ mentions)
877 end
878
879 defp build_mention_tag(%{ap_id: ap_id, nickname: nickname} = _) do
880 %{"type" => "Mention", "href" => ap_id, "name" => "@#{nickname}"}
881 end
882
883 def take_emoji_tags(%User{emoji: emoji}) do
884 emoji
885 |> Map.to_list()
886 |> Enum.map(&build_emoji_tag/1)
887 end
888
889 # TODO: we should probably send mtime instead of unix epoch time for updated
890 def add_emoji_tags(%{"emoji" => emoji} = object) do
891 tags = object["tag"] || []
892
893 out = Enum.map(emoji, &build_emoji_tag/1)
894
895 Map.put(object, "tag", tags ++ out)
896 end
897
898 def add_emoji_tags(object), do: object
899
900 defp build_emoji_tag({name, url}) do
901 %{
902 "icon" => %{"url" => "#{URI.encode(url)}", "type" => "Image"},
903 "name" => ":" <> name <> ":",
904 "type" => "Emoji",
905 "updated" => "1970-01-01T00:00:00Z",
906 "id" => url
907 }
908 end
909
910 def set_conversation(object) do
911 Map.put(object, "conversation", object["context"])
912 end
913
914 def set_type(%{"type" => "Answer"} = object) do
915 Map.put(object, "type", "Note")
916 end
917
918 def set_type(object), do: object
919
920 def add_attributed_to(object) do
921 attributed_to = object["attributedTo"] || object["actor"]
922 Map.put(object, "attributedTo", attributed_to)
923 end
924
925 # TODO: Revisit this
926 def prepare_attachments(%{"type" => "ChatMessage"} = object), do: object
927
928 def prepare_attachments(object) do
929 attachments =
930 object
931 |> Map.get("attachment", [])
932 |> Enum.map(fn data ->
933 [%{"mediaType" => media_type, "href" => href} | _] = data["url"]
934
935 %{
936 "url" => href,
937 "mediaType" => media_type,
938 "name" => data["name"],
939 "type" => "Document"
940 }
941 end)
942
943 Map.put(object, "attachment", attachments)
944 end
945
946 def strip_internal_fields(object) do
947 Map.drop(object, Pleroma.Constants.object_internal_fields())
948 end
949
950 defp strip_internal_tags(%{"tag" => tags} = object) do
951 tags = Enum.filter(tags, fn x -> is_map(x) end)
952
953 Map.put(object, "tag", tags)
954 end
955
956 defp strip_internal_tags(object), do: object
957
958 def perform(:user_upgrade, user) do
959 # we pass a fake user so that the followers collection is stripped away
960 old_follower_address = User.ap_followers(%User{nickname: user.nickname})
961
962 from(
963 a in Activity,
964 where: ^old_follower_address in a.recipients,
965 update: [
966 set: [
967 recipients:
968 fragment(
969 "array_replace(?,?,?)",
970 a.recipients,
971 ^old_follower_address,
972 ^user.follower_address
973 )
974 ]
975 ]
976 )
977 |> Repo.update_all([])
978 end
979
980 def upgrade_user_from_ap_id(ap_id) do
981 with %User{local: false} = user <- User.get_cached_by_ap_id(ap_id),
982 {:ok, data} <- ActivityPub.fetch_and_prepare_user_from_ap_id(ap_id),
983 {:ok, user} <- update_user(user, data) do
984 TransmogrifierWorker.enqueue("user_upgrade", %{"user_id" => user.id})
985 {:ok, user}
986 else
987 %User{} = user -> {:ok, user}
988 e -> e
989 end
990 end
991
992 defp update_user(user, data) do
993 user
994 |> User.remote_user_changeset(data)
995 |> User.update_and_set_cache()
996 end
997
998 def maybe_fix_user_url(%{"url" => url} = data) when is_map(url) do
999 Map.put(data, "url", url["href"])
1000 end
1001
1002 def maybe_fix_user_url(data), do: data
1003
1004 def maybe_fix_user_object(data), do: maybe_fix_user_url(data)
1005 end