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

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

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

26
  require Logger
27
  require Pleroma.Constants
28

29
30
31
  @doc """
  Modifies an incoming AP object (mastodon format) to our internal format.
  """
32
  def fix_object(object, options \\ []) do
33
    object
34
    |> strip_internal_fields
35
    |> fix_actor
36
    |> fix_url
37
    |> fix_attachments
lain's avatar
lain committed
38
    |> fix_context
39
    |> fix_in_reply_to(options)
lain's avatar
lain committed
40
    |> fix_emoji
41
    |> fix_tag
42
    |> fix_content_map
43
    |> fix_addressing
44
    |> fix_summary
45
    |> fix_type(options)
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
62
63
64
65
66
67
68
    cond do
      is_binary(map[field]) ->
        Map.put(map, field, [map[field]])

      is_nil(map[field]) ->
        Map.put(map, field, [])

      true ->
        map
69
70
71
    end
  end

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

79
    explicit_cc = Enum.filter(to, fn x -> x not in explicit_mentions end)
80
81
82

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

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

91
  def fix_explicit_addressing(object, _explicit_mentions, _followers_collection), do: object
92

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

96
  def fix_explicit_addressing(object) do
97
    explicit_mentions = Utils.determine_explicit_mentions(object)
98

99
100
101
102
    %User{follower_address: follower_collection} =
      object
      |> Containment.get_actor()
      |> User.get_cached_by_ap_id()
103

104
105
106
107
108
109
    explicit_mentions =
      explicit_mentions ++
        [
          Pleroma.Constants.as_public(),
          follower_collection
        ]
110

111
    fix_explicit_addressing(object, explicit_mentions, follower_collection)
lain's avatar
lain committed
112
113
  end

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

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

        true ->
          object
      end
132
    else
133
      object
134
135
136
    end
  end

137
138
  def fix_implicit_addressing(object, _), do: object

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

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

152
  def fix_actor(%{"attributedTo" => actor} = object) do
153
    Map.put(object, "actor", Containment.get_actor(%{"actor" => actor}))
154
155
  end

156
157
158
  def fix_in_reply_to(object, options \\ [])

  def fix_in_reply_to(%{"inReplyTo" => in_reply_to} = object, options)
159
      when not is_nil(in_reply_to) do
160
    in_reply_to_id = prepare_in_reply_to(in_reply_to)
161
    object = Map.put(object, "inReplyToAtomUri", in_reply_to_id)
162
    depth = (options[:depth] || 0) + 1
lain's avatar
lain committed
163

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

182
  def fix_in_reply_to(object, _options), do: object
lain's avatar
lain committed
183

184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
  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
200
  def fix_context(object) do
Haelwenn's avatar
Haelwenn committed
201
202
    context = object["context"] || object["conversation"] || Utils.generate_context_id()

lain's avatar
lain committed
203
    object
Haelwenn's avatar
Haelwenn committed
204
205
    |> Map.put("context", context)
    |> Map.put("conversation", context)
lain's avatar
lain committed
206
207
  end

208
  def fix_attachments(%{"attachment" => attachment} = object) when is_list(attachment) do
lain's avatar
lain committed
209
    attachments =
210
      Enum.map(attachment, fn data ->
211
212
213
214
215
216
217
        media_type = data["mediaType"] || data["mimeType"]
        href = data["url"] || data["href"]
        url = [%{"type" => "Link", "mediaType" => media_type, "href" => href}]

        data
        |> Map.put("mediaType", media_type)
        |> Map.put("url", url)
lain's avatar
lain committed
218
      end)
lain's avatar
lain committed
219

220
    Map.put(object, "attachment", attachments)
221
222
  end

223
  def fix_attachments(%{"attachment" => attachment} = object) when is_map(attachment) do
Maksim's avatar
Maksim committed
224
225
226
    object
    |> Map.put("attachment", [attachment])
    |> fix_attachments()
227
228
  end

229
  def fix_attachments(object), do: object
230

231
  def fix_url(%{"url" => url} = object) when is_map(url) do
232
    Map.put(object, "url", url["href"])
233
234
  end

235
236
  def fix_url(%{"type" => object_type, "url" => url} = object)
      when object_type in ["Video", "Audio"] and is_list(url) do
237
238
    first_element = Enum.at(url, 0)

239
    link_element = Enum.find(url, fn x -> is_map(x) and x["mimeType"] == "text/html" end)
240
241
242
243
244
245
246
247

    object
    |> Map.put("attachment", [first_element])
    |> 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
248
249
250
251
252
253
254
255
256
    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

257
    Map.put(object, "url", url_string)
258
259
260
261
  end

  def fix_url(object), do: object

262
  def fix_emoji(%{"tag" => tags} = object) when is_list(tags) do
lain's avatar
lain committed
263
    emoji =
264
265
      tags
      |> Enum.filter(fn data -> data["type"] == "Emoji" and data["icon"] end)
lain's avatar
lain committed
266
      |> Enum.reduce(%{}, fn data, mapping ->
267
        name = String.trim(data["name"], ":")
lain's avatar
lain committed
268

269
        Map.put(mapping, name, data["icon"]["url"])
lain's avatar
lain committed
270
      end)
lain's avatar
lain committed
271
272
273
274

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

275
    Map.put(object, "emoji", emoji)
lain's avatar
lain committed
276
277
  end

278
279
280
281
  def fix_emoji(%{"tag" => %{"type" => "Emoji"} = tag} = object) do
    name = String.trim(tag["name"], ":")
    emoji = %{name => tag["icon"]["url"]}

282
    Map.put(object, "emoji", emoji)
283
284
  end

285
  def fix_emoji(object), do: object
286

287
  def fix_tag(%{"tag" => tag} = object) when is_list(tag) do
lain's avatar
lain committed
288
    tags =
289
      tag
lain's avatar
lain committed
290
291
      |> Enum.filter(fn data -> data["type"] == "Hashtag" and data["name"] end)
      |> Enum.map(fn data -> String.slice(data["name"], 1..-1) end)
292

293
    Map.put(object, "tag", tag ++ tags)
294
295
  end

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

299
    Map.put(object, "tag", combined)
300
301
  end

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

304
  def fix_tag(object), do: object
305

306
307
308
309
310
  # 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)

311
    Map.put(object, "content", content)
312
313
314
315
  end

  def fix_content_map(object), do: object

316
317
  def fix_type(object, options \\ [])

318
319
  def fix_type(%{"inReplyTo" => reply_id, "name" => _} = object, options)
      when is_binary(reply_id) do
320
    with true <- Federator.allowed_thread_distance?(options[:depth]),
321
         {:ok, %{data: %{"type" => "Question"} = _} = _} <- get_obj_helper(reply_id, options) do
322
323
      Map.put(object, "type", "Answer")
    else
324
      _ -> object
325
326
327
    end
  end

328
  def fix_type(object, _), do: object
329

Maksim's avatar
Maksim committed
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
  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

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

367
368
  def handle_incoming(data, options \\ [])

369
370
  # Flag objects are placed ahead of the ID check because Mastodon 2.8 and earlier send them
  # with nil ID.
371
  def handle_incoming(%{"type" => "Flag", "object" => objects, "actor" => actor} = data, _options) do
372
373
374
375
    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.
376
         %User{} = account <- get_reported(objects),
377
378
         # Remove the reported user from the object list.
         statuses <- Enum.filter(objects, fn ap_id -> ap_id != account.ap_id end) do
379
      %{
380
381
382
383
384
        actor: actor,
        context: context,
        account: account,
        statuses: statuses,
        content: content,
385
        additional: %{"cc" => [account.ap_id]}
386
      }
387
      |> ActivityPub.flag()
388
389
390
    end
  end

391
  # disallow objects with bogus IDs
392
393
  def handle_incoming(%{"id" => nil}, _options), do: :error
  def handle_incoming(%{"id" => ""}, _options), do: :error
394
  # length of https:// = 8, should validate better, but good enough for now.
rinpatch's avatar
rinpatch committed
395
  def handle_incoming(%{"id" => id}, _options) when is_binary(id) and byte_size(id) < 8,
396
    do: :error
397

398
399
400
  # TODO: validate those with a Ecto scheme
  # - tags
  # - emoji
401
402
403
404
  def handle_incoming(
        %{"type" => "Create", "object" => %{"type" => objtype} = object} = data,
        options
      )
405
      when objtype in ["Article", "Event", "Note", "Video", "Page", "Question", "Answer", "Audio"] do
406
    actor = Containment.get_actor(data)
407
408
409
410

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

412
    with nil <- Activity.get_create_by_object_ap_id(object["id"]),
413
         {:ok, %User{} = user} <- User.get_or_fetch_by_ap_id(data["actor"]) do
414
      object = fix_object(object, options)
415

416
417
418
419
      params = %{
        to: data["to"],
        object: object,
        actor: user,
lain's avatar
lain committed
420
        context: object["conversation"],
421
422
        local: false,
        published: data["published"],
lain's avatar
lain committed
423
424
425
        additional:
          Map.take(data, [
            "cc",
426
            "directMessage",
lain's avatar
lain committed
427
428
            "id"
          ])
429
430
      }

431
      with {:ok, created_activity} <- ActivityPub.create(params) do
432
433
434
435
436
437
438
439
440
        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
441
442
443
444
        end

        {:ok, created_activity}
      end
445
    else
lain's avatar
lain committed
446
      %Activity{} = activity -> {:ok, activity}
447
448
449
450
      _e -> :error
    end
  end

451
452
453
454
455
456
457
458
459
460
461
  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
462
463
      reply_depth = (options[:depth] || 0) + 1
      options = Keyword.put(options, :depth, reply_depth)
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
      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

lain's avatar
lain committed
482
  def handle_incoming(
483
484
        %{"type" => "Follow", "object" => followed, "actor" => follower, "id" => id} = data,
        _options
lain's avatar
lain committed
485
      ) do
486
487
488
489
    with %User{local: true} = followed <-
           User.get_cached_by_ap_id(Containment.get_actor(%{"actor" => followed})),
         {:ok, %User{} = follower} <-
           User.get_or_fetch_by_ap_id(Containment.get_actor(%{"actor" => follower})),
490
         {:ok, activity} <- ActivityPub.follow(follower, followed, id, false) do
491
      with deny_follow_blocked <- Pleroma.Config.get([:user, :deny_follow_blocked]),
492
           {_, false} <- {:user_blocked, User.blocks?(followed, follower) && deny_follow_blocked},
493
494
           {_, false} <- {:user_locked, User.locked?(followed)},
           {_, {:ok, follower}} <- {:follow, User.follow(follower, followed)},
495
           {_, {:ok, _}} <-
496
497
             {:follow_state_update, Utils.update_follow_state_for_all(activity, "accept")},
           {:ok, _relationship} <- FollowingRelationship.update(follower, followed, "accept") do
kaniini's avatar
kaniini committed
498
499
        ActivityPub.accept(%{
          to: [follower.ap_id],
500
          actor: followed,
kaniini's avatar
kaniini committed
501
502
503
          object: data,
          local: true
        })
504
505
      else
        {:user_blocked, true} ->
506
          {:ok, _} = Utils.update_follow_state_for_all(activity, "reject")
507
          {:ok, _relationship} = FollowingRelationship.update(follower, followed, "reject")
508
509
510
511
512
513
514
515
516

          ActivityPub.reject(%{
            to: [follower.ap_id],
            actor: followed,
            object: data,
            local: true
          })

        {:follow, {:error, _}} ->
517
          {:ok, _} = Utils.update_follow_state_for_all(activity, "reject")
518
          {:ok, _relationship} = FollowingRelationship.update(follower, followed, "reject")
519
520
521
522
523
524
525
526
527

          ActivityPub.reject(%{
            to: [follower.ap_id],
            actor: followed,
            object: data,
            local: true
          })

        {:user_locked, true} ->
528
          {:ok, _relationship} = FollowingRelationship.update(follower, followed, "pending")
529
          :noop
530
      end
lain's avatar
lain committed
531

532
533
      {:ok, activity}
    else
534
535
      _e ->
        :error
536
537
538
    end
  end

539
  def handle_incoming(
540
        %{"type" => "Accept", "object" => follow_object, "actor" => _actor, "id" => id} = data,
541
        _options
542
      ) do
543
    with actor <- Containment.get_actor(data),
544
         {:ok, %User{} = followed} <- User.get_or_fetch_by_ap_id(actor),
545
         {:ok, follow_activity} <- get_follow_activity(follow_object, followed),
546
         {:ok, follow_activity} <- Utils.update_follow_state_for_all(follow_activity, "accept"),
547
         %User{local: true} = follower <- User.get_cached_by_ap_id(follow_activity.data["actor"]),
548
         {:ok, _relationship} <- FollowingRelationship.update(follower, followed, "accept") do
549
550
551
552
553
      ActivityPub.accept(%{
        to: follow_activity.data["to"],
        type: "Accept",
        actor: followed,
        object: follow_activity.data["id"],
554
555
        local: false,
        activity_id: id
556
      })
557
558
    else
      _e -> :error
559
560
561
562
    end
  end

  def handle_incoming(
563
        %{"type" => "Reject", "object" => follow_object, "actor" => _actor, "id" => id} = data,
564
        _options
565
      ) do
566
    with actor <- Containment.get_actor(data),
567
         {:ok, %User{} = followed} <- User.get_or_fetch_by_ap_id(actor),
568
         {:ok, follow_activity} <- get_follow_activity(follow_object, followed),
569
         {:ok, follow_activity} <- Utils.update_follow_state_for_all(follow_activity, "reject"),
570
         %User{local: true} = follower <- User.get_cached_by_ap_id(follow_activity.data["actor"]),
571
         {:ok, _relationship} <- FollowingRelationship.update(follower, followed, "reject"),
lain's avatar
lain committed
572
         {:ok, activity} <-
573
           ActivityPub.reject(%{
lain's avatar
lain committed
574
             to: follow_activity.data["to"],
575
             type: "Reject",
576
             actor: followed,
lain's avatar
lain committed
577
             object: follow_activity.data["id"],
578
579
             local: false,
             activity_id: id
lain's avatar
lain committed
580
           }) do
581
      {:ok, activity}
582
583
    else
      _e -> :error
584
585
586
    end
  end

587
588
589
590
591
592
593
594
595
596
  @misskey_reactions %{
    "like" => "👍",
    "love" => "❤️",
    "laugh" => "😆",
    "hmm" => "🤔",
    "surprise" => "😮",
    "congrats" => "🎉",
    "angry" => "💢",
    "confused" => "😥",
    "rip" => "😇",
597
598
    "pudding" => "🍮",
    "star" => "⭐"
599
600
  }

lain's avatar
lain committed
601
  @doc "Rewrite misskey likes into EmojiReacts"
602
603
604
605
606
607
608
609
  def handle_incoming(
        %{
          "type" => "Like",
          "_misskey_reaction" => reaction
        } = data,
        options
      ) do
    data
lain's avatar
lain committed
610
    |> Map.put("type", "EmojiReact")
611
    |> Map.put("content", @misskey_reactions[reaction] || reaction)
612
613
614
    |> handle_incoming(options)
  end

615
  def handle_incoming(%{"type" => "Like"} = data, _options) do
616
617
618
    with {_, {:ok, cast_data_sym}} <-
           {:casting_data,
            data |> LikeValidator.cast_data() |> Ecto.Changeset.apply_action(:insert)},
619
         cast_data = ObjectValidator.stringify_keys(Map.from_struct(cast_data_sym)),
620
         :ok <- ObjectValidator.fetch_actor_and_object(cast_data),
lain's avatar
lain committed
621
         {_, {:ok, cast_data}} <- {:ensure_context_presence, ensure_context_presence(cast_data)},
622
         {_, {:ok, cast_data}} <-
lain's avatar
lain committed
623
           {:ensure_recipients_presence, ensure_recipients_presence(cast_data)},
624
         {_, {:ok, activity, _meta}} <-
625
           {:common_pipeline, Pipeline.common_pipeline(cast_data, local: false)} do
lain's avatar
lain committed
626
627
      {:ok, activity}
    else
628
      e -> {:error, e}
lain's avatar
lain committed
629
630
631
    end
  end

632
633
  def handle_incoming(
        %{
lain's avatar
lain committed
634
          "type" => "EmojiReact",
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
          "object" => object_id,
          "actor" => _actor,
          "id" => id,
          "content" => emoji
        } = data,
        _options
      ) do
    with actor <- Containment.get_actor(data),
         {:ok, %User{} = actor} <- User.get_or_fetch_by_ap_id(actor),
         {:ok, object} <- get_obj_helper(object_id),
         {:ok, activity, _object} <-
           ActivityPub.react_with_emoji(actor, object, emoji, activity_id: id, local: false) do
      {:ok, activity}
    else
      _e -> :error
    end
  end

lain's avatar
lain committed
653
  def handle_incoming(
654
655
        %{"type" => "Announce", "object" => object_id, "actor" => _actor, "id" => id} = data,
        _options
lain's avatar
lain committed
656
      ) do
657
    with actor <- Containment.get_actor(data),
658
         {:ok, %User{} = actor} <- User.get_or_fetch_by_ap_id(actor),
659
         {:ok, object} <- get_embedded_obj_helper(object_id, actor),
lain's avatar
lain committed
660
         public <- Visibility.is_public?(data),
661
         {:ok, activity, _object} <- ActivityPub.announce(actor, object, id, false, public) do
lain's avatar
lain committed
662
663
664
665
666
667
      {:ok, activity}
    else
      _e -> :error
    end
  end

lain's avatar
lain committed
668
  def handle_incoming(
669
        %{"type" => "Update", "object" => %{"type" => object_type} = object, "actor" => actor_id} =
670
671
          data,
        _options
672
      )
673
674
675
676
      when object_type in [
             "Person",
             "Application",
             "Service",
677
             "Organization"
678
           ] do
minibikini's avatar
minibikini committed
679
    with %User{ap_id: ^actor_id} = actor <- User.get_cached_by_ap_id(object["id"]) do
lain's avatar
lain committed
680
681
682
      {:ok, new_user_data} = ActivityPub.user_data_from_user_object(object)

      actor
683
      |> User.upgrade_changeset(new_user_data, true)
lain's avatar
lain committed
684
      |> User.update_and_set_cache()
lain's avatar
lain committed
685

lain's avatar
lain committed
686
687
688
689
690
      ActivityPub.update(%{
        local: false,
        to: data["to"] || [],
        cc: data["cc"] || [],
        object: object,
691
692
        actor: actor_id,
        activity_id: data["id"]
lain's avatar
lain committed
693
      })
lain's avatar
lain committed
694
695
696
697
698
699
700
    else
      e ->
        Logger.error(e)
        :error
    end
  end

701
702
703
704
705
  # TODO: We presently assume that any actor on the same origin domain as the object being
  # deleted has the rights to delete that object.  A better way to validate whether or not
  # the object should be deleted is to refetch the object URI, which should return either
  # an error or a tombstone.  This would allow us to verify that a deletion actually took
  # place.
lain's avatar
lain committed
706
  def handle_incoming(
707
        %{"type" => "Delete", "object" => object_id, "actor" => actor, "id" => id} = data,
708
        _options
lain's avatar
lain committed
709
      ) do
lain's avatar
lain committed
710
    object_id = Utils.get_ap_id(object_id)
lain's avatar
lain committed
711

712
    with actor <- Containment.get_actor(data),
713
         {:ok, %User{} = actor} <- User.get_or_fetch_by_ap_id(actor),
714
         {:ok, object} <- get_obj_helper(object_id),
715
         :ok <- Containment.contain_origin(actor.ap_id, object.data),
716
717
         {:ok, activity} <-
           ActivityPub.delete(object, local: false, activity_id: id, actor: actor.ap_id) do
lain's avatar
lain committed
718
719
      {:ok, activity}
    else
720
721
722
      nil ->
        case User.get_cached_by_ap_id(object_id) do
          %User{ap_id: ^actor} = user ->
723
            User.delete(user)
724
725
726
727
728
729
730

          nil ->
            :error
        end

      _e ->
        :error
lain's avatar
lain committed
731
732
733
    end
  end

734
  def handle_incoming(
735
736
        %{
          "type" => "Undo",
737
          "object" => %{"type" => "Announce", "object" => object_id},
Maksim's avatar
Maksim committed
738
          "actor" => _actor,
739
          "id" => id
740
741
        } = data,
        _options
742
      ) do
743
    with actor <- Containment.get_actor(data),
744
         {:ok, %User{} = actor} <- User.get_or_fetch_by_ap_id(actor),
745
         {:ok, object} <- get_obj_helper(object_id),
746
         {:ok, activity, _} <- ActivityPub.unannounce(actor, object, id, false) do
747
748
      {:ok, activity}
    else
Thog's avatar
Thog committed
749
      _e -> :error
750
751
752
    end
  end

normandy's avatar
normandy committed
753
754
755
756
757
758
  def handle_incoming(
        %{
          "type" => "Undo",
          "object" => %{"type" => "Follow", "object" => followed},
          "actor" => follower,
          "id" => id
759
760
        } = _data,
        _options
normandy's avatar
normandy committed
761
      ) do
normandy's avatar
normandy committed
762
    with %User{local: true} = followed <- User.get_cached_by_ap_id(followed),
763
         {:ok, %User{} = follower} <- User.get_or_fetch_by_ap_id(follower),
normandy's avatar
normandy committed
764
         {:ok, activity} <- ActivityPub.unfollow(follower, followed, id, false) do
normandy's avatar
normandy committed
765
766
767
      User.unfollow(follower, followed)
      {:ok, activity}
    else
Maksim's avatar
Maksim committed
768
      _e -> :error
normandy's avatar
normandy committed
769
770
771
    end
  end

772
773
774
  def handle_incoming(
        %{
          "type" => "Undo",
lain's avatar
lain committed
775
          "object" => %{"type" => "EmojiReact", "id" => reaction_activity_id},
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
          "actor" => _actor,
          "id" => id
        } = data,
        _options
      ) do
    with actor <- Containment.get_actor(data),
         {:ok, %User{} = actor} <- User.get_or_fetch_by_ap_id(actor),
         {:ok, activity, _} <-
           ActivityPub.unreact_with_emoji(actor, reaction_activity_id,
             activity_id: id,
             local: false
           ) do
      {:ok, activity}
    else
      _e -> :error
    end
  end

normandy's avatar
normandy committed
794
795
796
797
798
799
  def handle_incoming(
        %{
          "type" => "Undo",
          "object" => %{"type" => "Block", "object" => blocked},
          "actor" => blocker,
          "id" => id
800
801
        } = _data,
        _options
normandy's avatar
normandy committed
802
      ) do
803
    with %User{local: true} = blocked <- User.get_cached_by_ap_id(blocked),
804
         {:ok, %User{} = blocker} <- User.get_or_fetch_by_ap_id(blocker),
normandy's avatar
normandy committed
805
         {:ok, activity} <- ActivityPub.unblock(blocker, blocked, id, false) do
normandy's avatar
normandy committed
806
      User.unblock(blocker, blocked)
normandy's avatar
normandy committed
807
808
      {:ok, activity}
    else
Maksim's avatar
Maksim committed
809
      _e -> :error
normandy's avatar
normandy committed
810
811
812
    end
  end

813
  def handle_incoming(
814
815
        %{"type" => "Block", "object" => blocked, "actor" => blocker, "id" => id} = _data,
        _options
816
      ) do
817
    with %User{local: true} = blocked = User.get_cached_by_ap_id(blocked),
0x1C3B00DA's avatar
0x1C3B00DA committed
818
         {:ok, %User{} = blocker} = User.get_or_fetch_by_ap_id(blocker),
normandy's avatar
normandy committed
819
         {:ok, activity} <- ActivityPub.block(blocker, blocked, id, false) do
820
      User.unfollow(blocker, blocked)
821
      User.block(blocker, blocked)
normandy's avatar
normandy committed
822
823
      {:ok, activity}
    else
Maksim's avatar
Maksim committed
824
      _e -> :error
normandy's avatar
normandy committed
825
826
    end
  end
827

Thog's avatar
Thog committed
828
829
830
831
  def handle_incoming(
        %{
          "type" => "Undo",
          "object" => %{"type" => "Like", "object" => object_id},
Maksim's avatar
Maksim committed
832
          "actor" => _actor,
Thog's avatar
Thog committed
833
          "id" => id
834
835
        } = data,
        _options
Thog's avatar
Thog committed
836
      ) do
837
    with actor <- Containment.get_actor(data),
838
         {:ok, %User{} = actor} <- User.get_or_fetch_by_ap_id(actor),
839
         {:ok, object} <- get_obj_helper(object_id),
Thog's avatar
Thog committed
840
841
842
         {:ok, activity, _, _} <- ActivityPub.unlike(actor, object, id, false) do
      {:ok, activity}
    else
Thog's avatar
Thog committed
843
      _e -> :error
Thog's avatar
Thog committed
844
845
846
    end
  end

847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
  # For Undos that don't have the complete object attached, try to find it in our database.
  def handle_incoming(
        %{
          "type" => "Undo",
          "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)
    else
      _e -> :error
    end
  end

minibikini's avatar
minibikini committed
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
  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

883
  def handle_incoming(_, _), do: :error
884

885
  @spec get_obj_helper(String.t(), Keyword.t()) :: {:ok, Object.t()} | nil
886
  def get_obj_helper(id, options \\ []) do
Maksim's avatar
Maksim committed
887
888
889
    case Object.normalize(id, true, options) do
      %Object{} = object -> {:ok, object}
      _ -> nil
890
    end
891
892
  end

893
  @spec get_embedded_obj_helper(String.t() | Object.t(), User.t()) :: {:ok, Object.t()} | nil
Thibaut Girka's avatar
Thibaut Girka committed
894
  def get_embedded_obj_helper(%{"attributedTo" => attributed_to, "id" => object_id} = data, %User{
895
896
        ap_id: ap_id
      })
Thibaut Girka's avatar
Thibaut Girka committed
897
      when attributed_to == ap_id do
898
899
900
901
902
    with {:ok, activity} <-
           handle_incoming(%{
             "type" => "Create",
             "to" => data["to"],
             "cc" => data["cc"],
Thibaut Girka's avatar
Thibaut Girka committed
903
             "actor" => attributed_to,
904
905
906
907
908
909
910
911
912
913
914
915
             "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

916
917
918
919
  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)
920
921
922
923
    else
      _e -> object
    end
  end
lain's avatar
lain committed
924

925
926
  def set_reply_to_uri(obj), do: obj

927
928
929
930
  @doc """
  Serialized Mastodon-compatible `replies` collection containing _self-replies_.
  Based on Mastodon's ActivityPub::NoteSerializer#replies.
  """
931
  def set_replies(obj_data) do
932
    replies_uris =
Ivan Tashkinov's avatar
Ivan Tashkinov committed
933
934
      with limit when limit > 0 <-
             Pleroma.Config.get([:activitypub, :note_replies_output_limit], 0),
935
936
937