transmogrifier.ex 32.2 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.FollowingRelationship
13
  alias Pleroma.Maps
lain's avatar
lain committed
14
  alias Pleroma.Notification
Haelwenn's avatar
Haelwenn committed
15
  alias Pleroma.Object
rinpatch's avatar
rinpatch committed
16
  alias Pleroma.Object.Containment
Haelwenn's avatar
Haelwenn committed
17
  alias Pleroma.Repo
18
  alias Pleroma.User
Haelwenn's avatar
Haelwenn committed
19
  alias Pleroma.Web.ActivityPub.ActivityPub
20
  alias Pleroma.Web.ActivityPub.Builder
21
22
  alias Pleroma.Web.ActivityPub.ObjectValidator
  alias Pleroma.Web.ActivityPub.Pipeline
Haelwenn's avatar
Haelwenn committed
23
  alias Pleroma.Web.ActivityPub.Utils
lain's avatar
lain committed
24
  alias Pleroma.Web.ActivityPub.Visibility
25
  alias Pleroma.Web.Federator
26
  alias Pleroma.Workers.TransmogrifierWorker
27

lain's avatar
lain committed
28
29
  import Ecto.Query

30
  require Logger
31
  require Pleroma.Constants
32

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

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

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

62
  def fix_summary(object), do: Map.put(object, "summary", "")
63
64

  def fix_addressing_list(map, field) do
65
66
    addrs = map[field]

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

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

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

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

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

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

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

98
  def fix_explicit_addressing(object, _explicit_mentions, _followers_collection), do: object
99

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

103
  def fix_explicit_addressing(object) do
104
    explicit_mentions = Utils.determine_explicit_mentions(object)
105

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

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

118
    fix_explicit_addressing(object, explicit_mentions, follower_collection)
lain's avatar
lain committed
119
120
  end

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

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

        true ->
          object
      end
139
    else
140
      object
141
142
143
    end
  end

144
145
  def fix_implicit_addressing(object, _), do: object

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

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

159
  def fix_actor(%{"attributedTo" => actor} = object) do
160
    Map.put(object, "actor", Containment.get_actor(%{"actor" => actor}))
161
162
  end

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

  def fix_in_reply_to(%{"inReplyTo" => in_reply_to} = object, options)
166
      when not is_nil(in_reply_to) do
167
    in_reply_to_id = prepare_in_reply_to(in_reply_to)
168
    object = Map.put(object, "inReplyToAtomUri", in_reply_to_id)
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
177
        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"])
178
        |> Map.drop(["conversation"])
179
      else
180
        e ->
feld's avatar
feld committed
181
          Logger.error("Couldn't fetch #{inspect(in_reply_to_id)}, error: #{inspect(e)}")
182
183
184
185
          object
      end
    else
      object
lain's avatar
lain committed
186
187
    end
  end
lain's avatar
lain committed
188

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

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

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

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

      true ->
        ""
    end
  end

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

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

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

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

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

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

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

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

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

270
  def fix_attachments(object), do: object
271

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

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

Haelwenn's avatar
Haelwenn committed
282
283
284
285
286
        is_map(x) and String.starts_with?(media_type, ["audio/", "video/"])
      end)

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

    object
Haelwenn's avatar
Haelwenn committed
289
    |> Map.put("attachment", [attachment])
290
291
292
293
294
    |> 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
295
296
297
298
299
300
301
302
303
    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

304
    Map.put(object, "url", url_string)
305
306
307
308
  end

  def fix_url(object), do: object

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

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

    # we merge mastodon and pleroma emoji into a single mapping, to allow for both wire formats
    emoji = Map.merge(object["emoji"] || %{}, emoji)

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

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

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

332
  def fix_emoji(object), do: object
333

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

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

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

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

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

351
  def fix_tag(object), do: object
352

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

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

  def fix_content_map(object), do: object

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

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

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

Maksim's avatar
Maksim committed
377
378
379
380
381
382
383
384
  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
385
386
  end

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

Maksim's avatar
Maksim committed
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
  defp mastodon_follow_hack(%{"id" => id, "actor" => follower_id}, followed) do
    with true <- id =~ "follows",
         %User{local: true} = follower <- User.get_cached_by_ap_id(follower_id),
         %Activity{} = activity <- Utils.fetch_latest_follow(follower, followed) do
      {:ok, activity}
    else
      _ -> {:error, nil}
    end
  end

  defp mastodon_follow_hack(_, _), do: {:error, nil}

  defp get_follow_activity(follow_object, followed) do
    with object_id when not is_nil(object_id) <- Utils.get_ap_id(follow_object),
         {_, %Activity{} = activity} <- {:activity, Activity.get_by_ap_id(object_id)} do
      {:ok, activity}
    else
      # Can't find the activity. This might a Mastodon 2.3 "Accept"
      {:activity, nil} ->
        mastodon_follow_hack(follow_object, followed)

      _ ->
        {:error, nil}
    end
  end

415
416
417
418
419
420
421
422
423
424
425
  # 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

426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
  # 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

449
450
  def handle_incoming(data, options \\ [])

451
452
  # Flag objects are placed ahead of the ID check because Mastodon 2.8 and earlier send them
  # with nil ID.
453
  def handle_incoming(%{"type" => "Flag", "object" => objects, "actor" => actor} = data, _options) do
454
455
456
457
    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.
458
         %User{} = account <- get_reported(objects),
459
460
         # Remove the reported user from the object list.
         statuses <- Enum.filter(objects, fn ap_id -> ap_id != account.ap_id end) do
461
      %{
462
463
464
465
466
        actor: actor,
        context: context,
        account: account,
        statuses: statuses,
        content: content,
467
        additional: %{"cc" => [account.ap_id]}
468
      }
469
      |> ActivityPub.flag()
470
471
472
    end
  end

473
  # disallow objects with bogus IDs
474
475
  def handle_incoming(%{"id" => nil}, _options), do: :error
  def handle_incoming(%{"id" => ""}, _options), do: :error
476
  # length of https:// = 8, should validate better, but good enough for now.
rinpatch's avatar
rinpatch committed
477
  def handle_incoming(%{"id" => id}, _options) when is_binary(id) and byte_size(id) < 8,
478
    do: :error
479

480
481
482
  # TODO: validate those with a Ecto scheme
  # - tags
  # - emoji
483
484
485
486
  def handle_incoming(
        %{"type" => "Create", "object" => %{"type" => objtype} = object} = data,
        options
      )
Haelwenn's avatar
Haelwenn committed
487
      when objtype in ["Article", "Event", "Note", "Video", "Page", "Audio"] do
488
    actor = Containment.get_actor(data)
489

490
    with nil <- Activity.get_create_by_object_ap_id(object["id"]),
491
492
493
494
495
496
497
498
         {: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
499
500
501
502
503
504
505
506
507
        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
508
509
510
511
        end

        {:ok, created_activity}
      end
512
    else
lain's avatar
lain committed
513
      %Activity{} = activity -> {:ok, activity}
514
515
516
517
      _e -> :error
    end
  end

518
519
520
521
522
523
524
525
526
527
528
  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
529
530
      reply_depth = (options[:depth] || 0) + 1
      options = Keyword.put(options, :depth, reply_depth)
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
      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

549
  def handle_incoming(
550
        %{"type" => "Accept", "object" => follow_object, "actor" => _actor, "id" => id} = data,
551
        _options
552
      ) do
553
    with actor <- Containment.get_actor(data),
554
         {:ok, %User{} = followed} <- User.get_or_fetch_by_ap_id(actor),
555
         {:ok, follow_activity} <- get_follow_activity(follow_object, followed),
556
         {:ok, follow_activity} <- Utils.update_follow_state_for_all(follow_activity, "accept"),
557
         %User{local: true} = follower <- User.get_cached_by_ap_id(follow_activity.data["actor"]),
558
         {:ok, _relationship} <- FollowingRelationship.update(follower, followed, :follow_accept) do
559
560
561
      User.update_follower_count(followed)
      User.update_following_count(follower)

562
563
      Notification.update_notification_type(followed, follow_activity)

564
565
566
567
568
      ActivityPub.accept(%{
        to: follow_activity.data["to"],
        type: "Accept",
        actor: followed,
        object: follow_activity.data["id"],
569
570
        local: false,
        activity_id: id
571
      })
572
    else
573
574
      _e ->
        :error
575
576
577
578
    end
  end

  def handle_incoming(
579
        %{"type" => "Reject", "object" => follow_object, "actor" => _actor, "id" => id} = data,
580
        _options
581
      ) do
582
    with actor <- Containment.get_actor(data),
583
         {:ok, %User{} = followed} <- User.get_or_fetch_by_ap_id(actor),
584
         {:ok, follow_activity} <- get_follow_activity(follow_object, followed),
585
         {:ok, follow_activity} <- Utils.update_follow_state_for_all(follow_activity, "reject"),
586
         %User{local: true} = follower <- User.get_cached_by_ap_id(follow_activity.data["actor"]),
587
         {:ok, _relationship} <- FollowingRelationship.update(follower, followed, :follow_reject),
lain's avatar
lain committed
588
         {:ok, activity} <-
589
           ActivityPub.reject(%{
lain's avatar
lain committed
590
             to: follow_activity.data["to"],
591
             type: "Reject",
592
             actor: followed,
lain's avatar
lain committed
593
             object: follow_activity.data["id"],
594
595
             local: false,
             activity_id: id
lain's avatar
lain committed
596
           }) do
597
      {:ok, activity}
598
599
    else
      _e -> :error
600
601
602
    end
  end

603
604
605
606
607
608
609
610
611
612
  @misskey_reactions %{
    "like" => "👍",
    "love" => "❤️",
    "laugh" => "😆",
    "hmm" => "🤔",
    "surprise" => "😮",
    "congrats" => "🎉",
    "angry" => "💢",
    "confused" => "😥",
    "rip" => "😇",
613
614
    "pudding" => "🍮",
    "star" => "⭐"
615
616
  }

lain's avatar
lain committed
617
  @doc "Rewrite misskey likes into EmojiReacts"
618
619
620
621
622
623
624
625
  def handle_incoming(
        %{
          "type" => "Like",
          "_misskey_reaction" => reaction
        } = data,
        options
      ) do
    data
lain's avatar
lain committed
626
    |> Map.put("type", "EmojiReact")
627
    |> Map.put("content", @misskey_reactions[reaction] || reaction)
628
629
630
    |> handle_incoming(options)
  end

Haelwenn's avatar
Haelwenn committed
631
  def handle_incoming(
Haelwenn's avatar
Haelwenn committed
632
        %{"type" => "Create", "object" => %{"type" => objtype} = object} = data,
Haelwenn's avatar
Haelwenn committed
633
        _options
Haelwenn's avatar
Haelwenn committed
634
635
      )
      when objtype in ["Question", "Answer"] do
Haelwenn's avatar
Haelwenn committed
636
637
638
639
640
641
642
643
644
645
646
    data =
      data
      |> Map.put("object", fix_object(object))
      |> fix_addressing()

    with {:ok, %User{}} <- ObjectValidator.fetch_actor(data),
         {:ok, activity, _} <- Pipeline.common_pipeline(data, local: false) do
      {:ok, activity}
    end
  end

lain's avatar
lain committed
647
648
  def handle_incoming(
        %{"type" => "Create", "object" => %{"type" => "ChatMessage"}} = data,
649
650
        _options
      ) do
651
652
653
    with {:ok, %User{}} <- ObjectValidator.fetch_actor(data),
         {:ok, activity, _} <- Pipeline.common_pipeline(data, local: false) do
      {:ok, activity}
654
655
    end
  end
lain's avatar
lain committed
656

657
  def handle_incoming(%{"type" => type} = data, _options)
658
      when type in ~w{Like EmojiReact Announce} do
lain's avatar
lain committed
659
660
661
    with :ok <- ObjectValidator.fetch_actor_and_object(data),
         {:ok, activity, _meta} <-
           Pipeline.common_pipeline(data, local: false) do
lain's avatar
lain committed
662
663
      {:ok, activity}
    else
664
      e -> {:error, e}
lain's avatar
lain committed
665
666
667
    end
  end

lain's avatar
lain committed
668
  def handle_incoming(
669
        %{"type" => type} = data,
670
        _options
671
      )
672
      when type in ~w{Update Block Follow} do
673
674
675
    with {:ok, %User{}} <- ObjectValidator.fetch_actor(data),
         {:ok, activity, _} <- Pipeline.common_pipeline(data, local: false) do
      {:ok, activity}
lain's avatar
lain committed
676
677
678
    end
  end

lain's avatar
lain committed
679
  def handle_incoming(
680
        %{"type" => "Delete"} = data,
681
        _options
lain's avatar
lain committed
682
      ) do
683
    with {:ok, activity, _} <- Pipeline.common_pipeline(data, local: false) do
lain's avatar
lain committed
684
      {:ok, activity}
685
686
687
    else
      {:error, {:validate_object, _}} = e ->
        # Check if we have a create activity for this
688
        with {:ok, object_id} <- ObjectValidators.ObjectID.cast(data["object"]),
689
690
691
692
693
694
695
696
697
             %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
698
699
700
    end
  end

normandy's avatar
normandy committed
701
702
703
704
705
706
  def handle_incoming(
        %{
          "type" => "Undo",
          "object" => %{"type" => "Follow", "object" => followed},
          "actor" => follower,
          "id" => id
707
708
        } = _data,
        _options
normandy's avatar
normandy committed
709
      ) do
normandy's avatar
normandy committed
710
    with %User{local: true} = followed <- User.get_cached_by_ap_id(followed),
711
         {:ok, %User{} = follower} <- User.get_or_fetch_by_ap_id(follower),
normandy's avatar
normandy committed
712
         {:ok, activity} <- ActivityPub.unfollow(follower, followed, id, false) do
normandy's avatar
normandy committed
713
714
715
      User.unfollow(follower, followed)
      {:ok, activity}
    else
Maksim's avatar
Maksim committed
716
      _e -> :error
normandy's avatar
normandy committed
717
718
719
    end
  end

720
721
722
  def handle_incoming(
        %{
          "type" => "Undo",
723
          "object" => %{"type" => type}
724
725
        } = data,
        _options
726
      )
727
      when type in ["Like", "EmojiReact", "Announce", "Block"] do
728
    with {:ok, activity, _} <- Pipeline.common_pipeline(data, local: false) do
729
730
731
732
      {:ok, activity}
    end
  end

733
  # For Undos that don't have the complete object attached, try to find it in our database.
normandy's avatar
normandy committed
734
735
736
  def handle_incoming(
        %{
          "type" => "Undo",
737
738
739
740
741
742
743
744
745
          "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
746
    else
Maksim's avatar
Maksim committed
747
      _e -> :error
normandy's avatar
normandy committed
748
749
750
    end
  end

minibikini's avatar
minibikini committed
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
  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

769
  def handle_incoming(_, _), do: :error
770

771
  @spec get_obj_helper(String.t(), Keyword.t()) :: {:ok, Object.t()} | nil
772
  def get_obj_helper(id, options \\ []) do
Maksim's avatar
Maksim committed
773
774
775
    case Object.normalize(id, true, options) do
      %Object{} = object -> {:ok, object}
      _ -> nil
776
    end
777
778
  end

779
  @spec get_embedded_obj_helper(String.t() | Object.t(), User.t()) :: {:ok, Object.t()} | nil
Thibaut Girka's avatar
Thibaut Girka committed
780
  def get_embedded_obj_helper(%{"attributedTo" => attributed_to, "id" => object_id} = data, %User{
781
782
        ap_id: ap_id
      })
Thibaut Girka's avatar
Thibaut Girka committed
783
      when attributed_to == ap_id do
784
785
786
787
788
    with {:ok, activity} <-
           handle_incoming(%{
             "type" => "Create",
             "to" => data["to"],
             "cc" => data["cc"],
Thibaut Girka's avatar
Thibaut Girka committed
789
             "actor" => attributed_to,
790
791
792
793
794
795
796
797
798
799
800
801
             "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

802
803
804
805
  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)
806
807
808
809
    else
      _e -> object
    end
  end
lain's avatar
lain committed
810

811
812
  def set_reply_to_uri(obj), do: obj

813
814
815
816
  @doc """
  Serialized Mastodon-compatible `replies` collection containing _self-replies_.
  Based on Mastodon's ActivityPub::NoteSerializer#replies.
  """
817
  def set_replies(obj_data) do
818
    replies_uris =
Ivan Tashkinov's avatar
Ivan Tashkinov committed
819
820
      with limit when limit > 0 <-
             Pleroma.Config.get([:activitypub, :note_replies_output_limit], 0),
821
822
823
824
           %Object{} = object <- Object.get_cached_by_ap_id(obj_data["id"]) do
        object
        |> Object.self_replies()
        |> select([o], fragment("?->>'id'", o.data))
825
826
        |> limit(^limit)
        |> Repo.all()
Ivan Tashkinov's avatar
Ivan Tashkinov committed
827
828
      else
        _ -> []
829
830
      end

Ivan Tashkinov's avatar
Ivan Tashkinov committed
831
    set_replies(obj_data, replies_uris)
832
833
  end

Ivan Tashkinov's avatar
Ivan Tashkinov committed
834
  defp set_replies(obj, []) do
835
836
837
838
839
840
    obj
  end

  defp set_replies(obj, replies_uris) do
    replies_collection = %{
      "type" => "Collection",
841
      "items" => replies_uris
842
843
844
845
846
    }

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

Ivan Tashkinov's avatar
Ivan Tashkinov committed
847
848
849
  def replies(%{"replies" => %{"first" => %{"items" => items}}}) when not is_nil(items) do
    items
  end
850

Ivan Tashkinov's avatar
Ivan Tashkinov committed
851
852
  def replies(%{"replies" => %{"items" => items}}) when not is_nil(items) do
    items
853
854
855
856
  end

  def replies(_), do: []

857
  # Prepares the object of an outgoing create activity.
lain's avatar
lain committed
858
859
  def prepare_object(object) do
    object
lain's avatar
lain committed
860
    |> set_sensitive
lain's avatar
lain committed
861
    |> add_hashtags
lain's avatar
lain committed
862
    |> add_mention_tags
lain's avatar
lain committed
863
    |> add_emoji_tags
lain's avatar
lain committed
864
    |> add_attributed_to
lain's avatar
lain committed
865
    |> prepare_attachments
lain's avatar
lain committed
866
    |> set_conversation
867
    |> set_reply_to_uri
868
    |> set_replies
869
870
    |> strip_internal_fields
    |> strip_internal_tags
871
    |> set_type
lain's avatar
lain committed
872
873
  end

feld's avatar
feld committed
874
875
876
877
  #  @doc
  #  """
  #  internal -> Mastodon
  #  """
lain's avatar
lain committed
878

879
880
  def prepare_outgoing(%{"type" => activity_type, "object" => object_id} = data)
      when activity_type in ["Create", "Listen"] do
lain's avatar
lain committed
881
    object =
minibikini's avatar
minibikini committed
882
883
884
      object_id
      |> Object.normalize()
      |> Map.get(:data)
lain's avatar
lain committed
885
886
887
888
889
      |> prepare_object

    data =
      data
      |> Map.put("object", object)
lain's avatar
lain committed
890
      |> Map.merge(Utils.make_json_ld_header())
minibikini's avatar
minibikini committed
891
      |> Map.delete("bcc")
lain's avatar
lain committed
892
893
894
895

    {:ok, data}
  end

896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
  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
917
918
919
  # Mastodon Accept/Reject requires a non-normalized object containing the actor URIs,
  # because of course it does.
  def prepare_outgoing(%{"type" => "Accept"} = data) do
920
    with follow_activity <- Activity.normalize(data["object"]) do
kaniini's avatar
kaniini committed
921
922
923
924
925
926
927
928
929
930
      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
931
        |> Map.merge(Utils.make_json_ld_header())
kaniini's avatar
kaniini committed
932
933
934
935
936

      {:ok, data}
    end
  end

937
  def prepare_outgoing(%{"type" => "Reject"} = data) do
938
    with follow_activity <- Activity.normalize(data["object"]) do
939
940
941
942
943
944
945
946
947
948
      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
949
        |> Map.merge(Utils.make_json_ld_header())
950
951
952
953
954

      {:ok, data}
    end
  end

feld's avatar
feld committed
955
  def prepare_outgoing(%{"type" => _type} = data) do
lain's avatar
lain committed
956
957
    data =
      data
958
      |> strip_internal_fields
lain's avatar
lain committed
959
      |> maybe_fix_object_url
lain's avatar
lain committed
960
      |> Map.merge(Utils.make_json_ld_header())
961
962
963
964

    {:ok, data}
  end

965
966
967
968
969
970
  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)
971
    else
972
973
974
975
976
977
      {:fetch, e} ->
        Logger.error("Couldn't fetch #{object} #{inspect(e)}")
        data

      _ ->
        data
978
979
980
    end
  end

Maksim's avatar