transmogrifier.ex 28.8 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
Maksim's avatar
Maksim committed
10
  alias Pleroma.EarmarkRenderer
11
  alias Pleroma.EctoType.ActivityPub.ObjectValidators
12
  alias Pleroma.Maps
Haelwenn's avatar
Haelwenn committed
13
  alias Pleroma.Object
rinpatch's avatar
rinpatch committed
14
  alias Pleroma.Object.Containment
Haelwenn's avatar
Haelwenn committed
15
  alias Pleroma.Repo
16
  alias Pleroma.User
Haelwenn's avatar
Haelwenn committed
17
  alias Pleroma.Web.ActivityPub.ActivityPub
18
  alias Pleroma.Web.ActivityPub.Builder
19
20
  alias Pleroma.Web.ActivityPub.ObjectValidator
  alias Pleroma.Web.ActivityPub.Pipeline
Haelwenn's avatar
Haelwenn committed
21
  alias Pleroma.Web.ActivityPub.Utils
lain's avatar
lain committed
22
  alias Pleroma.Web.ActivityPub.Visibility
23
  alias Pleroma.Web.Federator
24
  alias Pleroma.Workers.TransmogrifierWorker
25

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

28
  require Logger
29
  require Pleroma.Constants
30

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

192
  def fix_in_reply_to(object, _options), do: object
lain's avatar
lain committed
193

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

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

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

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

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

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

264
    Map.put(object, "attachment", attachments)
265
266
  end

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

273
  def fix_attachments(object), do: object
274

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

Haelwenn's avatar
Haelwenn committed
279
  def fix_url(%{"type" => "Video", "url" => url} = object) when is_list(url) do
Haelwenn's avatar
Haelwenn committed
280
281
282
    attachment =
      Enum.find(url, fn x ->
        media_type = x["mediaType"] || x["mimeType"] || ""
283

Haelwenn's avatar
Haelwenn committed
284
        is_map(x) and String.starts_with?(media_type, "video/")
Haelwenn's avatar
Haelwenn committed
285
286
287
288
      end)

    link_element =
      Enum.find(url, fn x -> is_map(x) and (x["mediaType"] || x["mimeType"]) == "text/html" end)
289
290

    object
Haelwenn's avatar
Haelwenn committed
291
    |> Map.put("attachment", [attachment])
292
293
294
295
296
    |> Map.put("url", link_element["href"])
  end

  def fix_url(%{"type" => object_type, "url" => url} = object)
      when object_type != "Video" and is_list(url) do
297
298
299
300
301
302
303
304
305
    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

306
    Map.put(object, "url", url_string)
307
308
309
310
  end

  def fix_url(object), do: object

311
  def fix_emoji(%{"tag" => tags} = object) when is_list(tags) do
lain's avatar
lain committed
312
    emoji =
313
314
      tags
      |> Enum.filter(fn data -> data["type"] == "Emoji" and data["icon"] end)
lain's avatar
lain committed
315
      |> Enum.reduce(%{}, fn data, mapping ->
316
        name = String.trim(data["name"], ":")
lain's avatar
lain committed
317

318
        Map.put(mapping, name, data["icon"]["url"])
lain's avatar
lain committed
319
      end)
lain's avatar
lain committed
320

321
    Map.put(object, "emoji", emoji)
lain's avatar
lain committed
322
323
  end

324
325
326
327
  def fix_emoji(%{"tag" => %{"type" => "Emoji"} = tag} = object) do
    name = String.trim(tag["name"], ":")
    emoji = %{name => tag["icon"]["url"]}

328
    Map.put(object, "emoji", emoji)
329
330
  end

331
  def fix_emoji(object), do: object
332

333
  def fix_tag(%{"tag" => tag} = object) when is_list(tag) do
lain's avatar
lain committed
334
    tags =
335
      tag
lain's avatar
lain committed
336
337
      |> Enum.filter(fn data -> data["type"] == "Hashtag" and data["name"] end)
      |> Enum.map(fn data -> String.slice(data["name"], 1..-1) end)
338

339
    Map.put(object, "tag", tag ++ tags)
340
341
  end

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

345
    Map.put(object, "tag", combined)
346
347
  end

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

350
  def fix_tag(object), do: object
351

352
353
354
355
356
  # 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)

357
    Map.put(object, "content", content)
358
359
360
361
  end

  def fix_content_map(object), do: object

362
363
  def fix_type(object, options \\ [])

364
365
  def fix_type(%{"inReplyTo" => reply_id, "name" => _} = object, options)
      when is_binary(reply_id) do
366
    with true <- Federator.allowed_thread_distance?(options[:depth]),
367
         {:ok, %{data: %{"type" => "Question"} = _} = _} <- get_obj_helper(reply_id, options) do
368
369
      Map.put(object, "type", "Answer")
    else
370
      _ -> object
371
372
373
    end
  end

374
  def fix_type(object, _), do: object
375

Maksim's avatar
Maksim committed
376
377
378
379
380
381
382
383
  defp fix_content(%{"mediaType" => "text/markdown", "content" => content} = object)
       when is_binary(content) do
    html_content =
      content
      |> Earmark.as_html!(%Earmark.Options{renderer: EarmarkRenderer})
      |> Pleroma.HTML.filter_tags()

    Map.merge(object, %{"content" => html_content, "mediaType" => "text/html"})
Maksim's avatar
Maksim committed
384
385
  end

Maksim's avatar
Maksim committed
386
  defp fix_content(object), do: object
Maksim's avatar
Maksim committed
387

388
389
390
391
392
393
394
395
396
397
398
  # 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

399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
  # 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

422
423
  def handle_incoming(data, options \\ [])

424
425
  # Flag objects are placed ahead of the ID check because Mastodon 2.8 and earlier send them
  # with nil ID.
426
  def handle_incoming(%{"type" => "Flag", "object" => objects, "actor" => actor} = data, _options) do
427
428
429
430
    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.
431
         %User{} = account <- get_reported(objects),
432
433
         # Remove the reported user from the object list.
         statuses <- Enum.filter(objects, fn ap_id -> ap_id != account.ap_id end) do
434
      %{
435
436
437
438
439
        actor: actor,
        context: context,
        account: account,
        statuses: statuses,
        content: content,
440
        additional: %{"cc" => [account.ap_id]}
441
      }
442
      |> ActivityPub.flag()
443
444
445
    end
  end

446
  # disallow objects with bogus IDs
447
448
  def handle_incoming(%{"id" => nil}, _options), do: :error
  def handle_incoming(%{"id" => ""}, _options), do: :error
449
  # length of https:// = 8, should validate better, but good enough for now.
rinpatch's avatar
rinpatch committed
450
  def handle_incoming(%{"id" => id}, _options) when is_binary(id) and byte_size(id) < 8,
451
    do: :error
452

453
454
455
  # TODO: validate those with a Ecto scheme
  # - tags
  # - emoji
456
457
458
459
  def handle_incoming(
        %{"type" => "Create", "object" => %{"type" => objtype} = object} = data,
        options
      )
Haelwenn's avatar
Haelwenn committed
460
      when objtype in ~w{Article Note Video Page} do
461
    actor = Containment.get_actor(data)
462

463
    with nil <- Activity.get_create_by_object_ap_id(object["id"]),
464
465
466
467
468
469
470
471
         {: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
472
473
474
475
476
477
478
479
480
        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
481
482
483
484
        end

        {:ok, created_activity}
      end
485
    else
lain's avatar
lain committed
486
      %Activity{} = activity -> {:ok, activity}
487
488
489
490
      _e -> :error
    end
  end

491
492
493
494
495
496
497
498
499
500
501
  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
502
503
      reply_depth = (options[:depth] || 0) + 1
      options = Keyword.put(options, :depth, reply_depth)
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
      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

522
523
524
525
526
527
528
529
530
531
  @misskey_reactions %{
    "like" => "👍",
    "love" => "❤️",
    "laugh" => "😆",
    "hmm" => "🤔",
    "surprise" => "😮",
    "congrats" => "🎉",
    "angry" => "💢",
    "confused" => "😥",
    "rip" => "😇",
532
533
    "pudding" => "🍮",
    "star" => "⭐"
534
535
  }

lain's avatar
lain committed
536
  @doc "Rewrite misskey likes into EmojiReacts"
537
538
539
540
541
542
543
544
  def handle_incoming(
        %{
          "type" => "Like",
          "_misskey_reaction" => reaction
        } = data,
        options
      ) do
    data
lain's avatar
lain committed
545
    |> Map.put("type", "EmojiReact")
546
    |> Map.put("content", @misskey_reactions[reaction] || reaction)
547
548
549
    |> handle_incoming(options)
  end

Haelwenn's avatar
Haelwenn committed
550
  def handle_incoming(
lain's avatar
lain committed
551
        %{"type" => "Create", "object" => %{"type" => objtype}} = data,
Haelwenn's avatar
Haelwenn committed
552
        _options
Haelwenn's avatar
Haelwenn committed
553
      )
Haelwenn's avatar
Haelwenn committed
554
      when objtype in ~w{Question Answer ChatMessage Audio Event} do
Haelwenn's avatar
Haelwenn committed
555
556
557
558
559
560
    with {:ok, %User{}} <- ObjectValidator.fetch_actor(data),
         {:ok, activity, _} <- Pipeline.common_pipeline(data, local: false) do
      {:ok, activity}
    end
  end

561
  def handle_incoming(%{"type" => type} = data, _options)
562
      when type in ~w{Like EmojiReact Announce} do
lain's avatar
lain committed
563
564
565
    with :ok <- ObjectValidator.fetch_actor_and_object(data),
         {:ok, activity, _meta} <-
           Pipeline.common_pipeline(data, local: false) do
lain's avatar
lain committed
566
567
      {:ok, activity}
    else
568
      e -> {:error, e}
lain's avatar
lain committed
569
570
571
    end
  end

lain's avatar
lain committed
572
  def handle_incoming(
573
        %{"type" => type} = data,
574
        _options
575
      )
576
      when type in ~w{Update Block Follow Accept Reject} do
577
    with {:ok, %User{}} <- ObjectValidator.fetch_actor(data),
578
579
         {:ok, activity, _} <-
           Pipeline.common_pipeline(data, local: false) do
580
      {:ok, activity}
lain's avatar
lain committed
581
582
583
    end
  end

lain's avatar
lain committed
584
  def handle_incoming(
585
        %{"type" => "Delete"} = data,
586
        _options
lain's avatar
lain committed
587
      ) do
588
589
    with {:ok, activity, _} <-
           Pipeline.common_pipeline(data, local: false) do
lain's avatar
lain committed
590
      {:ok, activity}
591
592
593
    else
      {:error, {:validate_object, _}} = e ->
        # Check if we have a create activity for this
594
        with {:ok, object_id} <- ObjectValidators.ObjectID.cast(data["object"]),
595
596
597
598
599
600
601
602
603
             %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
604
605
606
    end
  end

normandy's avatar
normandy committed
607
608
609
610
611
612
  def handle_incoming(
        %{
          "type" => "Undo",
          "object" => %{"type" => "Follow", "object" => followed},
          "actor" => follower,
          "id" => id
613
614
        } = _data,
        _options
normandy's avatar
normandy committed
615
      ) do
normandy's avatar
normandy committed
616
    with %User{local: true} = followed <- User.get_cached_by_ap_id(followed),
617
         {:ok, %User{} = follower} <- User.get_or_fetch_by_ap_id(follower),
normandy's avatar
normandy committed
618
         {:ok, activity} <- ActivityPub.unfollow(follower, followed, id, false) do
normandy's avatar
normandy committed
619
620
621
      User.unfollow(follower, followed)
      {:ok, activity}
    else
Maksim's avatar
Maksim committed
622
      _e -> :error
normandy's avatar
normandy committed
623
624
625
    end
  end

626
627
628
  def handle_incoming(
        %{
          "type" => "Undo",
629
          "object" => %{"type" => type}
630
631
        } = data,
        _options
632
      )
633
      when type in ["Like", "EmojiReact", "Announce", "Block"] do
634
    with {:ok, activity, _} <- Pipeline.common_pipeline(data, local: false) do
635
636
637
638
      {:ok, activity}
    end
  end

639
  # For Undos that don't have the complete object attached, try to find it in our database.
normandy's avatar
normandy committed
640
641
642
  def handle_incoming(
        %{
          "type" => "Undo",
643
644
645
646
647
648
649
650
651
          "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
652
    else
Maksim's avatar
Maksim committed
653
      _e -> :error
normandy's avatar
normandy committed
654
655
656
    end
  end

minibikini's avatar
minibikini committed
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
  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

675
  def handle_incoming(_, _), do: :error
676

677
  @spec get_obj_helper(String.t(), Keyword.t()) :: {:ok, Object.t()} | nil
678
  def get_obj_helper(id, options \\ []) do
Maksim's avatar
Maksim committed
679
680
681
    case Object.normalize(id, true, options) do
      %Object{} = object -> {:ok, object}
      _ -> nil
682
    end
683
684
  end

685
  @spec get_embedded_obj_helper(String.t() | Object.t(), User.t()) :: {:ok, Object.t()} | nil
Thibaut Girka's avatar
Thibaut Girka committed
686
  def get_embedded_obj_helper(%{"attributedTo" => attributed_to, "id" => object_id} = data, %User{
687
688
        ap_id: ap_id
      })
Thibaut Girka's avatar
Thibaut Girka committed
689
      when attributed_to == ap_id do
690
691
692
693
694
    with {:ok, activity} <-
           handle_incoming(%{
             "type" => "Create",
             "to" => data["to"],
             "cc" => data["cc"],
Thibaut Girka's avatar
Thibaut Girka committed
695
             "actor" => attributed_to,
696
697
698
699
700
701
702
703
704
705
706
707
             "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

708
709
710
711
  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)
712
713
714
715
    else
      _e -> object
    end
  end
lain's avatar
lain committed
716

717
718
  def set_reply_to_uri(obj), do: obj

719
720
721
722
  @doc """
  Serialized Mastodon-compatible `replies` collection containing _self-replies_.
  Based on Mastodon's ActivityPub::NoteSerializer#replies.
  """
723
  def set_replies(obj_data) do
724
    replies_uris =
Ivan Tashkinov's avatar
Ivan Tashkinov committed
725
726
      with limit when limit > 0 <-
             Pleroma.Config.get([:activitypub, :note_replies_output_limit], 0),
727
728
729
730
           %Object{} = object <- Object.get_cached_by_ap_id(obj_data["id"]) do
        object
        |> Object.self_replies()
        |> select([o], fragment("?->>'id'", o.data))
731
732
        |> limit(^limit)
        |> Repo.all()
Ivan Tashkinov's avatar
Ivan Tashkinov committed
733
734
      else
        _ -> []
735
736
      end

Ivan Tashkinov's avatar
Ivan Tashkinov committed
737
    set_replies(obj_data, replies_uris)
738
739
  end

Ivan Tashkinov's avatar
Ivan Tashkinov committed
740
  defp set_replies(obj, []) do
741
742
743
744
745
746
    obj
  end

  defp set_replies(obj, replies_uris) do
    replies_collection = %{
      "type" => "Collection",
747
      "items" => replies_uris
748
749
750
751
752
    }

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

Ivan Tashkinov's avatar
Ivan Tashkinov committed
753
754
755
  def replies(%{"replies" => %{"first" => %{"items" => items}}}) when not is_nil(items) do
    items
  end
756

Ivan Tashkinov's avatar
Ivan Tashkinov committed
757
758
  def replies(%{"replies" => %{"items" => items}}) when not is_nil(items) do
    items
759
760
761
762
  end

  def replies(_), do: []

763
  # Prepares the object of an outgoing create activity.
lain's avatar
lain committed
764
765
  def prepare_object(object) do
    object
lain's avatar
lain committed
766
    |> set_sensitive
lain's avatar
lain committed
767
    |> add_hashtags
lain's avatar
lain committed
768
    |> add_mention_tags
lain's avatar
lain committed
769
    |> add_emoji_tags
lain's avatar
lain committed
770
    |> add_attributed_to
lain's avatar
lain committed
771
    |> prepare_attachments
lain's avatar
lain committed
772
    |> set_conversation
773
    |> set_reply_to_uri
774
    |> set_replies
775
776
    |> strip_internal_fields
    |> strip_internal_tags
777
    |> set_type
lain's avatar
lain committed
778
779
  end

feld's avatar
feld committed
780
781
782
783
  #  @doc
  #  """
  #  internal -> Mastodon
  #  """
lain's avatar
lain committed
784

785
786
  def prepare_outgoing(%{"type" => activity_type, "object" => object_id} = data)
      when activity_type in ["Create", "Listen"] do
lain's avatar
lain committed
787
    object =
minibikini's avatar
minibikini committed
788
789
790
      object_id
      |> Object.normalize()
      |> Map.get(:data)
lain's avatar
lain committed
791
792
793
794
795
      |> prepare_object

    data =
      data
      |> Map.put("object", object)
lain's avatar
lain committed
796
      |> Map.merge(Utils.make_json_ld_header())
minibikini's avatar
minibikini committed
797
      |> Map.delete("bcc")
lain's avatar
lain committed
798
799
800
801

    {:ok, data}
  end

802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
  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
823
824
825
  # Mastodon Accept/Reject requires a non-normalized object containing the actor URIs,
  # because of course it does.
  def prepare_outgoing(%{"type" => "Accept"} = data) do
826
    with follow_activity <- Activity.normalize(data["object"]) do
kaniini's avatar
kaniini committed
827
828
829
830
831
832
833
834
835
836
      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
837
        |> Map.merge(Utils.make_json_ld_header())
kaniini's avatar
kaniini committed
838
839
840
841
842

      {:ok, data}
    end
  end

843
  def prepare_outgoing(%{"type" => "Reject"} = data) do
844
    with follow_activity <- Activity.normalize(data["object"]) do
845
846
847
848
849
850
851
852
853
854
      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
855
        |> Map.merge(Utils.make_json_ld_header())
856
857
858
859
860

      {:ok, data}
    end
  end

feld's avatar
feld committed
861
  def prepare_outgoing(%{"type" => _type} = data) do
lain's avatar
lain committed
862
863
    data =
      data
864
      |> strip_internal_fields
lain's avatar
lain committed
865
      |> maybe_fix_object_url
lain's avatar
lain committed
866
      |> Map.merge(Utils.make_json_ld_header())
867
868
869
870

    {:ok, data}
  end

871
872
873
874
875
876
  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)
877
    else
878
879
880
881
882
883
      {:fetch, e} ->
        Logger.error("Couldn't fetch #{object} #{inspect(e)}")
        data

      _ ->
        data
884
885
886
    end
  end

887
888
  def maybe_fix_object_url(data), do: data

lain's avatar
lain committed
889
  def add_hashtags(object) do
lain's avatar
lain committed
890
891
    tags =
      (object["tag"] || [])
892
893
894
895
896
897
898
899
900
901
902
903
      |> 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
904
      end)
lain's avatar
lain committed
905

906
    Map.put(object, "tag", tags)
lain's avatar
lain committed
907
908
  end

909
910
  # 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
911
  def add_mention_tags(object) do
912
913
914
915
916
    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
917

lain's avatar
lain committed
918
    tags = object["tag"] || []
919
    Map.put(object, "tag", tags ++ mentions)
lain's avatar
lain committed
920
921
  end

Maksim's avatar
Maksim committed
922
923
924
  defp build_mention_tag(%{ap_id: ap_id, nickname: nickname} = _) do
    %{"type" => "Mention", "href" => ap_id, "name" => "@#{nickname}"}
  end
Haelwenn's avatar
Haelwenn committed
925

926
  def take_emoji_tags(%User{emoji: emoji}) do
Maksim's avatar
Maksim committed
927
    emoji
928
    |> Map.to_list()
Maksim's avatar
Maksim committed
929
    |> Enum.map(&build_emoji_tag/1)
Haelwenn's avatar
Haelwenn committed
930
931
  end

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

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

938
    Map.put(object, "tag", tags ++ out)
lain's avatar
lain committed
939
940
  end

941
  def add_emoji_tags(object), do: object
Haelwenn's avatar
Haelwenn committed
942

Maksim's avatar
Maksim committed
943
944
945
946
947
948
949
950
951
952
  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
953
954
955
956
  def set_conversation(object) do
    Map.put(object, "conversation", object["context"])
  end

957
958
959
960
  def set_sensitive(%{"sensitive" => true} = object) do
    object
  end

lain's avatar
lain committed
961
962
963
964
965
  def set_sensitive(object) do
    tags = object["tag"] || []
    Map.put(object, "sensitive", "nsfw" in tags)
  end

966
967
968
969
970
971
  def set_type(%{"type" => "Answer"} = object) do
    Map.put(object, "type", "Note")
  end

  def set_type(object), do: object

lain's avatar
lain committed
972
  def add_attributed_to(object) do
973
    attributed_to = object["attributedTo"] || object["actor"]
974
    Map.put(object, "attributedTo", attributed_to)
975
  end
lain's avatar
lain committed
976

977
978
979
  # TODO: Revisit this
  def prepare_attachments(%{"type" => "ChatMessage"} = object), do: object

lain's avatar
lain committed
980
  def prepare_attachments(object) do
lain's avatar
lain committed
981
    attachments =
Maksim's avatar
Maksim committed
982
983
      object
      |> Map.get("attachment",