Merge branch 'feature/suggestions-api-with-third-party-recommendation-engine' into...
[akkoma] / lib / pleroma / web / activity_pub / transmogrifier.ex
1 defmodule Pleroma.Web.ActivityPub.Transmogrifier do
2 @moduledoc """
3 A module to handle coding from internal to wire ActivityPub and back.
4 """
5 alias Pleroma.User
6 alias Pleroma.Object
7 alias Pleroma.Activity
8 alias Pleroma.Repo
9 alias Pleroma.Web.ActivityPub.ActivityPub
10 alias Pleroma.Web.ActivityPub.Utils
11
12 import Ecto.Query
13
14 require Logger
15
16 def get_actor(%{"actor" => actor}) when is_binary(actor) do
17 actor
18 end
19
20 def get_actor(%{"actor" => actor}) when is_list(actor) do
21 Enum.at(actor, 0)
22 end
23
24 def get_actor(%{"actor" => actor_list}) do
25 Enum.find(actor_list, fn %{"type" => type} -> type == "Person" end)
26 |> Map.get("id")
27 end
28
29 @doc """
30 Modifies an incoming AP object (mastodon format) to our internal format.
31 """
32 def fix_object(object) do
33 object
34 |> fix_actor
35 |> fix_attachments
36 |> fix_context
37 |> fix_in_reply_to
38 |> fix_emoji
39 |> fix_tag
40 |> fix_content_map
41 end
42
43 def fix_actor(%{"attributedTo" => actor} = object) do
44 object
45 |> Map.put("actor", get_actor(%{"actor" => actor}))
46 end
47
48 def fix_in_reply_to(%{"inReplyTo" => in_reply_to_id} = object)
49 when not is_nil(in_reply_to_id) do
50 case ActivityPub.fetch_object_from_id(in_reply_to_id) do
51 {:ok, replied_object} ->
52 with %Activity{} = activity <-
53 Activity.get_create_activity_by_object_ap_id(replied_object.data["id"]) do
54 object
55 |> Map.put("inReplyTo", replied_object.data["id"])
56 |> Map.put("inReplyToAtomUri", object["inReplyToAtomUri"] || in_reply_to_id)
57 |> Map.put("inReplyToStatusId", activity.id)
58 |> Map.put("conversation", replied_object.data["context"] || object["conversation"])
59 |> Map.put("context", replied_object.data["context"] || object["conversation"])
60 else
61 e ->
62 Logger.error("Couldn't fetch #{object["inReplyTo"]} #{inspect(e)}")
63 object
64 end
65
66 e ->
67 Logger.error("Couldn't fetch #{object["inReplyTo"]} #{inspect(e)}")
68 object
69 end
70 end
71
72 def fix_in_reply_to(object), do: object
73
74 def fix_context(object) do
75 object
76 |> Map.put("context", object["conversation"])
77 end
78
79 def fix_attachments(object) do
80 attachments =
81 (object["attachment"] || [])
82 |> Enum.map(fn data ->
83 url = [%{"type" => "Link", "mediaType" => data["mediaType"], "href" => data["url"]}]
84 Map.put(data, "url", url)
85 end)
86
87 object
88 |> Map.put("attachment", attachments)
89 end
90
91 def fix_emoji(object) do
92 tags = object["tag"] || []
93 emoji = tags |> Enum.filter(fn data -> data["type"] == "Emoji" and data["icon"] end)
94
95 emoji =
96 emoji
97 |> Enum.reduce(%{}, fn data, mapping ->
98 name = data["name"]
99
100 name =
101 if String.starts_with?(name, ":") do
102 name |> String.slice(1..-2)
103 else
104 name
105 end
106
107 mapping |> Map.put(name, data["icon"]["url"])
108 end)
109
110 # we merge mastodon and pleroma emoji into a single mapping, to allow for both wire formats
111 emoji = Map.merge(object["emoji"] || %{}, emoji)
112
113 object
114 |> Map.put("emoji", emoji)
115 end
116
117 def fix_tag(object) do
118 tags =
119 (object["tag"] || [])
120 |> Enum.filter(fn data -> data["type"] == "Hashtag" and data["name"] end)
121 |> Enum.map(fn data -> String.slice(data["name"], 1..-1) end)
122
123 combined = (object["tag"] || []) ++ tags
124
125 object
126 |> Map.put("tag", combined)
127 end
128
129 # content map usually only has one language so this will do for now.
130 def fix_content_map(%{"contentMap" => content_map} = object) do
131 content_groups = Map.to_list(content_map)
132 {_, content} = Enum.at(content_groups, 0)
133
134 object
135 |> Map.put("content", content)
136 end
137
138 def fix_content_map(object), do: object
139
140 # TODO: validate those with a Ecto scheme
141 # - tags
142 # - emoji
143 def handle_incoming(%{"type" => "Create", "object" => %{"type" => objtype} = object} = data)
144 when objtype in ["Article", "Note"] do
145 actor = get_actor(data)
146 data = Map.put(data, "actor", actor)
147
148 with nil <- Activity.get_create_activity_by_object_ap_id(object["id"]),
149 %User{} = user <- User.get_or_fetch_by_ap_id(data["actor"]) do
150 object = fix_object(data["object"])
151
152 params = %{
153 to: data["to"],
154 object: object,
155 actor: user,
156 context: object["conversation"],
157 local: false,
158 published: data["published"],
159 additional:
160 Map.take(data, [
161 "cc",
162 "id"
163 ])
164 }
165
166 ActivityPub.create(params)
167 else
168 %Activity{} = activity -> {:ok, activity}
169 _e -> :error
170 end
171 end
172
173 def handle_incoming(
174 %{"type" => "Follow", "object" => followed, "actor" => follower, "id" => id} = data
175 ) do
176 with %User{local: true} = followed <- User.get_cached_by_ap_id(followed),
177 %User{} = follower <- User.get_or_fetch_by_ap_id(follower),
178 {:ok, activity} <- ActivityPub.follow(follower, followed, id, false) do
179 if not User.locked?(followed) do
180 ActivityPub.accept(%{
181 to: [follower.ap_id],
182 actor: followed.ap_id,
183 object: data,
184 local: true
185 })
186
187 User.follow(follower, followed)
188 end
189
190 {:ok, activity}
191 else
192 _e -> :error
193 end
194 end
195
196 defp mastodon_follow_hack(%{"id" => id, "actor" => follower_id}, followed) do
197 with true <- id =~ "follows",
198 %User{local: true} = follower <- User.get_cached_by_ap_id(follower_id),
199 %Activity{} = activity <- Utils.fetch_latest_follow(follower, followed) do
200 {:ok, activity}
201 else
202 _ -> {:error, nil}
203 end
204 end
205
206 defp mastodon_follow_hack(_), do: {:error, nil}
207
208 defp get_follow_activity(follow_object, followed) do
209 with object_id when not is_nil(object_id) <- Utils.get_ap_id(follow_object),
210 {_, %Activity{} = activity} <- {:activity, Activity.get_by_ap_id(object_id)} do
211 {:ok, activity}
212 else
213 # Can't find the activity. This might a Mastodon 2.3 "Accept"
214 {:activity, nil} ->
215 mastodon_follow_hack(follow_object, followed)
216
217 _ ->
218 {:error, nil}
219 end
220 end
221
222 def handle_incoming(
223 %{"type" => "Accept", "object" => follow_object, "actor" => actor, "id" => id} = data
224 ) do
225 with %User{} = followed <- User.get_or_fetch_by_ap_id(actor),
226 {:ok, follow_activity} <- get_follow_activity(follow_object, followed),
227 %User{local: true} = follower <- User.get_cached_by_ap_id(follow_activity.data["actor"]),
228 {:ok, activity} <-
229 ActivityPub.accept(%{
230 to: follow_activity.data["to"],
231 type: "Accept",
232 actor: followed.ap_id,
233 object: follow_activity.data["id"],
234 local: false
235 }) do
236 if not User.following?(follower, followed) do
237 {:ok, follower} = User.follow(follower, followed)
238 end
239
240 {:ok, activity}
241 else
242 _e -> :error
243 end
244 end
245
246 def handle_incoming(
247 %{"type" => "Reject", "object" => follow_object, "actor" => actor, "id" => id} = data
248 ) do
249 with %User{} = followed <- User.get_or_fetch_by_ap_id(actor),
250 {:ok, follow_activity} <- get_follow_activity(follow_object, followed),
251 %User{local: true} = follower <- User.get_cached_by_ap_id(follow_activity.data["actor"]),
252 {:ok, activity} <-
253 ActivityPub.accept(%{
254 to: follow_activity.data["to"],
255 type: "Accept",
256 actor: followed.ap_id,
257 object: follow_activity.data["id"],
258 local: false
259 }) do
260 User.unfollow(follower, followed)
261
262 {:ok, activity}
263 else
264 _e -> :error
265 end
266 end
267
268 def handle_incoming(
269 %{"type" => "Like", "object" => object_id, "actor" => actor, "id" => id} = _data
270 ) do
271 with %User{} = actor <- User.get_or_fetch_by_ap_id(actor),
272 {:ok, object} <-
273 get_obj_helper(object_id) || ActivityPub.fetch_object_from_id(object_id),
274 {:ok, activity, _object} <- ActivityPub.like(actor, object, id, false) do
275 {:ok, activity}
276 else
277 _e -> :error
278 end
279 end
280
281 def handle_incoming(
282 %{"type" => "Announce", "object" => object_id, "actor" => actor, "id" => id} = _data
283 ) do
284 with %User{} = actor <- User.get_or_fetch_by_ap_id(actor),
285 {:ok, object} <-
286 get_obj_helper(object_id) || ActivityPub.fetch_object_from_id(object_id),
287 {:ok, activity, _object} <- ActivityPub.announce(actor, object, id, false) do
288 {:ok, activity}
289 else
290 _e -> :error
291 end
292 end
293
294 def handle_incoming(
295 %{"type" => "Update", "object" => %{"type" => "Person"} = object, "actor" => actor_id} =
296 data
297 ) do
298 with %User{ap_id: ^actor_id} = actor <- User.get_by_ap_id(object["id"]) do
299 {:ok, new_user_data} = ActivityPub.user_data_from_user_object(object)
300
301 banner = new_user_data[:info]["banner"]
302 locked = new_user_data[:info]["locked"] || false
303
304 update_data =
305 new_user_data
306 |> Map.take([:name, :bio, :avatar])
307 |> Map.put(:info, Map.merge(actor.info, %{"banner" => banner, "locked" => locked}))
308
309 actor
310 |> User.upgrade_changeset(update_data)
311 |> User.update_and_set_cache()
312
313 ActivityPub.update(%{
314 local: false,
315 to: data["to"] || [],
316 cc: data["cc"] || [],
317 object: object,
318 actor: actor_id
319 })
320 else
321 e ->
322 Logger.error(e)
323 :error
324 end
325 end
326
327 # TODO: Make secure.
328 def handle_incoming(
329 %{"type" => "Delete", "object" => object_id, "actor" => actor, "id" => _id} = _data
330 ) do
331 object_id = Utils.get_ap_id(object_id)
332
333 with %User{} = _actor <- User.get_or_fetch_by_ap_id(actor),
334 {:ok, object} <-
335 get_obj_helper(object_id) || ActivityPub.fetch_object_from_id(object_id),
336 {:ok, activity} <- ActivityPub.delete(object, false) do
337 {:ok, activity}
338 else
339 _e -> :error
340 end
341 end
342
343 def handle_incoming(
344 %{
345 "type" => "Undo",
346 "object" => %{"type" => "Announce", "object" => object_id},
347 "actor" => actor,
348 "id" => id
349 } = _data
350 ) do
351 with %User{} = actor <- User.get_or_fetch_by_ap_id(actor),
352 {:ok, object} <-
353 get_obj_helper(object_id) || ActivityPub.fetch_object_from_id(object_id),
354 {:ok, activity, _} <- ActivityPub.unannounce(actor, object, id, false) do
355 {:ok, activity}
356 else
357 _e -> :error
358 end
359 end
360
361 def handle_incoming(
362 %{
363 "type" => "Undo",
364 "object" => %{"type" => "Follow", "object" => followed},
365 "actor" => follower,
366 "id" => id
367 } = _data
368 ) do
369 with %User{local: true} = followed <- User.get_cached_by_ap_id(followed),
370 %User{} = follower <- User.get_or_fetch_by_ap_id(follower),
371 {:ok, activity} <- ActivityPub.unfollow(follower, followed, id, false) do
372 User.unfollow(follower, followed)
373 {:ok, activity}
374 else
375 e -> :error
376 end
377 end
378
379 @ap_config Application.get_env(:pleroma, :activitypub)
380 @accept_blocks Keyword.get(@ap_config, :accept_blocks)
381
382 def handle_incoming(
383 %{
384 "type" => "Undo",
385 "object" => %{"type" => "Block", "object" => blocked},
386 "actor" => blocker,
387 "id" => id
388 } = _data
389 ) do
390 with true <- @accept_blocks,
391 %User{local: true} = blocked <- User.get_cached_by_ap_id(blocked),
392 %User{} = blocker <- User.get_or_fetch_by_ap_id(blocker),
393 {:ok, activity} <- ActivityPub.unblock(blocker, blocked, id, false) do
394 User.unblock(blocker, blocked)
395 {:ok, activity}
396 else
397 e -> :error
398 end
399 end
400
401 def handle_incoming(
402 %{"type" => "Block", "object" => blocked, "actor" => blocker, "id" => id} = data
403 ) do
404 with true <- @accept_blocks,
405 %User{local: true} = blocked = User.get_cached_by_ap_id(blocked),
406 %User{} = blocker = User.get_or_fetch_by_ap_id(blocker),
407 {:ok, activity} <- ActivityPub.block(blocker, blocked, id, false) do
408 User.unfollow(blocker, blocked)
409 User.block(blocker, blocked)
410 {:ok, activity}
411 else
412 e -> :error
413 end
414 end
415
416 def handle_incoming(
417 %{
418 "type" => "Undo",
419 "object" => %{"type" => "Like", "object" => object_id},
420 "actor" => actor,
421 "id" => id
422 } = _data
423 ) do
424 with %User{} = actor <- User.get_or_fetch_by_ap_id(actor),
425 {:ok, object} <-
426 get_obj_helper(object_id) || ActivityPub.fetch_object_from_id(object_id),
427 {:ok, activity, _, _} <- ActivityPub.unlike(actor, object, id, false) do
428 {:ok, activity}
429 else
430 _e -> :error
431 end
432 end
433
434 def handle_incoming(_), do: :error
435
436 def get_obj_helper(id) do
437 if object = Object.normalize(id), do: {:ok, object}, else: nil
438 end
439
440 def set_reply_to_uri(%{"inReplyTo" => inReplyTo} = object) do
441 with false <- String.starts_with?(inReplyTo, "http"),
442 {:ok, %{data: replied_to_object}} <- get_obj_helper(inReplyTo) do
443 Map.put(object, "inReplyTo", replied_to_object["external_url"] || inReplyTo)
444 else
445 _e -> object
446 end
447 end
448
449 def set_reply_to_uri(obj), do: obj
450
451 # Prepares the object of an outgoing create activity.
452 def prepare_object(object) do
453 object
454 |> set_sensitive
455 |> add_hashtags
456 |> add_mention_tags
457 |> add_emoji_tags
458 |> add_attributed_to
459 |> prepare_attachments
460 |> set_conversation
461 |> set_reply_to_uri
462 end
463
464 # @doc
465 # """
466 # internal -> Mastodon
467 # """
468
469 def prepare_outgoing(%{"type" => "Create", "object" => %{"type" => "Note"} = object} = data) do
470 object =
471 object
472 |> prepare_object
473
474 data =
475 data
476 |> Map.put("object", object)
477 |> Map.put("@context", "https://www.w3.org/ns/activitystreams")
478
479 {:ok, data}
480 end
481
482 # Mastodon Accept/Reject requires a non-normalized object containing the actor URIs,
483 # because of course it does.
484 def prepare_outgoing(%{"type" => "Accept"} = data) do
485 with follow_activity <- Activity.normalize(data["object"]) do
486 object = %{
487 "actor" => follow_activity.actor,
488 "object" => follow_activity.data["object"],
489 "id" => follow_activity.data["id"],
490 "type" => "Follow"
491 }
492
493 data =
494 data
495 |> Map.put("object", object)
496 |> Map.put("@context", "https://www.w3.org/ns/activitystreams")
497
498 {:ok, data}
499 end
500 end
501
502 def prepare_outgoing(%{"type" => "Reject"} = data) do
503 with follow_activity <- Activity.normalize(data["object"]) do
504 object = %{
505 "actor" => follow_activity.actor,
506 "object" => follow_activity.data["object"],
507 "id" => follow_activity.data["id"],
508 "type" => "Follow"
509 }
510
511 data =
512 data
513 |> Map.put("object", object)
514 |> Map.put("@context", "https://www.w3.org/ns/activitystreams")
515
516 {:ok, data}
517 end
518 end
519
520 def prepare_outgoing(%{"type" => _type} = data) do
521 data =
522 data
523 |> maybe_fix_object_url
524 |> Map.put("@context", "https://www.w3.org/ns/activitystreams")
525
526 {:ok, data}
527 end
528
529 def maybe_fix_object_url(data) do
530 if is_binary(data["object"]) and not String.starts_with?(data["object"], "http") do
531 case ActivityPub.fetch_object_from_id(data["object"]) do
532 {:ok, relative_object} ->
533 if relative_object.data["external_url"] do
534 _data =
535 data
536 |> Map.put("object", relative_object.data["external_url"])
537 else
538 data
539 end
540
541 e ->
542 Logger.error("Couldn't fetch #{data["object"]} #{inspect(e)}")
543 data
544 end
545 else
546 data
547 end
548 end
549
550 def add_hashtags(object) do
551 tags =
552 (object["tag"] || [])
553 |> Enum.map(fn tag ->
554 %{
555 "href" => Pleroma.Web.Endpoint.url() <> "/tags/#{tag}",
556 "name" => "##{tag}",
557 "type" => "Hashtag"
558 }
559 end)
560
561 object
562 |> Map.put("tag", tags)
563 end
564
565 def add_mention_tags(object) do
566 recipients = object["to"] ++ (object["cc"] || [])
567
568 mentions =
569 recipients
570 |> Enum.map(fn ap_id -> User.get_cached_by_ap_id(ap_id) end)
571 |> Enum.filter(& &1)
572 |> Enum.map(fn user ->
573 %{"type" => "Mention", "href" => user.ap_id, "name" => "@#{user.nickname}"}
574 end)
575
576 tags = object["tag"] || []
577
578 object
579 |> Map.put("tag", tags ++ mentions)
580 end
581
582 # TODO: we should probably send mtime instead of unix epoch time for updated
583 def add_emoji_tags(object) do
584 tags = object["tag"] || []
585 emoji = object["emoji"] || []
586
587 out =
588 emoji
589 |> Enum.map(fn {name, url} ->
590 %{
591 "icon" => %{"url" => url, "type" => "Image"},
592 "name" => ":" <> name <> ":",
593 "type" => "Emoji",
594 "updated" => "1970-01-01T00:00:00Z",
595 "id" => url
596 }
597 end)
598
599 object
600 |> Map.put("tag", tags ++ out)
601 end
602
603 def set_conversation(object) do
604 Map.put(object, "conversation", object["context"])
605 end
606
607 def set_sensitive(object) do
608 tags = object["tag"] || []
609 Map.put(object, "sensitive", "nsfw" in tags)
610 end
611
612 def add_attributed_to(object) do
613 attributedTo = object["attributedTo"] || object["actor"]
614
615 object
616 |> Map.put("attributedTo", attributedTo)
617 end
618
619 def prepare_attachments(object) do
620 attachments =
621 (object["attachment"] || [])
622 |> Enum.map(fn data ->
623 [%{"mediaType" => media_type, "href" => href} | _] = data["url"]
624 %{"url" => href, "mediaType" => media_type, "name" => data["name"], "type" => "Document"}
625 end)
626
627 object
628 |> Map.put("attachment", attachments)
629 end
630
631 defp user_upgrade_task(user) do
632 old_follower_address = User.ap_followers(user)
633
634 q =
635 from(
636 u in User,
637 where: ^old_follower_address in u.following,
638 update: [
639 set: [
640 following:
641 fragment(
642 "array_replace(?,?,?)",
643 u.following,
644 ^old_follower_address,
645 ^user.follower_address
646 )
647 ]
648 ]
649 )
650
651 Repo.update_all(q, [])
652
653 maybe_retire_websub(user.ap_id)
654
655 # Only do this for recent activties, don't go through the whole db.
656 # Only look at the last 1000 activities.
657 since = (Repo.aggregate(Activity, :max, :id) || 0) - 1_000
658
659 q =
660 from(
661 a in Activity,
662 where: ^old_follower_address in a.recipients,
663 where: a.id > ^since,
664 update: [
665 set: [
666 recipients:
667 fragment(
668 "array_replace(?,?,?)",
669 a.recipients,
670 ^old_follower_address,
671 ^user.follower_address
672 )
673 ]
674 ]
675 )
676
677 Repo.update_all(q, [])
678 end
679
680 def upgrade_user_from_ap_id(ap_id, async \\ true) do
681 with %User{local: false} = user <- User.get_by_ap_id(ap_id),
682 {:ok, data} <- ActivityPub.fetch_and_prepare_user_from_ap_id(ap_id) do
683 data =
684 data
685 |> Map.put(:info, Map.merge(user.info, data[:info]))
686
687 already_ap = User.ap_enabled?(user)
688
689 {:ok, user} =
690 User.upgrade_changeset(user, data)
691 |> Repo.update()
692
693 if !already_ap do
694 # This could potentially take a long time, do it in the background
695 if async do
696 Task.start(fn ->
697 user_upgrade_task(user)
698 end)
699 else
700 user_upgrade_task(user)
701 end
702 end
703
704 {:ok, user}
705 else
706 e -> e
707 end
708 end
709
710 def maybe_retire_websub(ap_id) do
711 # some sanity checks
712 if is_binary(ap_id) && String.length(ap_id) > 8 do
713 q =
714 from(
715 ws in Pleroma.Web.Websub.WebsubClientSubscription,
716 where: fragment("? like ?", ws.topic, ^"#{ap_id}%")
717 )
718
719 Repo.delete_all(q)
720 end
721 end
722
723 def maybe_fix_user_url(data) do
724 if is_map(data["url"]) do
725 Map.put(data, "url", data["url"]["href"])
726 else
727 data
728 end
729 end
730
731 def maybe_fix_user_object(data) do
732 data
733 |> maybe_fix_user_url
734 end
735 end