transmogrifier.ex 28.1 KB
Newer Older
1
# Pleroma: A lightweight social networking server
Haelwenn's avatar
Haelwenn committed
2
# Copyright © 2017-2021 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
36
37
38
39
    |> strip_internal_fields()
    |> fix_actor()
    |> fix_url()
    |> fix_attachments()
    |> fix_context()
40
    |> fix_in_reply_to(options)
41
42
43
44
45
    |> fix_emoji()
    |> fix_tag()
    |> fix_content_map()
    |> fix_addressing()
    |> fix_summary()
46
47
48
  end

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

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

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

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

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

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

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

74
75
76
  # if directMessage flag is set to true, leave the addressing alone
  def fix_explicit_addressing(%{"directMessage" => true} = object, _follower_collection),
    do: object
77

78
79
80
81
82
83
  def fix_explicit_addressing(%{"to" => to, "cc" => cc} = object, follower_collection) do
    explicit_mentions =
      Utils.determine_explicit_mentions(object) ++
        [Pleroma.Constants.as_public(), follower_collection]

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

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

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

97
98
99
100
101
102
103
  # 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
104
        Pleroma.Constants.as_public() in cc ->
105
106
107
          to = to ++ [followers_collection]
          Map.put(object, "to", to)

108
        Pleroma.Constants.as_public() in to ->
109
110
111
112
113
114
          cc = cc ++ [followers_collection]
          Map.put(object, "cc", cc)

        true ->
          object
      end
115
    else
116
      object
117
118
119
    end
  end

120
  def fix_addressing(object) do
121
122
123
124
    {:ok, %User{follower_address: follower_collection}} =
      object
      |> Containment.get_actor()
      |> User.get_or_fetch_by_ap_id()
125

126
    object
127
128
129
130
    |> fix_addressing_list("to")
    |> fix_addressing_list("cc")
    |> fix_addressing_list("bto")
    |> fix_addressing_list("bcc")
131
132
    |> fix_explicit_addressing(follower_collection)
    |> fix_implicit_addressing(follower_collection)
lain's avatar
lain committed
133
134
  end

135
  def fix_actor(%{"attributedTo" => actor} = object) do
136
137
138
139
140
141
    actor = Containment.get_actor(%{"actor" => actor})

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

144
145
146
  def fix_in_reply_to(object, options \\ [])

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

151
    if Federator.allowed_thread_distance?(depth) do
152
      with {:ok, replied_object} <- get_obj_helper(in_reply_to_id, options),
minibikini's avatar
minibikini committed
153
           %Activity{} <- Activity.get_create_by_object_ap_id(replied_object.data["id"]) do
154
155
156
        object
        |> Map.put("inReplyTo", replied_object.data["id"])
        |> Map.put("context", replied_object.data["context"] || object["conversation"])
157
        |> Map.drop(["conversation", "inReplyToAtomUri"])
158
      else
159
        e ->
160
          Logger.warn("Couldn't fetch #{inspect(in_reply_to_id)}, error: #{inspect(e)}")
161
162
163
164
          object
      end
    else
      object
lain's avatar
lain committed
165
166
    end
  end
lain's avatar
lain committed
167

168
  def fix_in_reply_to(object, _options), do: object
lain's avatar
lain committed
169

170
  def fix_quote_url(object, options \\ [])
171

172
  def fix_quote_url(%{"quoteUrl" => quote_url} = object, options)
173
174
175
176
177
178
179
180
181
182
183
      when not is_nil(quote_url) do
    with {:ok, quoted_object} <- get_obj_helper(quote_url, options),
         %Activity{} <- Activity.get_create_by_object_ap_id(quoted_object.data["id"]) do
      Map.put(object, "quoteUrl", quoted_object.data["id"])
    else
      e ->
        Logger.warn("Couldn't fetch #{inspect(quote_url)}, error: #{inspect(e)}")
        object
    end
  end

184
185
186
187
188
189
190
191
192
  # Fedibird
  # https://github.com/fedibird/mastodon/commit/dbd7ae6cf58a92ec67c512296b4daaea0d01e6ac
  def fix_quote_url(%{"quoteUri" => quote_url} = object, options) do
    object
    |> Map.put("quoteUrl", quote_url)
    |> fix_quote_url(options)
  end

  # Old Fedibird (bug)
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
  # https://github.com/fedibird/mastodon/issues/9
  def fix_quote_url(%{"quoteURL" => quote_url} = object, options) do
    object
    |> Map.put("quoteUrl", quote_url)
    |> fix_quote_url(options)
  end

  # Misskey fallback
  def fix_quote_url(%{"_misskey_quote" => quote_url} = object, options) do
    object
    |> Map.put("quoteUrl", quote_url)
    |> fix_quote_url(options)
  end

  def fix_quote_url(object, _options), do: object
208

209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
  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
225
  def fix_context(object) do
Haelwenn's avatar
Haelwenn committed
226
227
    context = object["context"] || object["conversation"] || Utils.generate_context_id()

lain's avatar
lain committed
228
    object
Haelwenn's avatar
Haelwenn committed
229
    |> Map.put("context", context)
230
    |> Map.drop(["conversation"])
lain's avatar
lain committed
231
232
  end

233
  def fix_attachments(%{"attachment" => attachment} = object) when is_list(attachment) do
lain's avatar
lain committed
234
    attachments =
235
      Enum.map(attachment, fn data ->
236
237
238
239
240
241
242
243
244
        url =
          cond do
            is_list(data["url"]) -> List.first(data["url"])
            is_map(data["url"]) -> data["url"]
            true -> nil
          end

        media_type =
          cond do
245
246
247
248
249
250
251
252
253
254
255
            is_map(url) && MIME.extensions(url["mediaType"]) != [] ->
              url["mediaType"]

            is_bitstring(data["mediaType"]) && MIME.extensions(data["mediaType"]) != [] ->
              data["mediaType"]

            is_bitstring(data["mimeType"]) && MIME.extensions(data["mimeType"]) != [] ->
              data["mimeType"]

            true ->
              nil
256
257
258
259
260
261
262
          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
263
            true -> nil
264
265
          end

Haelwenn's avatar
Haelwenn committed
266
267
        if href do
          attachment_url =
Haelwenn's avatar
Haelwenn committed
268
269
270
271
            %{
              "href" => href,
              "type" => Map.get(url || %{}, "type", "Link")
            }
Haelwenn's avatar
Haelwenn committed
272
            |> Maps.put_if_present("mediaType", media_type)
273
274
            |> Maps.put_if_present("width", (url || %{})["width"] || data["width"])
            |> Maps.put_if_present("height", (url || %{})["height"] || data["height"])
275

Haelwenn's avatar
Haelwenn committed
276
277
278
279
          %{
            "url" => [attachment_url],
            "type" => data["type"] || "Document"
          }
Haelwenn's avatar
Haelwenn committed
280
281
          |> Maps.put_if_present("mediaType", media_type)
          |> Maps.put_if_present("name", data["name"])
282
          |> Maps.put_if_present("blurhash", data["blurhash"])
Haelwenn's avatar
Haelwenn committed
283
284
285
        else
          nil
        end
lain's avatar
lain committed
286
      end)
Haelwenn's avatar
Haelwenn committed
287
      |> Enum.filter(& &1)
lain's avatar
lain committed
288

289
    Map.put(object, "attachment", attachments)
290
291
  end

292
  def fix_attachments(%{"attachment" => attachment} = object) when is_map(attachment) do
Maksim's avatar
Maksim committed
293
294
295
    object
    |> Map.put("attachment", [attachment])
    |> fix_attachments()
296
297
  end

298
  def fix_attachments(object), do: object
299

300
  def fix_url(%{"url" => url} = object) when is_map(url) do
301
    Map.put(object, "url", url["href"])
302
303
  end

Haelwenn's avatar
Haelwenn committed
304
  def fix_url(%{"url" => url} = object) when is_list(url) do
305
306
307
308
309
310
311
312
313
    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

314
    Map.put(object, "url", url_string)
315
316
317
318
  end

  def fix_url(object), do: object

319
  def fix_emoji(%{"tag" => tags} = object) when is_list(tags) do
lain's avatar
lain committed
320
    emoji =
321
      tags
322
      |> Enum.filter(fn data -> is_map(data) and data["type"] == "Emoji" and data["icon"] end)
lain's avatar
lain committed
323
      |> Enum.reduce(%{}, fn data, mapping ->
324
        name = String.trim(data["name"], ":")
lain's avatar
lain committed
325

326
        Map.put(mapping, name, data["icon"]["url"])
lain's avatar
lain committed
327
      end)
lain's avatar
lain committed
328

329
    Map.put(object, "emoji", emoji)
lain's avatar
lain committed
330
331
  end

332
333
334
335
  def fix_emoji(%{"tag" => %{"type" => "Emoji"} = tag} = object) do
    name = String.trim(tag["name"], ":")
    emoji = %{name => tag["icon"]["url"]}

336
    Map.put(object, "emoji", emoji)
337
338
  end

339
  def fix_emoji(object), do: object
340

341
  def fix_tag(%{"tag" => tag} = object) when is_list(tag) do
342
    tags =
343
      tag
lain's avatar
lain committed
344
      |> Enum.filter(fn data -> data["type"] == "Hashtag" and data["name"] end)
345
346
347
      |> Enum.map(fn
        %{"name" => "#" <> hashtag} -> String.downcase(hashtag)
        %{"name" => hashtag} -> String.downcase(hashtag)
348
      end)
349

350
    Map.put(object, "tag", tag ++ tags)
351
352
  end

353
354
355
356
  def fix_tag(%{"tag" => %{} = tag} = object) do
    object
    |> Map.put("tag", [tag])
    |> fix_tag
357
358
  end

359
  def fix_tag(object), do: object
360

361
362
363
364
365
  # 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)

366
    Map.put(object, "content", content)
367
368
369
370
  end

  def fix_content_map(object), do: object

371
372
373
  defp fix_type(%{"type" => "Note", "inReplyTo" => reply_id, "name" => _} = object, options)
       when is_binary(reply_id) do
    options = Keyword.put(options, :fetch, true)
374

375
    with %Object{data: %{"type" => "Question"}} <- Object.normalize(reply_id, options) do
376
377
      Map.put(object, "type", "Answer")
    else
378
      _ -> object
379
380
381
    end
  end

382
  defp fix_type(object, _options), do: object
383

384
385
386
387
388
389
390
391
392
393
394
  # 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

395
396
  def handle_incoming(data, options \\ [])

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

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

426
427
428
429
430
431
432
433
434
435
436
  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
437
438
      reply_depth = (options[:depth] || 0) + 1
      options = Keyword.put(options, :depth, reply_depth)
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
      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

457
458
459
460
461
462
463
464
465
466
  @misskey_reactions %{
    "like" => "👍",
    "love" => "❤️",
    "laugh" => "😆",
    "hmm" => "🤔",
    "surprise" => "😮",
    "congrats" => "🎉",
    "angry" => "💢",
    "confused" => "😥",
    "rip" => "😇",
467
468
    "pudding" => "🍮",
    "star" => "⭐"
469
470
  }

lain's avatar
lain committed
471
  @doc "Rewrite misskey likes into EmojiReacts"
472
473
474
475
476
477
478
479
  def handle_incoming(
        %{
          "type" => "Like",
          "_misskey_reaction" => reaction
        } = data,
        options
      ) do
    data
lain's avatar
lain committed
480
    |> Map.put("type", "EmojiReact")
481
    |> Map.put("content", @misskey_reactions[reaction] || reaction)
482
483
484
    |> handle_incoming(options)
  end

Haelwenn's avatar
Haelwenn committed
485
  def handle_incoming(
486
        %{"type" => "Create", "object" => %{"type" => objtype, "id" => obj_id}} = data,
Haelwenn's avatar
Haelwenn committed
487
        options
Haelwenn's avatar
Haelwenn committed
488
      )
Haelwenn's avatar
Haelwenn committed
489
      when objtype in ~w{Question Answer ChatMessage Audio Video Event Article Note Page} do
490
491
492
493
494
495
496
    fetch_options = Keyword.put(options, :depth, (options[:depth] || 0) + 1)

    object =
      data["object"]
      |> strip_internal_fields()
      |> fix_type(fetch_options)
      |> fix_in_reply_to(fetch_options)
497
      |> fix_quote_url(fetch_options)
498
499

    data = Map.put(data, "object", object)
Haelwenn's avatar
Haelwenn committed
500
    options = Keyword.put(options, :local, false)
501

Haelwenn's avatar
Haelwenn committed
502
    with {:ok, %User{}} <- ObjectValidator.fetch_actor(data),
503
         nil <- Activity.get_create_by_object_ap_id(obj_id),
Haelwenn's avatar
Haelwenn committed
504
         {:ok, activity, _} <- Pipeline.common_pipeline(data, options) do
Haelwenn's avatar
Haelwenn committed
505
      {:ok, activity}
506
507
508
    else
      %Activity{} = activity -> {:ok, activity}
      e -> e
Haelwenn's avatar
Haelwenn committed
509
510
511
    end
  end

512
  def handle_incoming(%{"type" => type} = data, _options)
Alexander Strizhakov's avatar
Alexander Strizhakov committed
513
      when type in ~w{Like EmojiReact Announce Add Remove} do
lain's avatar
lain committed
514
515
516
    with :ok <- ObjectValidator.fetch_actor_and_object(data),
         {:ok, activity, _meta} <-
           Pipeline.common_pipeline(data, local: false) do
lain's avatar
lain committed
517
518
      {:ok, activity}
    else
519
      e -> {:error, e}
lain's avatar
lain committed
520
521
522
    end
  end

lain's avatar
lain committed
523
  def handle_incoming(
524
        %{"type" => type} = data,
525
        _options
526
      )
527
      when type in ~w{Update Block Follow Accept Reject} do
528
    with {:ok, %User{}} <- ObjectValidator.fetch_actor(data),
529
530
         {:ok, activity, _} <-
           Pipeline.common_pipeline(data, local: false) do
531
      {:ok, activity}
lain's avatar
lain committed
532
533
534
    end
  end

lain's avatar
lain committed
535
  def handle_incoming(
536
        %{"type" => "Delete"} = data,
537
        _options
lain's avatar
lain committed
538
      ) do
539
540
    with {:ok, activity, _} <-
           Pipeline.common_pipeline(data, local: false) do
lain's avatar
lain committed
541
      {:ok, activity}
542
    else
Haelwenn's avatar
Haelwenn committed
543
      {:error, {:validate, _}} = e ->
544
        # Check if we have a create activity for this
545
        with {:ok, object_id} <- ObjectValidators.ObjectID.cast(data["object"]),
546
547
548
549
550
551
552
553
554
             %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
555
556
557
    end
  end

normandy's avatar
normandy committed
558
559
560
561
562
563
  def handle_incoming(
        %{
          "type" => "Undo",
          "object" => %{"type" => "Follow", "object" => followed},
          "actor" => follower,
          "id" => id
564
565
        } = _data,
        _options
normandy's avatar
normandy committed
566
      ) do
normandy's avatar
normandy committed
567
    with %User{local: true} = followed <- User.get_cached_by_ap_id(followed),
568
         {:ok, %User{} = follower} <- User.get_or_fetch_by_ap_id(follower),
normandy's avatar
normandy committed
569
         {:ok, activity} <- ActivityPub.unfollow(follower, followed, id, false) do
normandy's avatar
normandy committed
570
571
572
      User.unfollow(follower, followed)
      {:ok, activity}
    else
Maksim's avatar
Maksim committed
573
      _e -> :error
normandy's avatar
normandy committed
574
575
576
    end
  end

577
578
579
  def handle_incoming(
        %{
          "type" => "Undo",
580
          "object" => %{"type" => type}
581
582
        } = data,
        _options
583
      )
584
      when type in ["Like", "EmojiReact", "Announce", "Block"] do
585
    with {:ok, activity, _} <- Pipeline.common_pipeline(data, local: false) do
586
587
588
589
      {:ok, activity}
    end
  end

590
  # For Undos that don't have the complete object attached, try to find it in our database.
normandy's avatar
normandy committed
591
592
593
  def handle_incoming(
        %{
          "type" => "Undo",
594
595
596
597
598
599
600
601
602
          "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
603
    else
Maksim's avatar
Maksim committed
604
      _e -> :error
normandy's avatar
normandy committed
605
606
607
    end
  end

minibikini's avatar
minibikini committed
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
  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

626
  def handle_incoming(_, _), do: :error
627

628
  @spec get_obj_helper(String.t(), Keyword.t()) :: {:ok, Object.t()} | nil
629
  def get_obj_helper(id, options \\ []) do
630
631
632
    options = Keyword.put(options, :fetch, true)

    case Object.normalize(id, options) do
Maksim's avatar
Maksim committed
633
634
      %Object{} = object -> {:ok, object}
      _ -> nil
635
    end
636
637
  end

638
  @spec get_embedded_obj_helper(String.t() | Object.t(), User.t()) :: {:ok, Object.t()} | nil
Thibaut Girka's avatar
Thibaut Girka committed
639
  def get_embedded_obj_helper(%{"attributedTo" => attributed_to, "id" => object_id} = data, %User{
640
641
        ap_id: ap_id
      })
Thibaut Girka's avatar
Thibaut Girka committed
642
      when attributed_to == ap_id do
643
644
645
646
647
    with {:ok, activity} <-
           handle_incoming(%{
             "type" => "Create",
             "to" => data["to"],
             "cc" => data["cc"],
Thibaut Girka's avatar
Thibaut Girka committed
648
             "actor" => attributed_to,
649
650
             "object" => data
           }) do
651
      {:ok, Object.normalize(activity, fetch: false)}
652
653
654
655
656
657
658
659
660
    else
      _ -> get_obj_helper(object_id)
    end
  end

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

661
662
663
664
  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)
665
666
667
668
    else
      _e -> object
    end
  end
lain's avatar
lain committed
669

670
671
  def set_reply_to_uri(obj), do: obj

672
673
674
675
  @doc """
  Fedibird compatibility
  https://github.com/fedibird/mastodon/commit/dbd7ae6cf58a92ec67c512296b4daaea0d01e6ac
  """
676
  def set_quote_url(%{"quoteUrl" => quote_url} = object) when is_binary(quote_url) do
677
    Map.put(object, "quoteUri", quote_url)
678
679
680
681
  end

  def set_quote_url(obj), do: obj

682
683
684
685
  @doc """
  Serialized Mastodon-compatible `replies` collection containing _self-replies_.
  Based on Mastodon's ActivityPub::NoteSerializer#replies.
  """
686
  def set_replies(obj_data) do
687
    replies_uris =
Ivan Tashkinov's avatar
Ivan Tashkinov committed
688
689
      with limit when limit > 0 <-
             Pleroma.Config.get([:activitypub, :note_replies_output_limit], 0),
690
691
692
693
           %Object{} = object <- Object.get_cached_by_ap_id(obj_data["id"]) do
        object
        |> Object.self_replies()
        |> select([o], fragment("?->>'id'", o.data))
694
695
        |> limit(^limit)
        |> Repo.all()
Ivan Tashkinov's avatar
Ivan Tashkinov committed
696
697
      else
        _ -> []
698
699
      end

Ivan Tashkinov's avatar
Ivan Tashkinov committed
700
    set_replies(obj_data, replies_uris)
701
702
  end

Ivan Tashkinov's avatar
Ivan Tashkinov committed
703
  defp set_replies(obj, []) do
704
705
706
707
708
709
    obj
  end

  defp set_replies(obj, replies_uris) do
    replies_collection = %{
      "type" => "Collection",
710
      "items" => replies_uris
711
712
713
714
715
    }

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

Ivan Tashkinov's avatar
Ivan Tashkinov committed
716
717
718
  def replies(%{"replies" => %{"first" => %{"items" => items}}}) when not is_nil(items) do
    items
  end
719

Ivan Tashkinov's avatar
Ivan Tashkinov committed
720
721
  def replies(%{"replies" => %{"items" => items}}) when not is_nil(items) do
    items
722
723
724
725
  end

  def replies(_), do: []

726
  # Prepares the object of an outgoing create activity.
lain's avatar
lain committed
727
728
  def prepare_object(object) do
    object
lain's avatar
lain committed
729
    |> add_hashtags
lain's avatar
lain committed
730
    |> add_mention_tags
lain's avatar
lain committed
731
    |> add_emoji_tags
lain's avatar
lain committed
732
    |> add_attributed_to
lain's avatar
lain committed
733
    |> prepare_attachments
lain's avatar
lain committed
734
    |> set_conversation
735
    |> set_reply_to_uri
736
    |> set_quote_url
737
    |> set_replies
738
739
    |> strip_internal_fields
    |> strip_internal_tags
740
    |> set_type
lain's avatar
lain committed
741
742
  end

feld's avatar
feld committed
743
744
745
746
  #  @doc
  #  """
  #  internal -> Mastodon
  #  """
lain's avatar
lain committed
747

748
749
  def prepare_outgoing(%{"type" => activity_type, "object" => object_id} = data)
      when activity_type in ["Create", "Listen"] do
lain's avatar
lain committed
750
    object =
minibikini's avatar
minibikini committed
751
      object_id
752
      |> Object.normalize(fetch: false)
minibikini's avatar
minibikini committed
753
      |> Map.get(:data)
lain's avatar
lain committed
754
755
756
757
758
      |> prepare_object

    data =
      data
      |> Map.put("object", object)
lain's avatar
lain committed
759
      |> Map.merge(Utils.make_json_ld_header())
minibikini's avatar
minibikini committed
760
      |> Map.delete("bcc")
lain's avatar
lain committed
761
762
763
764

    {:ok, data}
  end

765
766
767
  def prepare_outgoing(%{"type" => "Announce", "actor" => ap_id, "object" => object_id} = data) do
    object =
      object_id
768
      |> Object.normalize(fetch: false)
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785

    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
786
787
788
  # Mastodon Accept/Reject requires a non-normalized object containing the actor URIs,
  # because of course it does.
  def prepare_outgoing(%{"type" => "Accept"} = data) do
789
    with follow_activity <- Activity.normalize(data["object"]) do
kaniini's avatar
kaniini committed
790
791
792
793
794
795
796
797
798
799
      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
800
        |> Map.merge(Utils.make_json_ld_header())
kaniini's avatar
kaniini committed
801
802
803
804
805

      {:ok, data}
    end
  end

806
  def prepare_outgoing(%{"type" => "Reject"} = data) do
807
    with follow_activity <- Activity.normalize(data["object"]) do
808
809
810
811
812
813
814
815
816
817
      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
818
        |> Map.merge(Utils.make_json_ld_header())
819
820
821
822
823

      {:ok, data}
    end
  end

feld's avatar
feld committed
824
  def prepare_outgoing(%{"type" => _type} = data) do
lain's avatar
lain committed
825
826
    data =
      data
827
      |> strip_internal_fields
lain's avatar
lain committed
828
      |> maybe_fix_object_url
lain's avatar
lain committed
829
      |> Map.merge(Utils.make_json_ld_header())
830
831
832
833

    {:ok, data}
  end

834
835
836
837
838
839
  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)
840
    else
841
842
843
844
845
846
      {:fetch, e} ->
        Logger.error("Couldn't fetch #{object} #{inspect(e)}")
        data

      _ ->
        data
847
848
849
    end
  end

850
851
  def maybe_fix_object_url(data), do: data

lain's avatar
lain committed
852
  def add_hashtags(object) do
853
854
855
856
857
858
859
860
861
862
863
864
865
866
    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
867
      end)
lain's avatar
lain committed
868

869
    Map.put(object, "tag", tags)
lain's avatar
lain committed
870
871
  end

872
873
  # 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
874
  def add_mention_tags(object) do
875
876
877
878
879
    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
880

lain's avatar
lain committed
881
    tags = object["tag"] || []
882
    Map.put(object, "tag", tags ++ mentions)
lain's avatar
lain committed
883
884
  end

Maksim's avatar
Maksim committed
885
886
887
  defp build_mention_tag(%{ap_id: ap_id, nickname: nickname} = _) do
    %{"type" => "Mention", "href" => ap_id, "name" => "@#{nickname}"}
  end
Haelwenn's avatar
Haelwenn committed
888

889
  def take_emoji_tags(%User{emoji: emoji}) do
Maksim's avatar
Maksim committed
890
    emoji
891
    |> Map.to_list()
Maksim's avatar
Maksim committed
892
    |> Enum.map(&build_emoji_tag/1)
Haelwenn's avatar
Haelwenn committed
893
894
  end

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

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

901
    Map.put(object, "tag", tags ++ out)
lain's avatar
lain committed
902
903
  end

904
  def add_emoji_tags(object), do: object
Haelwenn's avatar
Haelwenn committed
905

Maksim's avatar
Maksim committed
906
907
  defp build_emoji_tag({name, url}) do
    %{
feld's avatar
feld committed
908
      "icon" => %{"url" => "#{URI.encode(url)}", "type" => "Image"},
Maksim's avatar
Maksim committed
909
910
911
912
913
914
915
      "name" => ":" <> name <> ":",
      "type" => "Emoji",
      "updated" => "1970-01-01T00:00:00Z",
      "id" => url
    }
  end

lain's avatar
lain committed
916
917
918
919
  def set_conversation(object) do
    Map.put(object, "conversation", object["context"])
  end

920
921
922
923
924
925
  def set_type(%{"type" => "Answer"} = object) do
    Map.put(object, "type", "Note")
  end

  def set_type(object), do: object

lain's avatar
lain committed
926
  def add_attributed_to(object) do
927
    attributed_to = object["attributedTo"] || object["actor"]
928
    Map.put(object, "attributedTo", attributed_to)
929
  end
lain's avatar
lain committed
930

931
932
933
  # TODO: Revisit this
  def prepare_attachments(%{"type" => "ChatMessage"} = object), do: object

lain's avatar
lain committed
934
  def prepare_attachments(object) do
lain's avatar
lain committed
935
    attachments =
Maksim's avatar
Maksim committed
936
937
      object
      |> Map.get("attachment", [])
lain's avatar
lain committed
938
      |> Enum.map(fn data ->
939
        [%{"mediaType" => media_type, "href" => href} = url | _] = data["url"]
Maksim's avatar
Maksim committed
940
941
942
943
944
945
946

        %{
          "url" => href,
          "mediaType" => media_type,
          "name" => data["name"],
          "type" => "Document"
        }
947
948
        |> Maps.put_if_present("width", url["width"])
        |> Maps.put_if_present("height", url["height"])
Alex Gleason's avatar
Alex Gleason committed
949
        |> Maps.put_if_present("blurhash", data["blurhash"])
lain's avatar
lain committed
950
      end)
lain's avatar
lain committed
951

952
    Map.put(object, "attachment", attachments)
lain's avatar
lain committed
953
  end
lain's avatar
lain committed
954

955
  def strip_internal_fields(object) do
Maksim's avatar
Maksim committed
956
    Map.drop(object, Pleroma.Constants.object_internal_fields())
957
958
959
  end

  defp strip_internal_tags(%{"tag" => tags} = object) do
960
    tags = Enum.filter(tags, fn x -> is_map(x) end)
961

962
    Map.put(object, "tag", tags)
963
964
965
966
  end

  defp strip_internal_tags(object), do: object

967
  def perform(:user_upgrade, user) do
968
969
    # we pass a fake user so that the followers collection is stripped away
    old_follower_address = User.ap_followers(%User{nickname: user.nickname})
lain's avatar
lain committed
970