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