Transmogrifier: Fix BAD code by RINPATCH
[akkoma] / lib / pleroma / web / activity_pub / transmogrifier.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.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.FollowingRelationship
11 alias Pleroma.Object
12 alias Pleroma.Object.Containment
13 alias Pleroma.Repo
14 alias Pleroma.User
15 alias Pleroma.Web.ActivityPub.ActivityPub
16 alias Pleroma.Web.ActivityPub.ObjectValidator
17 alias Pleroma.Web.ActivityPub.ObjectValidators.LikeValidator
18 alias Pleroma.Web.ActivityPub.Pipeline
19 alias Pleroma.Web.ActivityPub.Utils
20 alias Pleroma.Web.ActivityPub.Visibility
21 alias Pleroma.Web.Federator
22 alias Pleroma.Workers.TransmogrifierWorker
23
24 import Ecto.Query
25
26 require Logger
27 require Pleroma.Constants
28
29 @doc """
30 Modifies an incoming AP object (mastodon format) to our internal format.
31 """
32 def fix_object(object, options \\ []) do
33 object
34 |> strip_internal_fields
35 |> fix_actor
36 |> fix_url
37 |> fix_attachments
38 |> fix_context
39 |> fix_in_reply_to(options)
40 |> fix_emoji
41 |> fix_tag
42 |> fix_content_map
43 |> fix_addressing
44 |> fix_summary
45 |> fix_type(options)
46 end
47
48 def fix_summary(%{"summary" => nil} = object) do
49 Map.put(object, "summary", "")
50 end
51
52 def fix_summary(%{"summary" => _} = object) do
53 # summary is present, nothing to do
54 object
55 end
56
57 def fix_summary(object), do: Map.put(object, "summary", "")
58
59 def fix_addressing_list(map, field) do
60 cond do
61 is_binary(map[field]) ->
62 Map.put(map, field, [map[field]])
63
64 is_nil(map[field]) ->
65 Map.put(map, field, [])
66
67 true ->
68 map
69 end
70 end
71
72 def fix_explicit_addressing(
73 %{"to" => to, "cc" => cc} = object,
74 explicit_mentions,
75 follower_collection
76 ) do
77 explicit_to = Enum.filter(to, fn x -> x in explicit_mentions end)
78
79 explicit_cc = Enum.filter(to, fn x -> x not in explicit_mentions end)
80
81 final_cc =
82 (cc ++ explicit_cc)
83 |> Enum.reject(fn x -> String.ends_with?(x, "/followers") and x != follower_collection end)
84 |> Enum.uniq()
85
86 object
87 |> Map.put("to", explicit_to)
88 |> Map.put("cc", final_cc)
89 end
90
91 def fix_explicit_addressing(object, _explicit_mentions, _followers_collection), do: object
92
93 # if directMessage flag is set to true, leave the addressing alone
94 def fix_explicit_addressing(%{"directMessage" => true} = object), do: object
95
96 def fix_explicit_addressing(object) do
97 explicit_mentions = Utils.determine_explicit_mentions(object)
98
99 %User{follower_address: follower_collection} =
100 object
101 |> Containment.get_actor()
102 |> User.get_cached_by_ap_id()
103
104 explicit_mentions =
105 explicit_mentions ++
106 [
107 Pleroma.Constants.as_public(),
108 follower_collection
109 ]
110
111 fix_explicit_addressing(object, explicit_mentions, follower_collection)
112 end
113
114 # if as:Public is addressed, then make sure the followers collection is also addressed
115 # so that the activities will be delivered to local users.
116 def fix_implicit_addressing(%{"to" => to, "cc" => cc} = object, followers_collection) do
117 recipients = to ++ cc
118
119 if followers_collection not in recipients do
120 cond do
121 Pleroma.Constants.as_public() in cc ->
122 to = to ++ [followers_collection]
123 Map.put(object, "to", to)
124
125 Pleroma.Constants.as_public() in to ->
126 cc = cc ++ [followers_collection]
127 Map.put(object, "cc", cc)
128
129 true ->
130 object
131 end
132 else
133 object
134 end
135 end
136
137 def fix_implicit_addressing(object, _), do: object
138
139 def fix_addressing(object) do
140 {:ok, %User{} = user} = User.get_or_fetch_by_ap_id(object["actor"])
141 followers_collection = User.ap_followers(user)
142
143 object
144 |> fix_addressing_list("to")
145 |> fix_addressing_list("cc")
146 |> fix_addressing_list("bto")
147 |> fix_addressing_list("bcc")
148 |> fix_explicit_addressing()
149 |> fix_implicit_addressing(followers_collection)
150 end
151
152 def fix_actor(%{"attributedTo" => actor} = object) do
153 Map.put(object, "actor", Containment.get_actor(%{"actor" => actor}))
154 end
155
156 def fix_in_reply_to(object, options \\ [])
157
158 def fix_in_reply_to(%{"inReplyTo" => in_reply_to} = object, options)
159 when not is_nil(in_reply_to) do
160 in_reply_to_id = prepare_in_reply_to(in_reply_to)
161 object = Map.put(object, "inReplyToAtomUri", in_reply_to_id)
162 depth = (options[:depth] || 0) + 1
163
164 if Federator.allowed_thread_distance?(depth) do
165 with {:ok, replied_object} <- get_obj_helper(in_reply_to_id, options),
166 %Activity{} <- Activity.get_create_by_object_ap_id(replied_object.data["id"]) do
167 object
168 |> Map.put("inReplyTo", replied_object.data["id"])
169 |> Map.put("inReplyToAtomUri", object["inReplyToAtomUri"] || in_reply_to_id)
170 |> Map.put("conversation", replied_object.data["context"] || object["conversation"])
171 |> Map.put("context", replied_object.data["context"] || object["conversation"])
172 else
173 e ->
174 Logger.error("Couldn't fetch #{inspect(in_reply_to_id)}, error: #{inspect(e)}")
175 object
176 end
177 else
178 object
179 end
180 end
181
182 def fix_in_reply_to(object, _options), do: object
183
184 defp prepare_in_reply_to(in_reply_to) do
185 cond do
186 is_bitstring(in_reply_to) ->
187 in_reply_to
188
189 is_map(in_reply_to) && is_bitstring(in_reply_to["id"]) ->
190 in_reply_to["id"]
191
192 is_list(in_reply_to) && is_bitstring(Enum.at(in_reply_to, 0)) ->
193 Enum.at(in_reply_to, 0)
194
195 true ->
196 ""
197 end
198 end
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 Enum.map(attachment, fn data ->
211 media_type = data["mediaType"] || data["mimeType"]
212 href = data["url"] || data["href"]
213 url = [%{"type" => "Link", "mediaType" => media_type, "href" => href}]
214
215 data
216 |> Map.put("mediaType", media_type)
217 |> Map.put("url", url)
218 end)
219
220 Map.put(object, "attachment", attachments)
221 end
222
223 def fix_attachments(%{"attachment" => attachment} = object) when is_map(attachment) do
224 object
225 |> Map.put("attachment", [attachment])
226 |> fix_attachments()
227 end
228
229 def fix_attachments(object), do: object
230
231 def fix_url(%{"url" => url} = object) when is_map(url) do
232 Map.put(object, "url", url["href"])
233 end
234
235 def fix_url(%{"type" => "Video", "url" => url} = object) when is_list(url) do
236 first_element = Enum.at(url, 0)
237
238 link_element = Enum.find(url, fn x -> is_map(x) and x["mimeType"] == "text/html" end)
239
240 object
241 |> Map.put("attachment", [first_element])
242 |> Map.put("url", link_element["href"])
243 end
244
245 def fix_url(%{"type" => object_type, "url" => url} = object)
246 when object_type != "Video" and is_list(url) do
247 first_element = Enum.at(url, 0)
248
249 url_string =
250 cond do
251 is_bitstring(first_element) -> first_element
252 is_map(first_element) -> first_element["href"] || ""
253 true -> ""
254 end
255
256 Map.put(object, "url", url_string)
257 end
258
259 def fix_url(object), do: object
260
261 def fix_emoji(%{"tag" => tags} = object) when is_list(tags) do
262 emoji =
263 tags
264 |> Enum.filter(fn data -> data["type"] == "Emoji" and data["icon"] end)
265 |> Enum.reduce(%{}, fn data, mapping ->
266 name = String.trim(data["name"], ":")
267
268 Map.put(mapping, name, data["icon"]["url"])
269 end)
270
271 # we merge mastodon and pleroma emoji into a single mapping, to allow for both wire formats
272 emoji = Map.merge(object["emoji"] || %{}, emoji)
273
274 Map.put(object, "emoji", emoji)
275 end
276
277 def fix_emoji(%{"tag" => %{"type" => "Emoji"} = tag} = object) do
278 name = String.trim(tag["name"], ":")
279 emoji = %{name => tag["icon"]["url"]}
280
281 Map.put(object, "emoji", emoji)
282 end
283
284 def fix_emoji(object), do: object
285
286 def fix_tag(%{"tag" => tag} = object) when is_list(tag) do
287 tags =
288 tag
289 |> Enum.filter(fn data -> data["type"] == "Hashtag" and data["name"] end)
290 |> Enum.map(fn data -> String.slice(data["name"], 1..-1) end)
291
292 Map.put(object, "tag", tag ++ tags)
293 end
294
295 def fix_tag(%{"tag" => %{"type" => "Hashtag", "name" => hashtag} = tag} = object) do
296 combined = [tag, String.slice(hashtag, 1..-1)]
297
298 Map.put(object, "tag", combined)
299 end
300
301 def fix_tag(%{"tag" => %{} = tag} = object), do: Map.put(object, "tag", [tag])
302
303 def fix_tag(object), do: object
304
305 # content map usually only has one language so this will do for now.
306 def fix_content_map(%{"contentMap" => content_map} = object) do
307 content_groups = Map.to_list(content_map)
308 {_, content} = Enum.at(content_groups, 0)
309
310 Map.put(object, "content", content)
311 end
312
313 def fix_content_map(object), do: object
314
315 def fix_type(object, options \\ [])
316
317 def fix_type(%{"inReplyTo" => reply_id, "name" => _} = object, options)
318 when is_binary(reply_id) do
319 with true <- Federator.allowed_thread_distance?(options[:depth]),
320 {:ok, %{data: %{"type" => "Question"} = _} = _} <- get_obj_helper(reply_id, options) do
321 Map.put(object, "type", "Answer")
322 else
323 _ -> object
324 end
325 end
326
327 def fix_type(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 # Reduce the object list to find the reported user.
356 defp get_reported(objects) do
357 Enum.reduce_while(objects, nil, fn ap_id, _ ->
358 with %User{} = user <- User.get_cached_by_ap_id(ap_id) do
359 {:halt, user}
360 else
361 _ -> {:cont, nil}
362 end
363 end)
364 end
365
366 def handle_incoming(data, options \\ [])
367
368 # Flag objects are placed ahead of the ID check because Mastodon 2.8 and earlier send them
369 # with nil ID.
370 def handle_incoming(%{"type" => "Flag", "object" => objects, "actor" => actor} = data, _options) do
371 with context <- data["context"] || Utils.generate_context_id(),
372 content <- data["content"] || "",
373 %User{} = actor <- User.get_cached_by_ap_id(actor),
374 # Reduce the object list to find the reported user.
375 %User{} = account <- get_reported(objects),
376 # Remove the reported user from the object list.
377 statuses <- Enum.filter(objects, fn ap_id -> ap_id != account.ap_id end) do
378 %{
379 actor: actor,
380 context: context,
381 account: account,
382 statuses: statuses,
383 content: content,
384 additional: %{"cc" => [account.ap_id]}
385 }
386 |> ActivityPub.flag()
387 end
388 end
389
390 # disallow objects with bogus IDs
391 def handle_incoming(%{"id" => nil}, _options), do: :error
392 def handle_incoming(%{"id" => ""}, _options), do: :error
393 # length of https:// = 8, should validate better, but good enough for now.
394 def handle_incoming(%{"id" => id}, _options) when is_binary(id) and byte_size(id) < 8,
395 do: :error
396
397 # TODO: validate those with a Ecto scheme
398 # - tags
399 # - emoji
400 def handle_incoming(
401 %{"type" => "Create", "object" => %{"type" => objtype} = object} = data,
402 options
403 )
404 when objtype in ["Article", "Event", "Note", "Video", "Page", "Question", "Answer"] do
405 actor = Containment.get_actor(data)
406
407 data =
408 Map.put(data, "actor", actor)
409 |> fix_addressing
410
411 with nil <- Activity.get_create_by_object_ap_id(object["id"]),
412 {:ok, %User{} = user} <- User.get_or_fetch_by_ap_id(data["actor"]) do
413 object = fix_object(object, options)
414
415 params = %{
416 to: data["to"],
417 object: object,
418 actor: user,
419 context: object["conversation"],
420 local: false,
421 published: data["published"],
422 additional:
423 Map.take(data, [
424 "cc",
425 "directMessage",
426 "id"
427 ])
428 }
429
430 with {:ok, created_activity} <- ActivityPub.create(params) do
431 reply_depth = (options[:depth] || 0) + 1
432
433 if Federator.allowed_thread_distance?(reply_depth) do
434 for reply_id <- replies(object) do
435 Pleroma.Workers.RemoteFetcherWorker.enqueue("fetch_remote", %{
436 "id" => reply_id,
437 "depth" => reply_depth
438 })
439 end
440 end
441
442 {:ok, created_activity}
443 end
444 else
445 %Activity{} = activity -> {:ok, activity}
446 _e -> :error
447 end
448 end
449
450 def handle_incoming(
451 %{"type" => "Listen", "object" => %{"type" => "Audio"} = object} = data,
452 options
453 ) do
454 actor = Containment.get_actor(data)
455
456 data =
457 Map.put(data, "actor", actor)
458 |> fix_addressing
459
460 with {:ok, %User{} = user} <- User.get_or_fetch_by_ap_id(data["actor"]) do
461 reply_depth = (options[:depth] || 0) + 1
462 options = Keyword.put(options, :depth, reply_depth)
463 object = fix_object(object, options)
464
465 params = %{
466 to: data["to"],
467 object: object,
468 actor: user,
469 context: nil,
470 local: false,
471 published: data["published"],
472 additional: Map.take(data, ["cc", "id"])
473 }
474
475 ActivityPub.listen(params)
476 else
477 _e -> :error
478 end
479 end
480
481 def handle_incoming(
482 %{"type" => "Follow", "object" => followed, "actor" => follower, "id" => id} = data,
483 _options
484 ) do
485 with %User{local: true} = followed <-
486 User.get_cached_by_ap_id(Containment.get_actor(%{"actor" => followed})),
487 {:ok, %User{} = follower} <-
488 User.get_or_fetch_by_ap_id(Containment.get_actor(%{"actor" => follower})),
489 {:ok, activity} <- ActivityPub.follow(follower, followed, id, false) do
490 with deny_follow_blocked <- Pleroma.Config.get([:user, :deny_follow_blocked]),
491 {_, false} <- {:user_blocked, User.blocks?(followed, follower) && deny_follow_blocked},
492 {_, false} <- {:user_locked, User.locked?(followed)},
493 {_, {:ok, follower}} <- {:follow, User.follow(follower, followed)},
494 {_, {:ok, _}} <-
495 {:follow_state_update, Utils.update_follow_state_for_all(activity, "accept")},
496 {:ok, _relationship} <- FollowingRelationship.update(follower, followed, "accept") do
497 ActivityPub.accept(%{
498 to: [follower.ap_id],
499 actor: followed,
500 object: data,
501 local: true
502 })
503 else
504 {:user_blocked, true} ->
505 {:ok, _} = Utils.update_follow_state_for_all(activity, "reject")
506 {:ok, _relationship} = FollowingRelationship.update(follower, followed, "reject")
507
508 ActivityPub.reject(%{
509 to: [follower.ap_id],
510 actor: followed,
511 object: data,
512 local: true
513 })
514
515 {:follow, {:error, _}} ->
516 {:ok, _} = Utils.update_follow_state_for_all(activity, "reject")
517 {:ok, _relationship} = FollowingRelationship.update(follower, followed, "reject")
518
519 ActivityPub.reject(%{
520 to: [follower.ap_id],
521 actor: followed,
522 object: data,
523 local: true
524 })
525
526 {:user_locked, true} ->
527 {:ok, _relationship} = FollowingRelationship.update(follower, followed, "pending")
528 :noop
529 end
530
531 {:ok, activity}
532 else
533 _e ->
534 :error
535 end
536 end
537
538 def handle_incoming(
539 %{"type" => "Accept", "object" => follow_object, "actor" => _actor, "id" => id} = data,
540 _options
541 ) do
542 with actor <- Containment.get_actor(data),
543 {:ok, %User{} = followed} <- User.get_or_fetch_by_ap_id(actor),
544 {:ok, follow_activity} <- get_follow_activity(follow_object, followed),
545 {:ok, follow_activity} <- Utils.update_follow_state_for_all(follow_activity, "accept"),
546 %User{local: true} = follower <- User.get_cached_by_ap_id(follow_activity.data["actor"]),
547 {:ok, _relationship} <- FollowingRelationship.update(follower, followed, "accept") do
548 ActivityPub.accept(%{
549 to: follow_activity.data["to"],
550 type: "Accept",
551 actor: followed,
552 object: follow_activity.data["id"],
553 local: false,
554 activity_id: id
555 })
556 else
557 _e -> :error
558 end
559 end
560
561 def handle_incoming(
562 %{"type" => "Reject", "object" => follow_object, "actor" => _actor, "id" => id} = data,
563 _options
564 ) do
565 with actor <- Containment.get_actor(data),
566 {:ok, %User{} = followed} <- User.get_or_fetch_by_ap_id(actor),
567 {:ok, follow_activity} <- get_follow_activity(follow_object, followed),
568 {:ok, follow_activity} <- Utils.update_follow_state_for_all(follow_activity, "reject"),
569 %User{local: true} = follower <- User.get_cached_by_ap_id(follow_activity.data["actor"]),
570 {:ok, _relationship} <- FollowingRelationship.update(follower, followed, "reject"),
571 {:ok, activity} <-
572 ActivityPub.reject(%{
573 to: follow_activity.data["to"],
574 type: "Reject",
575 actor: followed,
576 object: follow_activity.data["id"],
577 local: false,
578 activity_id: id
579 }) do
580 {:ok, activity}
581 else
582 _e -> :error
583 end
584 end
585
586 @misskey_reactions %{
587 "like" => "👍",
588 "love" => "❤️",
589 "laugh" => "😆",
590 "hmm" => "🤔",
591 "surprise" => "😮",
592 "congrats" => "🎉",
593 "angry" => "💢",
594 "confused" => "😥",
595 "rip" => "😇",
596 "pudding" => "🍮",
597 "star" => "⭐"
598 }
599
600 @doc "Rewrite misskey likes into EmojiReacts"
601 def handle_incoming(
602 %{
603 "type" => "Like",
604 "_misskey_reaction" => reaction
605 } = data,
606 options
607 ) do
608 data
609 |> Map.put("type", "EmojiReact")
610 |> Map.put("content", @misskey_reactions[reaction] || reaction)
611 |> handle_incoming(options)
612 end
613
614 def handle_incoming(%{"type" => "Like"} = data, _options) do
615 with {_, {:ok, cast_data_sym}} <-
616 {:casting_data,
617 data |> LikeValidator.cast_data() |> Ecto.Changeset.apply_action(:insert)},
618 cast_data = ObjectValidator.stringify_keys(Map.from_struct(cast_data_sym)),
619 :ok <- ObjectValidator.fetch_actor_and_object(cast_data),
620 {_, {:ok, cast_data}} <- {:maybe_add_context, maybe_add_context_from_object(cast_data)},
621 {_, {:ok, cast_data}} <-
622 {:maybe_add_recipients, maybe_add_recipients_from_object(cast_data)},
623 {_, {:ok, activity, _meta}} <-
624 {:common_pipeline, Pipeline.common_pipeline(cast_data, local: false)} do
625 {:ok, activity}
626 else
627 e -> {:error, e}
628 end
629 end
630
631 def handle_incoming(
632 %{
633 "type" => "EmojiReact",
634 "object" => object_id,
635 "actor" => _actor,
636 "id" => id,
637 "content" => emoji
638 } = data,
639 _options
640 ) do
641 with actor <- Containment.get_actor(data),
642 {:ok, %User{} = actor} <- User.get_or_fetch_by_ap_id(actor),
643 {:ok, object} <- get_obj_helper(object_id),
644 {:ok, activity, _object} <-
645 ActivityPub.react_with_emoji(actor, object, emoji, activity_id: id, local: false) do
646 {:ok, activity}
647 else
648 _e -> :error
649 end
650 end
651
652 def handle_incoming(
653 %{"type" => "Announce", "object" => object_id, "actor" => _actor, "id" => id} = data,
654 _options
655 ) do
656 with actor <- Containment.get_actor(data),
657 {:ok, %User{} = actor} <- User.get_or_fetch_by_ap_id(actor),
658 {:ok, object} <- get_embedded_obj_helper(object_id, actor),
659 public <- Visibility.is_public?(data),
660 {:ok, activity, _object} <- ActivityPub.announce(actor, object, id, false, public) do
661 {:ok, activity}
662 else
663 _e -> :error
664 end
665 end
666
667 def handle_incoming(
668 %{"type" => "Update", "object" => %{"type" => object_type} = object, "actor" => actor_id} =
669 data,
670 _options
671 )
672 when object_type in [
673 "Person",
674 "Application",
675 "Service",
676 "Organization"
677 ] do
678 with %User{ap_id: ^actor_id} = actor <- User.get_cached_by_ap_id(object["id"]) do
679 {:ok, new_user_data} = ActivityPub.user_data_from_user_object(object)
680
681 actor
682 |> User.upgrade_changeset(new_user_data, true)
683 |> User.update_and_set_cache()
684
685 ActivityPub.update(%{
686 local: false,
687 to: data["to"] || [],
688 cc: data["cc"] || [],
689 object: object,
690 actor: actor_id,
691 activity_id: data["id"]
692 })
693 else
694 e ->
695 Logger.error(e)
696 :error
697 end
698 end
699
700 # TODO: We presently assume that any actor on the same origin domain as the object being
701 # deleted has the rights to delete that object. A better way to validate whether or not
702 # the object should be deleted is to refetch the object URI, which should return either
703 # an error or a tombstone. This would allow us to verify that a deletion actually took
704 # place.
705 def handle_incoming(
706 %{"type" => "Delete", "object" => object_id, "actor" => actor, "id" => id} = data,
707 _options
708 ) do
709 object_id = Utils.get_ap_id(object_id)
710
711 with actor <- Containment.get_actor(data),
712 {:ok, %User{} = actor} <- User.get_or_fetch_by_ap_id(actor),
713 {:ok, object} <- get_obj_helper(object_id),
714 :ok <- Containment.contain_origin(actor.ap_id, object.data),
715 {:ok, activity} <-
716 ActivityPub.delete(object, local: false, activity_id: id, actor: actor.ap_id) do
717 {:ok, activity}
718 else
719 nil ->
720 case User.get_cached_by_ap_id(object_id) do
721 %User{ap_id: ^actor} = user ->
722 User.delete(user)
723
724 nil ->
725 :error
726 end
727
728 _e ->
729 :error
730 end
731 end
732
733 def handle_incoming(
734 %{
735 "type" => "Undo",
736 "object" => %{"type" => "Announce", "object" => object_id},
737 "actor" => _actor,
738 "id" => id
739 } = data,
740 _options
741 ) do
742 with actor <- Containment.get_actor(data),
743 {:ok, %User{} = actor} <- User.get_or_fetch_by_ap_id(actor),
744 {:ok, object} <- get_obj_helper(object_id),
745 {:ok, activity, _} <- ActivityPub.unannounce(actor, object, id, false) do
746 {:ok, activity}
747 else
748 _e -> :error
749 end
750 end
751
752 def handle_incoming(
753 %{
754 "type" => "Undo",
755 "object" => %{"type" => "Follow", "object" => followed},
756 "actor" => follower,
757 "id" => id
758 } = _data,
759 _options
760 ) do
761 with %User{local: true} = followed <- User.get_cached_by_ap_id(followed),
762 {:ok, %User{} = follower} <- User.get_or_fetch_by_ap_id(follower),
763 {:ok, activity} <- ActivityPub.unfollow(follower, followed, id, false) do
764 User.unfollow(follower, followed)
765 {:ok, activity}
766 else
767 _e -> :error
768 end
769 end
770
771 def handle_incoming(
772 %{
773 "type" => "Undo",
774 "object" => %{"type" => "EmojiReact", "id" => reaction_activity_id},
775 "actor" => _actor,
776 "id" => id
777 } = data,
778 _options
779 ) do
780 with actor <- Containment.get_actor(data),
781 {:ok, %User{} = actor} <- User.get_or_fetch_by_ap_id(actor),
782 {:ok, activity, _} <-
783 ActivityPub.unreact_with_emoji(actor, reaction_activity_id,
784 activity_id: id,
785 local: false
786 ) do
787 {:ok, activity}
788 else
789 _e -> :error
790 end
791 end
792
793 def handle_incoming(
794 %{
795 "type" => "Undo",
796 "object" => %{"type" => "Block", "object" => blocked},
797 "actor" => blocker,
798 "id" => id
799 } = _data,
800 _options
801 ) do
802 with %User{local: true} = blocked <- User.get_cached_by_ap_id(blocked),
803 {:ok, %User{} = blocker} <- User.get_or_fetch_by_ap_id(blocker),
804 {:ok, activity} <- ActivityPub.unblock(blocker, blocked, id, false) do
805 User.unblock(blocker, blocked)
806 {:ok, activity}
807 else
808 _e -> :error
809 end
810 end
811
812 def handle_incoming(
813 %{"type" => "Block", "object" => blocked, "actor" => blocker, "id" => id} = _data,
814 _options
815 ) do
816 with %User{local: true} = blocked = User.get_cached_by_ap_id(blocked),
817 {:ok, %User{} = blocker} = User.get_or_fetch_by_ap_id(blocker),
818 {:ok, activity} <- ActivityPub.block(blocker, blocked, id, false) do
819 User.unfollow(blocker, blocked)
820 User.block(blocker, blocked)
821 {:ok, activity}
822 else
823 _e -> :error
824 end
825 end
826
827 def handle_incoming(
828 %{
829 "type" => "Undo",
830 "object" => %{"type" => "Like", "object" => object_id},
831 "actor" => _actor,
832 "id" => id
833 } = data,
834 _options
835 ) do
836 with actor <- Containment.get_actor(data),
837 {:ok, %User{} = actor} <- User.get_or_fetch_by_ap_id(actor),
838 {:ok, object} <- get_obj_helper(object_id),
839 {:ok, activity, _, _} <- ActivityPub.unlike(actor, object, id, false) do
840 {:ok, activity}
841 else
842 _e -> :error
843 end
844 end
845
846 # For Undos that don't have the complete object attached, try to find it in our database.
847 def handle_incoming(
848 %{
849 "type" => "Undo",
850 "object" => object
851 } = activity,
852 options
853 )
854 when is_binary(object) do
855 with %Activity{data: data} <- Activity.get_by_ap_id(object) do
856 activity
857 |> Map.put("object", data)
858 |> handle_incoming(options)
859 else
860 _e -> :error
861 end
862 end
863
864 def handle_incoming(
865 %{
866 "type" => "Move",
867 "actor" => origin_actor,
868 "object" => origin_actor,
869 "target" => target_actor
870 },
871 _options
872 ) do
873 with %User{} = origin_user <- User.get_cached_by_ap_id(origin_actor),
874 {:ok, %User{} = target_user} <- User.get_or_fetch_by_ap_id(target_actor),
875 true <- origin_actor in target_user.also_known_as do
876 ActivityPub.move(origin_user, target_user, false)
877 else
878 _e -> :error
879 end
880 end
881
882 def handle_incoming(_, _), do: :error
883
884 @spec get_obj_helper(String.t(), Keyword.t()) :: {:ok, Object.t()} | nil
885 def get_obj_helper(id, options \\ []) do
886 case Object.normalize(id, true, options) do
887 %Object{} = object -> {:ok, object}
888 _ -> nil
889 end
890 end
891
892 @spec get_embedded_obj_helper(String.t() | Object.t(), User.t()) :: {:ok, Object.t()} | nil
893 def get_embedded_obj_helper(%{"attributedTo" => attributed_to, "id" => object_id} = data, %User{
894 ap_id: ap_id
895 })
896 when attributed_to == ap_id do
897 with {:ok, activity} <-
898 handle_incoming(%{
899 "type" => "Create",
900 "to" => data["to"],
901 "cc" => data["cc"],
902 "actor" => attributed_to,
903 "object" => data
904 }) do
905 {:ok, Object.normalize(activity)}
906 else
907 _ -> get_obj_helper(object_id)
908 end
909 end
910
911 def get_embedded_obj_helper(object_id, _) do
912 get_obj_helper(object_id)
913 end
914
915 def set_reply_to_uri(%{"inReplyTo" => in_reply_to} = object) when is_binary(in_reply_to) do
916 with false <- String.starts_with?(in_reply_to, "http"),
917 {:ok, %{data: replied_to_object}} <- get_obj_helper(in_reply_to) do
918 Map.put(object, "inReplyTo", replied_to_object["external_url"] || in_reply_to)
919 else
920 _e -> object
921 end
922 end
923
924 def set_reply_to_uri(obj), do: obj
925
926 @doc """
927 Serialized Mastodon-compatible `replies` collection containing _self-replies_.
928 Based on Mastodon's ActivityPub::NoteSerializer#replies.
929 """
930 def set_replies(obj_data) do
931 replies_uris =
932 with limit when limit > 0 <-
933 Pleroma.Config.get([:activitypub, :note_replies_output_limit], 0),
934 %Object{} = object <- Object.get_cached_by_ap_id(obj_data["id"]) do
935 object
936 |> Object.self_replies()
937 |> select([o], fragment("?->>'id'", o.data))
938 |> limit(^limit)
939 |> Repo.all()
940 else
941 _ -> []
942 end
943
944 set_replies(obj_data, replies_uris)
945 end
946
947 defp set_replies(obj, []) do
948 obj
949 end
950
951 defp set_replies(obj, replies_uris) do
952 replies_collection = %{
953 "type" => "Collection",
954 "items" => replies_uris
955 }
956
957 Map.merge(obj, %{"replies" => replies_collection})
958 end
959
960 def replies(%{"replies" => %{"first" => %{"items" => items}}}) when not is_nil(items) do
961 items
962 end
963
964 def replies(%{"replies" => %{"items" => items}}) when not is_nil(items) do
965 items
966 end
967
968 def replies(_), do: []
969
970 # Prepares the object of an outgoing create activity.
971 def prepare_object(object) do
972 object
973 |> set_sensitive
974 |> add_hashtags
975 |> add_mention_tags
976 |> add_emoji_tags
977 |> add_attributed_to
978 |> prepare_attachments
979 |> set_conversation
980 |> set_reply_to_uri
981 |> set_replies
982 |> strip_internal_fields
983 |> strip_internal_tags
984 |> set_type
985 end
986
987 # @doc
988 # """
989 # internal -> Mastodon
990 # """
991
992 def prepare_outgoing(%{"type" => activity_type, "object" => object_id} = data)
993 when activity_type in ["Create", "Listen"] do
994 object =
995 object_id
996 |> Object.normalize()
997 |> Map.get(:data)
998 |> prepare_object
999
1000 data =
1001 data
1002 |> Map.put("object", object)
1003 |> Map.merge(Utils.make_json_ld_header())
1004 |> Map.delete("bcc")
1005
1006 {:ok, data}
1007 end
1008
1009 def prepare_outgoing(%{"type" => "Announce", "actor" => ap_id, "object" => object_id} = data) do
1010 object =
1011 object_id
1012 |> Object.normalize()
1013
1014 data =
1015 if Visibility.is_private?(object) && object.data["actor"] == ap_id do
1016 data |> Map.put("object", object |> Map.get(:data) |> prepare_object)
1017 else
1018 data |> maybe_fix_object_url
1019 end
1020
1021 data =
1022 data
1023 |> strip_internal_fields
1024 |> Map.merge(Utils.make_json_ld_header())
1025 |> Map.delete("bcc")
1026
1027 {:ok, data}
1028 end
1029
1030 # Mastodon Accept/Reject requires a non-normalized object containing the actor URIs,
1031 # because of course it does.
1032 def prepare_outgoing(%{"type" => "Accept"} = data) do
1033 with follow_activity <- Activity.normalize(data["object"]) do
1034 object = %{
1035 "actor" => follow_activity.actor,
1036 "object" => follow_activity.data["object"],
1037 "id" => follow_activity.data["id"],
1038 "type" => "Follow"
1039 }
1040
1041 data =
1042 data
1043 |> Map.put("object", object)
1044 |> Map.merge(Utils.make_json_ld_header())
1045
1046 {:ok, data}
1047 end
1048 end
1049
1050 def prepare_outgoing(%{"type" => "Reject"} = data) do
1051 with follow_activity <- Activity.normalize(data["object"]) do
1052 object = %{
1053 "actor" => follow_activity.actor,
1054 "object" => follow_activity.data["object"],
1055 "id" => follow_activity.data["id"],
1056 "type" => "Follow"
1057 }
1058
1059 data =
1060 data
1061 |> Map.put("object", object)
1062 |> Map.merge(Utils.make_json_ld_header())
1063
1064 {:ok, data}
1065 end
1066 end
1067
1068 def prepare_outgoing(%{"type" => _type} = data) do
1069 data =
1070 data
1071 |> strip_internal_fields
1072 |> maybe_fix_object_url
1073 |> Map.merge(Utils.make_json_ld_header())
1074
1075 {:ok, data}
1076 end
1077
1078 def maybe_fix_object_url(%{"object" => object} = data) when is_binary(object) do
1079 with false <- String.starts_with?(object, "http"),
1080 {:fetch, {:ok, relative_object}} <- {:fetch, get_obj_helper(object)},
1081 %{data: %{"external_url" => external_url}} when not is_nil(external_url) <-
1082 relative_object do
1083 Map.put(data, "object", external_url)
1084 else
1085 {:fetch, e} ->
1086 Logger.error("Couldn't fetch #{object} #{inspect(e)}")
1087 data
1088
1089 _ ->
1090 data
1091 end
1092 end
1093
1094 def maybe_fix_object_url(data), do: data
1095
1096 def add_hashtags(object) do
1097 tags =
1098 (object["tag"] || [])
1099 |> Enum.map(fn
1100 # Expand internal representation tags into AS2 tags.
1101 tag when is_binary(tag) ->
1102 %{
1103 "href" => Pleroma.Web.Endpoint.url() <> "/tags/#{tag}",
1104 "name" => "##{tag}",
1105 "type" => "Hashtag"
1106 }
1107
1108 # Do not process tags which are already AS2 tag objects.
1109 tag when is_map(tag) ->
1110 tag
1111 end)
1112
1113 Map.put(object, "tag", tags)
1114 end
1115
1116 def add_mention_tags(object) do
1117 mentions =
1118 object
1119 |> Utils.get_notified_from_object()
1120 |> Enum.map(&build_mention_tag/1)
1121
1122 tags = object["tag"] || []
1123
1124 Map.put(object, "tag", tags ++ mentions)
1125 end
1126
1127 defp build_mention_tag(%{ap_id: ap_id, nickname: nickname} = _) do
1128 %{"type" => "Mention", "href" => ap_id, "name" => "@#{nickname}"}
1129 end
1130
1131 def take_emoji_tags(%User{emoji: emoji}) do
1132 emoji
1133 |> Enum.flat_map(&Map.to_list/1)
1134 |> Enum.map(&build_emoji_tag/1)
1135 end
1136
1137 # TODO: we should probably send mtime instead of unix epoch time for updated
1138 def add_emoji_tags(%{"emoji" => emoji} = object) do
1139 tags = object["tag"] || []
1140
1141 out = Enum.map(emoji, &build_emoji_tag/1)
1142
1143 Map.put(object, "tag", tags ++ out)
1144 end
1145
1146 def add_emoji_tags(object), do: object
1147
1148 defp build_emoji_tag({name, url}) do
1149 %{
1150 "icon" => %{"url" => url, "type" => "Image"},
1151 "name" => ":" <> name <> ":",
1152 "type" => "Emoji",
1153 "updated" => "1970-01-01T00:00:00Z",
1154 "id" => url
1155 }
1156 end
1157
1158 def set_conversation(object) do
1159 Map.put(object, "conversation", object["context"])
1160 end
1161
1162 def set_sensitive(object) do
1163 tags = object["tag"] || []
1164 Map.put(object, "sensitive", "nsfw" in tags)
1165 end
1166
1167 def set_type(%{"type" => "Answer"} = object) do
1168 Map.put(object, "type", "Note")
1169 end
1170
1171 def set_type(object), do: object
1172
1173 def add_attributed_to(object) do
1174 attributed_to = object["attributedTo"] || object["actor"]
1175 Map.put(object, "attributedTo", attributed_to)
1176 end
1177
1178 def prepare_attachments(object) do
1179 attachments =
1180 (object["attachment"] || [])
1181 |> Enum.map(fn data ->
1182 [%{"mediaType" => media_type, "href" => href} | _] = data["url"]
1183 %{"url" => href, "mediaType" => media_type, "name" => data["name"], "type" => "Document"}
1184 end)
1185
1186 Map.put(object, "attachment", attachments)
1187 end
1188
1189 def strip_internal_fields(object) do
1190 object
1191 |> Map.drop(Pleroma.Constants.object_internal_fields())
1192 end
1193
1194 defp strip_internal_tags(%{"tag" => tags} = object) do
1195 tags = Enum.filter(tags, fn x -> is_map(x) end)
1196
1197 Map.put(object, "tag", tags)
1198 end
1199
1200 defp strip_internal_tags(object), do: object
1201
1202 def perform(:user_upgrade, user) do
1203 # we pass a fake user so that the followers collection is stripped away
1204 old_follower_address = User.ap_followers(%User{nickname: user.nickname})
1205
1206 from(
1207 a in Activity,
1208 where: ^old_follower_address in a.recipients,
1209 update: [
1210 set: [
1211 recipients:
1212 fragment(
1213 "array_replace(?,?,?)",
1214 a.recipients,
1215 ^old_follower_address,
1216 ^user.follower_address
1217 )
1218 ]
1219 ]
1220 )
1221 |> Repo.update_all([])
1222 end
1223
1224 def upgrade_user_from_ap_id(ap_id) do
1225 with %User{local: false} = user <- User.get_cached_by_ap_id(ap_id),
1226 {:ok, data} <- ActivityPub.fetch_and_prepare_user_from_ap_id(ap_id),
1227 already_ap <- User.ap_enabled?(user),
1228 {:ok, user} <- upgrade_user(user, data) do
1229 if not already_ap do
1230 TransmogrifierWorker.enqueue("user_upgrade", %{"user_id" => user.id})
1231 end
1232
1233 {:ok, user}
1234 else
1235 %User{} = user -> {:ok, user}
1236 e -> e
1237 end
1238 end
1239
1240 defp upgrade_user(user, data) do
1241 user
1242 |> User.upgrade_changeset(data, true)
1243 |> User.update_and_set_cache()
1244 end
1245
1246 def maybe_fix_user_url(%{"url" => url} = data) when is_map(url) do
1247 Map.put(data, "url", url["href"])
1248 end
1249
1250 def maybe_fix_user_url(data), do: data
1251
1252 def maybe_fix_user_object(data), do: maybe_fix_user_url(data)
1253
1254 defp maybe_add_context_from_object(%{"context" => context} = data) when is_binary(context),
1255 do: {:ok, data}
1256
1257 defp maybe_add_context_from_object(%{"object" => object} = data) when is_binary(object) do
1258 with %{data: %{"context" => context}} when is_binary(context) <- Object.normalize(object) do
1259 {:ok, Map.put(data, "context", context)}
1260 else
1261 _ ->
1262 {:error, :no_context}
1263 end
1264 end
1265
1266 defp maybe_add_context_from_object(_) do
1267 {:error, :no_context}
1268 end
1269
1270 defp maybe_add_recipients_from_object(%{"to" => [_ | _], "cc" => [_ | _]} = data),
1271 do: {:ok, data}
1272
1273 defp maybe_add_recipients_from_object(%{"object" => object} = data) do
1274 case Object.normalize(object) do
1275 %{data: %{"actor" => actor}} ->
1276 data =
1277 data
1278 |> Map.put("to", [actor])
1279 |> Map.put("cc", data["cc"] || [])
1280
1281 {:ok, data}
1282
1283 nil ->
1284 {:error, :no_object}
1285
1286 _ ->
1287 {:error, :no_actor}
1288 end
1289 end
1290
1291 defp maybe_add_recipients_from_object(_) do
1292 {:error, :no_object}
1293 end
1294 end