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