transmogrifier.ex 28 KB
Newer Older
1
# Pleroma: A lightweight social networking server
2
# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/>
3
4
# SPDX-License-Identifier: AGPL-3.0-only

5
6
7
8
defmodule Pleroma.Web.ActivityPub.Transmogrifier do
  @moduledoc """
  A module to handle coding from internal to wire ActivityPub and back.
  """
Haelwenn's avatar
Haelwenn committed
9
  alias Pleroma.Activity
10
  alias Pleroma.EctoType.ActivityPub.ObjectValidators
11
  alias Pleroma.Maps
Haelwenn's avatar
Haelwenn committed
12
  alias Pleroma.Object
rinpatch's avatar
rinpatch committed
13
  alias Pleroma.Object.Containment
Haelwenn's avatar
Haelwenn committed
14
  alias Pleroma.Repo
15
  alias Pleroma.User
Haelwenn's avatar
Haelwenn committed
16
  alias Pleroma.Web.ActivityPub.ActivityPub
17
  alias Pleroma.Web.ActivityPub.Builder
18
19
  alias Pleroma.Web.ActivityPub.ObjectValidator
  alias Pleroma.Web.ActivityPub.Pipeline
Haelwenn's avatar
Haelwenn committed
20
  alias Pleroma.Web.ActivityPub.Utils
lain's avatar
lain committed
21
  alias Pleroma.Web.ActivityPub.Visibility
22
  alias Pleroma.Web.Federator
23
  alias Pleroma.Workers.TransmogrifierWorker
24

lain's avatar
lain committed
25
26
  import Ecto.Query

27
  require Logger
28
  require Pleroma.Constants
29

30
31
32
  @doc """
  Modifies an incoming AP object (mastodon format) to our internal format.
  """
33
  def fix_object(object, options \\ []) do
34
    object
35
    |> strip_internal_fields
36
    |> fix_actor
37
    |> fix_url
38
    |> fix_attachments
lain's avatar
lain committed
39
    |> fix_context
40
    |> fix_in_reply_to(options)
lain's avatar
lain committed
41
    |> fix_emoji
42
    |> fix_tag
43
    |> set_sensitive
44
    |> fix_content_map
45
    |> fix_addressing
46
    |> fix_summary
47
    |> fix_type(options)
48
49
50
  end

  def fix_summary(%{"summary" => nil} = object) do
51
    Map.put(object, "summary", "")
52
53
54
55
56
57
58
  end

  def fix_summary(%{"summary" => _} = object) do
    # summary is present, nothing to do
    object
  end

59
  def fix_summary(object), do: Map.put(object, "summary", "")
60
61

  def fix_addressing_list(map, field) do
62
63
    addrs = map[field]

64
    cond do
65
66
      is_list(addrs) ->
        Map.put(map, field, Enum.filter(addrs, &is_binary/1))
67

68
69
      is_binary(addrs) ->
        Map.put(map, field, [addrs])
70
71

      true ->
72
        Map.put(map, field, [])
73
74
75
    end
  end

76
77
78
79
80
  def fix_explicit_addressing(
        %{"to" => to, "cc" => cc} = object,
        explicit_mentions,
        follower_collection
      ) do
81
    explicit_to = Enum.filter(to, fn x -> x in explicit_mentions end)
82

83
    explicit_cc = Enum.filter(to, fn x -> x not in explicit_mentions end)
84
85
86

    final_cc =
      (cc ++ explicit_cc)
87
      |> Enum.reject(fn x -> String.ends_with?(x, "/followers") and x != follower_collection end)
88
89
90
91
92
93
94
      |> Enum.uniq()

    object
    |> Map.put("to", explicit_to)
    |> Map.put("cc", final_cc)
  end

95
  def fix_explicit_addressing(object, _explicit_mentions, _followers_collection), do: object
96

97
98
  # if directMessage flag is set to true, leave the addressing alone
  def fix_explicit_addressing(%{"directMessage" => true} = object), do: object
99

100
  def fix_explicit_addressing(object) do
101
    explicit_mentions = Utils.determine_explicit_mentions(object)
102

103
104
105
106
    %User{follower_address: follower_collection} =
      object
      |> Containment.get_actor()
      |> User.get_cached_by_ap_id()
107

108
109
110
111
112
113
    explicit_mentions =
      explicit_mentions ++
        [
          Pleroma.Constants.as_public(),
          follower_collection
        ]
114

115
    fix_explicit_addressing(object, explicit_mentions, follower_collection)
lain's avatar
lain committed
116
117
  end

118
119
120
121
122
123
124
  # if as:Public is addressed, then make sure the followers collection is also addressed
  # so that the activities will be delivered to local users.
  def fix_implicit_addressing(%{"to" => to, "cc" => cc} = object, followers_collection) do
    recipients = to ++ cc

    if followers_collection not in recipients do
      cond do
125
        Pleroma.Constants.as_public() in cc ->
126
127
128
          to = to ++ [followers_collection]
          Map.put(object, "to", to)

129
        Pleroma.Constants.as_public() in to ->
130
131
132
133
134
135
          cc = cc ++ [followers_collection]
          Map.put(object, "cc", cc)

        true ->
          object
      end
136
    else
137
      object
138
139
140
    end
  end

141
142
  def fix_implicit_addressing(object, _), do: object

143
  def fix_addressing(object) do
Alexander Strizhakov's avatar
Alexander Strizhakov committed
144
    {:ok, %User{} = user} = User.get_or_fetch_by_ap_id(object["actor"])
145
146
    followers_collection = User.ap_followers(user)

147
    object
148
149
150
151
    |> fix_addressing_list("to")
    |> fix_addressing_list("cc")
    |> fix_addressing_list("bto")
    |> fix_addressing_list("bcc")
152
    |> fix_explicit_addressing()
153
    |> fix_implicit_addressing(followers_collection)
lain's avatar
lain committed
154
155
  end

156
  def fix_actor(%{"attributedTo" => actor} = object) do
157
158
159
160
161
162
    actor = Containment.get_actor(%{"actor" => actor})

    # TODO: Remove actor field for Objects
    object
    |> Map.put("actor", actor)
    |> Map.put("attributedTo", actor)
163
164
  end

165
166
167
  def fix_in_reply_to(object, options \\ [])

  def fix_in_reply_to(%{"inReplyTo" => in_reply_to} = object, options)
168
      when not is_nil(in_reply_to) do
169
    in_reply_to_id = prepare_in_reply_to(in_reply_to)
170
    depth = (options[:depth] || 0) + 1
lain's avatar
lain committed
171

172
    if Federator.allowed_thread_distance?(depth) do
173
      with {:ok, replied_object} <- get_obj_helper(in_reply_to_id, options),
minibikini's avatar
minibikini committed
174
           %Activity{} <- Activity.get_create_by_object_ap_id(replied_object.data["id"]) do
175
176
177
        object
        |> Map.put("inReplyTo", replied_object.data["id"])
        |> Map.put("context", replied_object.data["context"] || object["conversation"])
178
        |> Map.drop(["conversation", "inReplyToAtomUri"])
179
      else
180
        e ->
181
          Logger.warn("Couldn't fetch #{inspect(in_reply_to_id)}, error: #{inspect(e)}")
182
183
184
185
          object
      end
    else
      object
lain's avatar
lain committed
186
187
    end
  end
lain's avatar
lain committed
188

189
  def fix_in_reply_to(object, _options), do: object
lain's avatar
lain committed
190

191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
  defp prepare_in_reply_to(in_reply_to) do
    cond do
      is_bitstring(in_reply_to) ->
        in_reply_to

      is_map(in_reply_to) && is_bitstring(in_reply_to["id"]) ->
        in_reply_to["id"]

      is_list(in_reply_to) && is_bitstring(Enum.at(in_reply_to, 0)) ->
        Enum.at(in_reply_to, 0)

      true ->
        ""
    end
  end

lain's avatar
lain committed
207
  def fix_context(object) do
Haelwenn's avatar
Haelwenn committed
208
209
    context = object["context"] || object["conversation"] || Utils.generate_context_id()

lain's avatar
lain committed
210
    object
Haelwenn's avatar
Haelwenn committed
211
    |> Map.put("context", context)
212
    |> Map.drop(["conversation"])
lain's avatar
lain committed
213
214
  end

215
  def fix_attachments(%{"attachment" => attachment} = object) when is_list(attachment) do
lain's avatar
lain committed
216
    attachments =
217
      Enum.map(attachment, fn data ->
218
219
220
221
222
223
224
225
226
        url =
          cond do
            is_list(data["url"]) -> List.first(data["url"])
            is_map(data["url"]) -> data["url"]
            true -> nil
          end

        media_type =
          cond do
227
228
229
            is_map(url) && MIME.valid?(url["mediaType"]) -> url["mediaType"]
            MIME.valid?(data["mediaType"]) -> data["mediaType"]
            MIME.valid?(data["mimeType"]) -> data["mimeType"]
230
231
232
233
234
235
236
237
            true -> nil
          end

        href =
          cond do
            is_map(url) && is_binary(url["href"]) -> url["href"]
            is_binary(data["url"]) -> data["url"]
            is_binary(data["href"]) -> data["href"]
Haelwenn's avatar
Haelwenn committed
238
            true -> nil
239
240
          end

Haelwenn's avatar
Haelwenn committed
241
242
        if href do
          attachment_url =
Haelwenn's avatar
Haelwenn committed
243
244
245
246
            %{
              "href" => href,
              "type" => Map.get(url || %{}, "type", "Link")
            }
Haelwenn's avatar
Haelwenn committed
247
            |> Maps.put_if_present("mediaType", media_type)
248

Haelwenn's avatar
Haelwenn committed
249
250
251
252
          %{
            "url" => [attachment_url],
            "type" => data["type"] || "Document"
          }
Haelwenn's avatar
Haelwenn committed
253
254
          |> Maps.put_if_present("mediaType", media_type)
          |> Maps.put_if_present("name", data["name"])
255
          |> Maps.put_if_present("blurhash", data["blurhash"])
Haelwenn's avatar
Haelwenn committed
256
257
258
        else
          nil
        end
lain's avatar
lain committed
259
      end)
Haelwenn's avatar
Haelwenn committed
260
      |> Enum.filter(& &1)
lain's avatar
lain committed
261

262
    Map.put(object, "attachment", attachments)
263
264
  end

265
  def fix_attachments(%{"attachment" => attachment} = object) when is_map(attachment) do
Maksim's avatar
Maksim committed
266
267
268
    object
    |> Map.put("attachment", [attachment])
    |> fix_attachments()
269
270
  end

271
  def fix_attachments(object), do: object
272

273
  def fix_url(%{"url" => url} = object) when is_map(url) do
274
    Map.put(object, "url", url["href"])
275
276
  end

Haelwenn's avatar
Haelwenn committed
277
  def fix_url(%{"url" => url} = object) when is_list(url) do
278
279
280
281
282
283
284
285
286
    first_element = Enum.at(url, 0)

    url_string =
      cond do
        is_bitstring(first_element) -> first_element
        is_map(first_element) -> first_element["href"] || ""
        true -> ""
      end

287
    Map.put(object, "url", url_string)
288
289
290
291
  end

  def fix_url(object), do: object

292
  def fix_emoji(%{"tag" => tags} = object) when is_list(tags) do
lain's avatar
lain committed
293
    emoji =
294
      tags
295
      |> Enum.filter(fn data -> is_map(data) and data["type"] == "Emoji" and data["icon"] end)
lain's avatar
lain committed
296
      |> Enum.reduce(%{}, fn data, mapping ->
297
        name = String.trim(data["name"], ":")
lain's avatar
lain committed
298

299
        Map.put(mapping, name, data["icon"]["url"])
lain's avatar
lain committed
300
      end)
lain's avatar
lain committed
301

302
    Map.put(object, "emoji", emoji)
lain's avatar
lain committed
303
304
  end

305
306
307
308
  def fix_emoji(%{"tag" => %{"type" => "Emoji"} = tag} = object) do
    name = String.trim(tag["name"], ":")
    emoji = %{name => tag["icon"]["url"]}

309
    Map.put(object, "emoji", emoji)
310
311
  end

312
  def fix_emoji(object), do: object
313

314
  def fix_tag(%{"tag" => tag} = object) when is_list(tag) do
315
    tags =
316
      tag
lain's avatar
lain committed
317
      |> Enum.filter(fn data -> data["type"] == "Hashtag" and data["name"] end)
318
319
320
321
      |> Enum.map(fn %{"name" => name} ->
        name
        |> String.slice(1..-1)
        |> String.downcase()
322
      end)
323

324
    Map.put(object, "tag", tag ++ tags)
325
326
  end

327
328
329
330
  def fix_tag(%{"tag" => %{} = tag} = object) do
    object
    |> Map.put("tag", [tag])
    |> fix_tag
331
332
  end

333
  def fix_tag(object), do: object
334

335
336
337
338
339
  # content map usually only has one language so this will do for now.
  def fix_content_map(%{"contentMap" => content_map} = object) do
    content_groups = Map.to_list(content_map)
    {_, content} = Enum.at(content_groups, 0)

340
    Map.put(object, "content", content)
341
342
343
344
  end

  def fix_content_map(object), do: object

345
346
  def fix_type(object, options \\ [])

347
348
  def fix_type(%{"inReplyTo" => reply_id, "name" => _} = object, options)
      when is_binary(reply_id) do
349
    with true <- Federator.allowed_thread_distance?(options[:depth]),
350
         {:ok, %{data: %{"type" => "Question"} = _} = _} <- get_obj_helper(reply_id, options) do
351
352
      Map.put(object, "type", "Answer")
    else
353
      _ -> object
354
355
356
    end
  end

357
  def fix_type(object, _), do: object
358

359
360
361
362
363
364
365
366
367
368
369
  # Reduce the object list to find the reported user.
  defp get_reported(objects) do
    Enum.reduce_while(objects, nil, fn ap_id, _ ->
      with %User{} = user <- User.get_cached_by_ap_id(ap_id) do
        {:halt, user}
      else
        _ -> {:cont, nil}
      end
    end)
  end

370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
  # Compatibility wrapper for Mastodon votes
  defp handle_create(%{"object" => %{"type" => "Answer"}} = data, _user) do
    handle_incoming(data)
  end

  defp handle_create(%{"object" => object} = data, user) do
    %{
      to: data["to"],
      object: object,
      actor: user,
      context: object["context"],
      local: false,
      published: data["published"],
      additional:
        Map.take(data, [
          "cc",
          "directMessage",
          "id"
        ])
    }
    |> ActivityPub.create()
  end

393
394
  def handle_incoming(data, options \\ [])

395
396
  # Flag objects are placed ahead of the ID check because Mastodon 2.8 and earlier send them
  # with nil ID.
397
  def handle_incoming(%{"type" => "Flag", "object" => objects, "actor" => actor} = data, _options) do
398
399
400
401
    with context <- data["context"] || Utils.generate_context_id(),
         content <- data["content"] || "",
         %User{} = actor <- User.get_cached_by_ap_id(actor),
         # Reduce the object list to find the reported user.
402
         %User{} = account <- get_reported(objects),
403
404
         # Remove the reported user from the object list.
         statuses <- Enum.filter(objects, fn ap_id -> ap_id != account.ap_id end) do
405
      %{
406
407
408
409
410
        actor: actor,
        context: context,
        account: account,
        statuses: statuses,
        content: content,
411
        additional: %{"cc" => [account.ap_id]}
412
      }
413
      |> ActivityPub.flag()
414
415
416
    end
  end

417
  # disallow objects with bogus IDs
418
419
  def handle_incoming(%{"id" => nil}, _options), do: :error
  def handle_incoming(%{"id" => ""}, _options), do: :error
420
  # length of https:// = 8, should validate better, but good enough for now.
rinpatch's avatar
rinpatch committed
421
  def handle_incoming(%{"id" => id}, _options) when is_binary(id) and byte_size(id) < 8,
422
    do: :error
423

424
425
426
  # TODO: validate those with a Ecto scheme
  # - tags
  # - emoji
427
428
429
430
  def handle_incoming(
        %{"type" => "Create", "object" => %{"type" => objtype} = object} = data,
        options
      )
Haelwenn's avatar
Haelwenn committed
431
      when objtype in ~w{Note Page} do
432
    actor = Containment.get_actor(data)
433

434
    with nil <- Activity.get_create_by_object_ap_id(object["id"]),
435
436
437
438
439
440
441
442
         {:ok, %User{} = user} <- User.get_or_fetch_by_ap_id(actor) do
      data =
        data
        |> Map.put("object", fix_object(object, options))
        |> Map.put("actor", actor)
        |> fix_addressing()

      with {:ok, created_activity} <- handle_create(data, user) do
443
444
445
446
447
448
449
450
451
        reply_depth = (options[:depth] || 0) + 1

        if Federator.allowed_thread_distance?(reply_depth) do
          for reply_id <- replies(object) do
            Pleroma.Workers.RemoteFetcherWorker.enqueue("fetch_remote", %{
              "id" => reply_id,
              "depth" => reply_depth
            })
          end
452
453
454
455
        end

        {:ok, created_activity}
      end
456
    else
lain's avatar
lain committed
457
      %Activity{} = activity -> {:ok, activity}
458
459
460
461
      _e -> :error
    end
  end

462
463
464
465
466
467
468
469
470
471
472
  def handle_incoming(
        %{"type" => "Listen", "object" => %{"type" => "Audio"} = object} = data,
        options
      ) do
    actor = Containment.get_actor(data)

    data =
      Map.put(data, "actor", actor)
      |> fix_addressing

    with {:ok, %User{} = user} <- User.get_or_fetch_by_ap_id(data["actor"]) do
473
474
      reply_depth = (options[:depth] || 0) + 1
      options = Keyword.put(options, :depth, reply_depth)
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
      object = fix_object(object, options)

      params = %{
        to: data["to"],
        object: object,
        actor: user,
        context: nil,
        local: false,
        published: data["published"],
        additional: Map.take(data, ["cc", "id"])
      }

      ActivityPub.listen(params)
    else
      _e -> :error
    end
  end

493
494
495
496
497
498
499
500
501
502
  @misskey_reactions %{
    "like" => "👍",
    "love" => "❤️",
    "laugh" => "😆",
    "hmm" => "🤔",
    "surprise" => "😮",
    "congrats" => "🎉",
    "angry" => "💢",
    "confused" => "😥",
    "rip" => "😇",
503
504
    "pudding" => "🍮",
    "star" => "⭐"
505
506
  }

lain's avatar
lain committed
507
  @doc "Rewrite misskey likes into EmojiReacts"
508
509
510
511
512
513
514
515
  def handle_incoming(
        %{
          "type" => "Like",
          "_misskey_reaction" => reaction
        } = data,
        options
      ) do
    data
lain's avatar
lain committed
516
    |> Map.put("type", "EmojiReact")
517
    |> Map.put("content", @misskey_reactions[reaction] || reaction)
518
519
520
    |> handle_incoming(options)
  end

Haelwenn's avatar
Haelwenn committed
521
  def handle_incoming(
522
        %{"type" => "Create", "object" => %{"type" => objtype, "id" => obj_id}} = data,
Haelwenn's avatar
Haelwenn committed
523
        _options
Haelwenn's avatar
Haelwenn committed
524
      )
Haelwenn's avatar
Haelwenn committed
525
      when objtype in ~w{Question Answer ChatMessage Audio Video Event Article} do
526
527
    data = Map.put(data, "object", strip_internal_fields(data["object"]))

Haelwenn's avatar
Haelwenn committed
528
    with {:ok, %User{}} <- ObjectValidator.fetch_actor(data),
529
         nil <- Activity.get_create_by_object_ap_id(obj_id),
Haelwenn's avatar
Haelwenn committed
530
531
         {:ok, activity, _} <- Pipeline.common_pipeline(data, local: false) do
      {:ok, activity}
532
533
534
    else
      %Activity{} = activity -> {:ok, activity}
      e -> e
Haelwenn's avatar
Haelwenn committed
535
536
537
    end
  end

538
  def handle_incoming(%{"type" => type} = data, _options)
539
      when type in ~w{Like EmojiReact Announce} do
lain's avatar
lain committed
540
541
542
    with :ok <- ObjectValidator.fetch_actor_and_object(data),
         {:ok, activity, _meta} <-
           Pipeline.common_pipeline(data, local: false) do
lain's avatar
lain committed
543
544
      {:ok, activity}
    else
545
      e -> {:error, e}
lain's avatar
lain committed
546
547
548
    end
  end

lain's avatar
lain committed
549
  def handle_incoming(
550
        %{"type" => type} = data,
551
        _options
552
      )
553
      when type in ~w{Update Block Follow Accept Reject} do
554
    with {:ok, %User{}} <- ObjectValidator.fetch_actor(data),
555
556
         {:ok, activity, _} <-
           Pipeline.common_pipeline(data, local: false) do
557
      {:ok, activity}
lain's avatar
lain committed
558
559
560
    end
  end

lain's avatar
lain committed
561
  def handle_incoming(
562
        %{"type" => "Delete"} = data,
563
        _options
lain's avatar
lain committed
564
      ) do
565
566
    with {:ok, activity, _} <-
           Pipeline.common_pipeline(data, local: false) do
lain's avatar
lain committed
567
      {:ok, activity}
568
569
570
    else
      {:error, {:validate_object, _}} = e ->
        # Check if we have a create activity for this
571
        with {:ok, object_id} <- ObjectValidators.ObjectID.cast(data["object"]),
572
573
574
575
576
577
578
579
580
             %Activity{data: %{"actor" => actor}} <-
               Activity.create_by_object_ap_id(object_id) |> Repo.one(),
             # We have one, insert a tombstone and retry
             {:ok, tombstone_data, _} <- Builder.tombstone(actor, object_id),
             {:ok, _tombstone} <- Object.create(tombstone_data) do
          handle_incoming(data)
        else
          _ -> e
        end
lain's avatar
lain committed
581
582
583
    end
  end

normandy's avatar
normandy committed
584
585
586
587
588
589
  def handle_incoming(
        %{
          "type" => "Undo",
          "object" => %{"type" => "Follow", "object" => followed},
          "actor" => follower,
          "id" => id
590
591
        } = _data,
        _options
normandy's avatar
normandy committed
592
      ) do
normandy's avatar
normandy committed
593
    with %User{local: true} = followed <- User.get_cached_by_ap_id(followed),
594
         {:ok, %User{} = follower} <- User.get_or_fetch_by_ap_id(follower),
normandy's avatar
normandy committed
595
         {:ok, activity} <- ActivityPub.unfollow(follower, followed, id, false) do
normandy's avatar
normandy committed
596
597
598
      User.unfollow(follower, followed)
      {:ok, activity}
    else
Maksim's avatar
Maksim committed
599
      _e -> :error
normandy's avatar
normandy committed
600
601
602
    end
  end

603
604
605
  def handle_incoming(
        %{
          "type" => "Undo",
606
          "object" => %{"type" => type}
607
608
        } = data,
        _options
609
      )
610
      when type in ["Like", "EmojiReact", "Announce", "Block"] do
611
    with {:ok, activity, _} <- Pipeline.common_pipeline(data, local: false) do
612
613
614
615
      {:ok, activity}
    end
  end

616
  # For Undos that don't have the complete object attached, try to find it in our database.
normandy's avatar
normandy committed
617
618
619
  def handle_incoming(
        %{
          "type" => "Undo",
620
621
622
623
624
625
626
627
628
          "object" => object
        } = activity,
        options
      )
      when is_binary(object) do
    with %Activity{data: data} <- Activity.get_by_ap_id(object) do
      activity
      |> Map.put("object", data)
      |> handle_incoming(options)
normandy's avatar
normandy committed
629
    else
Maksim's avatar
Maksim committed
630
      _e -> :error
normandy's avatar
normandy committed
631
632
633
    end
  end

minibikini's avatar
minibikini committed
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
  def handle_incoming(
        %{
          "type" => "Move",
          "actor" => origin_actor,
          "object" => origin_actor,
          "target" => target_actor
        },
        _options
      ) do
    with %User{} = origin_user <- User.get_cached_by_ap_id(origin_actor),
         {:ok, %User{} = target_user} <- User.get_or_fetch_by_ap_id(target_actor),
         true <- origin_actor in target_user.also_known_as do
      ActivityPub.move(origin_user, target_user, false)
    else
      _e -> :error
    end
  end

652
  def handle_incoming(_, _), do: :error
653

654
  @spec get_obj_helper(String.t(), Keyword.t()) :: {:ok, Object.t()} | nil
655
  def get_obj_helper(id, options \\ []) do
656
657
658
    options = Keyword.put(options, :fetch, true)

    case Object.normalize(id, options) do
Maksim's avatar
Maksim committed
659
660
      %Object{} = object -> {:ok, object}
      _ -> nil
661
    end
662
663
  end

664
  @spec get_embedded_obj_helper(String.t() | Object.t(), User.t()) :: {:ok, Object.t()} | nil
Thibaut Girka's avatar
Thibaut Girka committed
665
  def get_embedded_obj_helper(%{"attributedTo" => attributed_to, "id" => object_id} = data, %User{
666
667
        ap_id: ap_id
      })
Thibaut Girka's avatar
Thibaut Girka committed
668
      when attributed_to == ap_id do
669
670
671
672
673
    with {:ok, activity} <-
           handle_incoming(%{
             "type" => "Create",
             "to" => data["to"],
             "cc" => data["cc"],
Thibaut Girka's avatar
Thibaut Girka committed
674
             "actor" => attributed_to,
675
676
             "object" => data
           }) do
677
      {:ok, Object.normalize(activity, fetch: false)}
678
679
680
681
682
683
684
685
686
    else
      _ -> get_obj_helper(object_id)
    end
  end

  def get_embedded_obj_helper(object_id, _) do
    get_obj_helper(object_id)
  end

687
688
689
690
  def set_reply_to_uri(%{"inReplyTo" => in_reply_to} = object) when is_binary(in_reply_to) do
    with false <- String.starts_with?(in_reply_to, "http"),
         {:ok, %{data: replied_to_object}} <- get_obj_helper(in_reply_to) do
      Map.put(object, "inReplyTo", replied_to_object["external_url"] || in_reply_to)
691
692
693
694
    else
      _e -> object
    end
  end
lain's avatar
lain committed
695

696
697
  def set_reply_to_uri(obj), do: obj

698
699
700
701
  @doc """
  Serialized Mastodon-compatible `replies` collection containing _self-replies_.
  Based on Mastodon's ActivityPub::NoteSerializer#replies.
  """
702
  def set_replies(obj_data) do
703
    replies_uris =
Ivan Tashkinov's avatar
Ivan Tashkinov committed
704
705
      with limit when limit > 0 <-
             Pleroma.Config.get([:activitypub, :note_replies_output_limit], 0),
706
707
708
709
           %Object{} = object <- Object.get_cached_by_ap_id(obj_data["id"]) do
        object
        |> Object.self_replies()
        |> select([o], fragment("?->>'id'", o.data))
710
711
        |> limit(^limit)
        |> Repo.all()
Ivan Tashkinov's avatar
Ivan Tashkinov committed
712
713
      else
        _ -> []
714
715
      end

Ivan Tashkinov's avatar
Ivan Tashkinov committed
716
    set_replies(obj_data, replies_uris)
717
718
  end

Ivan Tashkinov's avatar
Ivan Tashkinov committed
719
  defp set_replies(obj, []) do
720
721
722
723
724
725
    obj
  end

  defp set_replies(obj, replies_uris) do
    replies_collection = %{
      "type" => "Collection",
726
      "items" => replies_uris
727
728
729
730
731
    }

    Map.merge(obj, %{"replies" => replies_collection})
  end

Ivan Tashkinov's avatar
Ivan Tashkinov committed
732
733
734
  def replies(%{"replies" => %{"first" => %{"items" => items}}}) when not is_nil(items) do
    items
  end
735

Ivan Tashkinov's avatar
Ivan Tashkinov committed
736
737
  def replies(%{"replies" => %{"items" => items}}) when not is_nil(items) do
    items
738
739
740
741
  end

  def replies(_), do: []

742
  # Prepares the object of an outgoing create activity.
lain's avatar
lain committed
743
744
  def prepare_object(object) do
    object
lain's avatar
lain committed
745
    |> set_sensitive
lain's avatar
lain committed
746
    |> add_hashtags
lain's avatar
lain committed
747
    |> add_mention_tags
lain's avatar
lain committed
748
    |> add_emoji_tags
lain's avatar
lain committed
749
    |> add_attributed_to
lain's avatar
lain committed
750
    |> prepare_attachments
lain's avatar
lain committed
751
    |> set_conversation
752
    |> set_reply_to_uri
753
    |> set_replies
754
755
    |> strip_internal_fields
    |> strip_internal_tags
756
    |> set_type
lain's avatar
lain committed
757
758
  end

feld's avatar
feld committed
759
760
761
762
  #  @doc
  #  """
  #  internal -> Mastodon
  #  """
lain's avatar
lain committed
763

764
765
  def prepare_outgoing(%{"type" => activity_type, "object" => object_id} = data)
      when activity_type in ["Create", "Listen"] do
lain's avatar
lain committed
766
    object =
minibikini's avatar
minibikini committed
767
      object_id
768
      |> Object.normalize(fetch: false)
minibikini's avatar
minibikini committed
769
      |> Map.get(:data)
lain's avatar
lain committed
770
771
772
773
774
      |> prepare_object

    data =
      data
      |> Map.put("object", object)
lain's avatar
lain committed
775
      |> Map.merge(Utils.make_json_ld_header())
minibikini's avatar
minibikini committed
776
      |> Map.delete("bcc")
lain's avatar
lain committed
777
778
779
780

    {:ok, data}
  end

781
782
783
  def prepare_outgoing(%{"type" => "Announce", "actor" => ap_id, "object" => object_id} = data) do
    object =
      object_id
784
      |> Object.normalize(fetch: false)
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801

    data =
      if Visibility.is_private?(object) && object.data["actor"] == ap_id do
        data |> Map.put("object", object |> Map.get(:data) |> prepare_object)
      else
        data |> maybe_fix_object_url
      end

    data =
      data
      |> strip_internal_fields
      |> Map.merge(Utils.make_json_ld_header())
      |> Map.delete("bcc")

    {:ok, data}
  end

kaniini's avatar
kaniini committed
802
803
804
  # Mastodon Accept/Reject requires a non-normalized object containing the actor URIs,
  # because of course it does.
  def prepare_outgoing(%{"type" => "Accept"} = data) do
805
    with follow_activity <- Activity.normalize(data["object"]) do
kaniini's avatar
kaniini committed
806
807
808
809
810
811
812
813
814
815
      object = %{
        "actor" => follow_activity.actor,
        "object" => follow_activity.data["object"],
        "id" => follow_activity.data["id"],
        "type" => "Follow"
      }

      data =
        data
        |> Map.put("object", object)
lain's avatar
lain committed
816
        |> Map.merge(Utils.make_json_ld_header())
kaniini's avatar
kaniini committed
817
818
819
820
821

      {:ok, data}
    end
  end

822
  def prepare_outgoing(%{"type" => "Reject"} = data) do
823
    with follow_activity <- Activity.normalize(data["object"]) do
824
825
826
827
828
829
830
831
832
833
      object = %{
        "actor" => follow_activity.actor,
        "object" => follow_activity.data["object"],
        "id" => follow_activity.data["id"],
        "type" => "Follow"
      }

      data =
        data
        |> Map.put("object", object)
lain's avatar
lain committed
834
        |> Map.merge(Utils.make_json_ld_header())
835
836
837
838
839

      {:ok, data}
    end
  end

feld's avatar
feld committed
840
  def prepare_outgoing(%{"type" => _type} = data) do
lain's avatar
lain committed
841
842
    data =
      data
843
      |> strip_internal_fields
lain's avatar
lain committed
844
      |> maybe_fix_object_url
lain's avatar
lain committed
845
      |> Map.merge(Utils.make_json_ld_header())
846
847
848
849

    {:ok, data}
  end

850
851
852
853
854
855
  def maybe_fix_object_url(%{"object" => object} = data) when is_binary(object) do
    with false <- String.starts_with?(object, "http"),
         {:fetch, {:ok, relative_object}} <- {:fetch, get_obj_helper(object)},
         %{data: %{"external_url" => external_url}} when not is_nil(external_url) <-
           relative_object do
      Map.put(data, "object", external_url)
856
    else
857
858
859
860
861
862
      {:fetch, e} ->
        Logger.error("Couldn't fetch #{object} #{inspect(e)}")
        data

      _ ->
        data
863
864
865
    end
  end

866
867
  def maybe_fix_object_url(data), do: data

lain's avatar
lain committed
868
  def add_hashtags(object) do
869
870
871
872
873
874
875
876
877
878
879
880
881
882
    tags =
      (object["tag"] || [])
      |> Enum.map(fn
        # Expand internal representation tags into AS2 tags.
        tag when is_binary(tag) ->
          %{
            "href" => Pleroma.Web.Endpoint.url() <> "/tags/#{tag}",
            "name" => "##{tag}",
            "type" => "Hashtag"
          }

        # Do not process tags which are already AS2 tag objects.
        tag when is_map(tag) ->
          tag
lain's avatar
lain committed
883
      end)
lain's avatar
lain committed
884

885
    Map.put(object, "tag", tags)
lain's avatar
lain committed
886
887
  end

888
889
  # TODO These should be added on our side on insertion, it doesn't make much
  # sense to regenerate these all the time
lain's avatar
lain committed
890
  def add_mention_tags(object) do
891
892
893
894
895
    to = object["to"] || []
    cc = object["cc"] || []
    mentioned = User.get_users_from_set(to ++ cc, local_only: false)

    mentions = Enum.map(mentioned, &build_mention_tag/1)
lain's avatar
lain committed
896

lain's avatar
lain committed
897
    tags = object["tag"] || []
898
    Map.put(object, "tag", tags ++ mentions)
lain's avatar
lain committed
899
900
  end

Maksim's avatar
Maksim committed
901
902
903
  defp build_mention_tag(%{ap_id: ap_id, nickname: nickname} = _) do
    %{"type" => "Mention", "href" => ap_id, "name" => "@#{nickname}"}
  end
Haelwenn's avatar
Haelwenn committed
904

905
  def take_emoji_tags(%User{emoji: emoji}) do
Maksim's avatar
Maksim committed
906
    emoji
907
    |> Map.to_list()
Maksim's avatar
Maksim committed
908
    |> Enum.map(&build_emoji_tag/1)
Haelwenn's avatar
Haelwenn committed
909
910
  end

lain's avatar
lain committed
911
  # TODO: we should probably send mtime instead of unix epoch time for updated
Haelwenn's avatar
Haelwenn committed
912
  def add_emoji_tags(%{"emoji" => emoji} = object) do
lain's avatar
lain committed
913
    tags = object["tag"] || []
lain's avatar
lain committed
914

Maksim's avatar
Maksim committed
915
    out = Enum.map(emoji, &build_emoji_tag/1)
lain's avatar
lain committed
916

917
    Map.put(object, "tag", tags ++ out)
lain's avatar
lain committed
918
919
  end

920
  def add_emoji_tags(object), do: object
Haelwenn's avatar
Haelwenn committed
921

Maksim's avatar
Maksim committed
922
923
  defp build_emoji_tag({name, url}) do
    %{
feld's avatar
feld committed
924
      "icon" => %{"url" => "#{URI.encode(url)}", "type" => "Image"},
Maksim's avatar
Maksim committed
925
926
927
928
929
930
931
      "name" => ":" <> name <> ":",
      "type" => "Emoji",
      "updated" => "1970-01-01T00:00:00Z",
      "id" => url
    }
  end

lain's avatar
lain committed
932
933
934
935
  def set_conversation(object) do
    Map.put(object, "conversation", object["context"])
  end

936
  def set_sensitive(%{"sensitive" => _} = object) do
937
938
939
    object
  end

lain's avatar
lain committed
940
  def set_sensitive(object) do
941
    tags = object["tag"] || []
lain's avatar
lain committed
942
943
944
    Map.put(object, "sensitive", "nsfw" in tags)
  end

945
946
947
948
949
950
  def set_type(%{"type" => "Answer"} = object) do
    Map.put(object, "type", "Note")
  end

  def set_type(object), do: object

lain's avatar
lain committed
951
  def add_attributed_to(object) do
952
    attributed_to = object["attributedTo"] || object["actor"]
953
    Map.put(object, "attributedTo", attributed_to)
954
  end
lain's avatar
lain committed
955

956
957
958
  # TODO: Revisit this
  def prepare_attachments(%{"type" => "ChatMessage"} = object), do: object

lain's avatar
lain committed
959
  def prepare_attachments(object) do
lain's avatar
lain committed
960
    attachments =
Maksim's avatar
Maksim committed
961
962
      object
      |> Map.get("attachment", [])
lain's avatar
lain committed
963