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