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
    |> fix_content_map
44
    |> fix_addressing
45
    |> fix_summary
46
    |> fix_type(options)
47
48
49
  end

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

117
118
119
120
121
122
123
  # 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
124
        Pleroma.Constants.as_public() in cc ->
125
126
127
          to = to ++ [followers_collection]
          Map.put(object, "to", to)

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

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

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

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

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

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

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

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

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

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

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

190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
  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
206
  def fix_context(object) do
Haelwenn's avatar
Haelwenn committed
207
208
    context = object["context"] || object["conversation"] || Utils.generate_context_id()

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

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

        media_type =
          cond do
226
227
228
            is_map(url) && MIME.valid?(url["mediaType"]) -> url["mediaType"]
            MIME.valid?(data["mediaType"]) -> data["mediaType"]
            MIME.valid?(data["mimeType"]) -> data["mimeType"]
229
230
231
232
233
234
235
236
            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
237
            true -> nil
238
239
          end

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

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

260
    Map.put(object, "attachment", attachments)
261
262
  end

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

269
  def fix_attachments(object), do: object
270

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

Haelwenn's avatar
Haelwenn committed
275
  def fix_url(%{"url" => url} = object) when is_list(url) do
276
277
278
279
280
281
282
283
284
    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

285
    Map.put(object, "url", url_string)
286
287
288
289
  end

  def fix_url(object), do: object

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

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

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

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

307
    Map.put(object, "emoji", emoji)
308
309
  end

310
  def fix_emoji(object), do: object
311

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

318
    Map.put(object, "tag", tag ++ tags)
319
320
  end

321
322
  def fix_tag(%{"tag" => %{"type" => "Hashtag", "name" => hashtag} = tag} = object) do
    combined = [tag, String.slice(hashtag, 1..-1)]
323

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

327
328
  def fix_tag(%{"tag" => %{} = tag} = object), do: Map.put(object, "tag", [tag])

329
  def fix_tag(object), do: object
330

331
332
333
334
335
  # 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)

336
    Map.put(object, "content", content)
337
338
339
340
  end

  def fix_content_map(object), do: object

341
342
  def fix_type(object, options \\ [])

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

353
  def fix_type(object, _), do: object
354

355
356
357
358
359
360
361
362
363
364
365
  # 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

366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
  # 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

389
390
  def handle_incoming(data, options \\ [])

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

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

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

430
    with nil <- Activity.get_create_by_object_ap_id(object["id"]),
431
432
433
434
435
436
437
438
         {: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
439
440
441
442
443
444
445
446
447
        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
448
449
450
451
        end

        {:ok, created_activity}
      end
452
    else
lain's avatar
lain committed
453
      %Activity{} = activity -> {:ok, activity}
454
455
456
457
      _e -> :error
    end
  end

458
459
460
461
462
463
464
465
466
467
468
  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
469
470
      reply_depth = (options[:depth] || 0) + 1
      options = Keyword.put(options, :depth, reply_depth)
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
      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

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

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

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

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

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

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

lain's avatar
lain committed
557
  def handle_incoming(
558
        %{"type" => "Delete"} = data,
559
        _options
lain's avatar
lain committed
560
      ) do
561
562
    with {:ok, activity, _} <-
           Pipeline.common_pipeline(data, local: false) do
lain's avatar
lain committed
563
      {:ok, activity}
564
565
566
    else
      {:error, {:validate_object, _}} = e ->
        # Check if we have a create activity for this
567
        with {:ok, object_id} <- ObjectValidators.ObjectID.cast(data["object"]),
568
569
570
571
572
573
574
575
576
             %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
577
578
579
    end
  end

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

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

612
  # For Undos that don't have the complete object attached, try to find it in our database.
normandy's avatar
normandy committed
613
614
615
  def handle_incoming(
        %{
          "type" => "Undo",
616
617
618
619
620
621
622
623
624
          "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
625
    else
Maksim's avatar
Maksim committed
626
      _e -> :error
normandy's avatar
normandy committed
627
628
629
    end
  end

minibikini's avatar
minibikini committed
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
  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

648
  def handle_incoming(_, _), do: :error
649

650
  @spec get_obj_helper(String.t(), Keyword.t()) :: {:ok, Object.t()} | nil
651
  def get_obj_helper(id, options \\ []) do
Maksim's avatar
Maksim committed
652
653
654
    case Object.normalize(id, true, options) do
      %Object{} = object -> {:ok, object}
      _ -> nil
655
    end
656
657
  end

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

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

681
682
683
684
  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)
685
686
687
688
    else
      _e -> object
    end
  end
lain's avatar
lain committed
689

690
691
  def set_reply_to_uri(obj), do: obj

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

Ivan Tashkinov's avatar
Ivan Tashkinov committed
710
    set_replies(obj_data, replies_uris)
711
712
  end

Ivan Tashkinov's avatar
Ivan Tashkinov committed
713
  defp set_replies(obj, []) do
714
715
716
717
718
719
    obj
  end

  defp set_replies(obj, replies_uris) do
    replies_collection = %{
      "type" => "Collection",
720
      "items" => replies_uris
721
722
723
724
725
    }

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

Ivan Tashkinov's avatar
Ivan Tashkinov committed
726
727
728
  def replies(%{"replies" => %{"first" => %{"items" => items}}}) when not is_nil(items) do
    items
  end
729

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

  def replies(_), do: []

736
  # Prepares the object of an outgoing create activity.
lain's avatar
lain committed
737
738
  def prepare_object(object) do
    object
lain's avatar
lain committed
739
    |> set_sensitive
lain's avatar
lain committed
740
    |> add_hashtags
lain's avatar
lain committed
741
    |> add_mention_tags
lain's avatar
lain committed
742
    |> add_emoji_tags
lain's avatar
lain committed
743
    |> add_attributed_to
lain's avatar
lain committed
744
    |> prepare_attachments
lain's avatar
lain committed
745
    |> set_conversation
746
    |> set_reply_to_uri
747
    |> set_replies
748
749
    |> strip_internal_fields
    |> strip_internal_tags
750
    |> set_type
lain's avatar
lain committed
751
752
  end

feld's avatar
feld committed
753
754
755
756
  #  @doc
  #  """
  #  internal -> Mastodon
  #  """
lain's avatar
lain committed
757

758
759
  def prepare_outgoing(%{"type" => activity_type, "object" => object_id} = data)
      when activity_type in ["Create", "Listen"] do
lain's avatar
lain committed
760
    object =
minibikini's avatar
minibikini committed
761
762
763
      object_id
      |> Object.normalize()
      |> Map.get(:data)
lain's avatar
lain committed
764
765
766
767
768
      |> prepare_object

    data =
      data
      |> Map.put("object", object)
lain's avatar
lain committed
769
      |> Map.merge(Utils.make_json_ld_header())
minibikini's avatar
minibikini committed
770
      |> Map.delete("bcc")
lain's avatar
lain committed
771
772
773
774

    {:ok, data}
  end

775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
  def prepare_outgoing(%{"type" => "Announce", "actor" => ap_id, "object" => object_id} = data) do
    object =
      object_id
      |> Object.normalize()

    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
796
797
798
  # Mastodon Accept/Reject requires a non-normalized object containing the actor URIs,
  # because of course it does.
  def prepare_outgoing(%{"type" => "Accept"} = data) do
799
    with follow_activity <- Activity.normalize(data["object"]) do
kaniini's avatar
kaniini committed
800
801
802
803
804
805
806
807
808
809
      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
810
        |> Map.merge(Utils.make_json_ld_header())
kaniini's avatar
kaniini committed
811
812
813
814
815

      {:ok, data}
    end
  end

816
  def prepare_outgoing(%{"type" => "Reject"} = data) do
817
    with follow_activity <- Activity.normalize(data["object"]) do
818
819
820
821
822
823
824
825
826
827
      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
828
        |> Map.merge(Utils.make_json_ld_header())
829
830
831
832
833

      {:ok, data}
    end
  end

feld's avatar
feld committed
834
  def prepare_outgoing(%{"type" => _type} = data) do
lain's avatar
lain committed
835
836
    data =
      data
837
      |> strip_internal_fields
lain's avatar
lain committed
838
      |> maybe_fix_object_url
lain's avatar
lain committed
839
      |> Map.merge(Utils.make_json_ld_header())
840
841
842
843

    {:ok, data}
  end

844
845
846
847
848
849
  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)
850
    else
851
852
853
854
855
856
      {:fetch, e} ->
        Logger.error("Couldn't fetch #{object} #{inspect(e)}")
        data

      _ ->
        data
857
858
859
    end
  end

860
861
  def maybe_fix_object_url(data), do: data

lain's avatar
lain committed
862
  def add_hashtags(object) do
lain's avatar
lain committed
863
864
    tags =
      (object["tag"] || [])
865
866
867
868
869
870
871
872
873
874
875
876
      |> 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
877
      end)
lain's avatar
lain committed
878

879
    Map.put(object, "tag", tags)
lain's avatar
lain committed
880
881
  end

882
883
  # 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
884
  def add_mention_tags(object) do
885
886
887
888
889
    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
890

lain's avatar
lain committed
891
    tags = object["tag"] || []
892
    Map.put(object, "tag", tags ++ mentions)
lain's avatar
lain committed
893
894
  end

Maksim's avatar
Maksim committed
895
896
897
  defp build_mention_tag(%{ap_id: ap_id, nickname: nickname} = _) do
    %{"type" => "Mention", "href" => ap_id, "name" => "@#{nickname}"}
  end
Haelwenn's avatar
Haelwenn committed
898

899
  def take_emoji_tags(%User{emoji: emoji}) do
Maksim's avatar
Maksim committed
900
    emoji
901
    |> Map.to_list()
Maksim's avatar
Maksim committed
902
    |> Enum.map(&build_emoji_tag/1)
Haelwenn's avatar
Haelwenn committed
903
904
  end

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

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

911
    Map.put(object, "tag", tags ++ out)
lain's avatar
lain committed
912
913
  end

914
  def add_emoji_tags(object), do: object
Haelwenn's avatar
Haelwenn committed
915

Maksim's avatar
Maksim committed
916
917
918
919
920
921
922
923
924
925
  defp build_emoji_tag({name, url}) do
    %{
      "icon" => %{"url" => url, "type" => "Image"},
      "name" => ":" <> name <> ":",
      "type" => "Emoji",
      "updated" => "1970-01-01T00:00:00Z",
      "id" => url
    }
  end

lain's avatar
lain committed
926
927
928
929
  def set_conversation(object) do
    Map.put(object, "conversation", object["context"])
  end

930
931
932
933
  def set_sensitive(%{"sensitive" => true} = object) do
    object
  end

lain's avatar
lain committed
934
935
936
937
938
  def set_sensitive(object) do
    tags = object["tag"] || []
    Map.put(object, "sensitive", "nsfw" in tags)
  end

939
940
941
942
943
944
  def set_type(%{"type" => "Answer"} = object) do
    Map.put(object, "type", "Note")
  end

  def set_type(object), do: object

lain's avatar
lain committed
945
  def add_attributed_to(object) do
946
    attributed_to = object["attributedTo"] || object["actor"]
947
    Map.put(object, "attributedTo", attributed_to)
948
  end
lain's avatar
lain committed
949

950
951
952
  # TODO: Revisit this
  def prepare_attachments(%{"type" => "ChatMessage"} = object), do: object

lain's avatar
lain committed
953
  def prepare_attachments(object) do
lain's avatar
lain committed
954
    attachments =
Maksim's avatar
Maksim committed
955
956
      object
      |> Map.get("attachment", [])
lain's avatar
lain committed
957
958
      |> Enum.map(fn data ->
        [%{"mediaType" => media_type, "href" => href} | _] = data["url"]
Maksim's avatar
Maksim committed
959
960
961
962
963
964
965

        %{
          "url" => href,
          "mediaType" => media_type,
          "name" => data["name"],
          "type" => "Document"
        }
lain's avatar
lain committed
966
      end)
lain's avatar
lain committed
967

968
    Map.put(object, "attachment", attachments)
lain's avatar
lain committed
969
  end
lain's avatar
lain committed
970

971
  def strip_internal_fields(object) do
Maksim's avatar
Maksim committed
972
    Map.drop(object, Pleroma.Constants.object_internal_fields())
973
974
975
  end

  defp strip_internal_tags(%{"tag" => tags} = object) do