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