transmogrifier.ex 36.6 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.FollowingRelationship
Haelwenn's avatar
Haelwenn committed
12
  alias Pleroma.Object
rinpatch's avatar
rinpatch committed
13
  alias Pleroma.Object.Containment
Haelwenn's avatar
Haelwenn committed
14
  alias Pleroma.Repo
15
  alias Pleroma.User
Haelwenn's avatar
Haelwenn committed
16
  alias Pleroma.Web.ActivityPub.ActivityPub
17
18
  alias Pleroma.Web.ActivityPub.ObjectValidator
  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)
Maksim's avatar
Maksim committed
46
    |> fix_content
47
48
49
  end

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

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

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

  def fix_addressing_list(map, field) do
61
62
63
64
65
66
67
68
69
    cond do
      is_binary(map[field]) ->
        Map.put(map, field, [map[field]])

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

      true ->
        map
70
71
72
    end
  end

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

209
210
211
212
213
214
  defp add_if_present(map, _key, nil), do: map

  defp add_if_present(map, key, value) do
    Map.put(map, key, value)
  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
        url =
          cond do
            is_list(data["url"]) -> List.first(data["url"])
            is_map(data["url"]) -> data["url"]
            true -> nil
          end
224

225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
        media_type =
          cond do
            is_map(url) && is_binary(url["mediaType"]) -> url["mediaType"]
            is_binary(data["mediaType"]) -> data["mediaType"]
            is_binary(data["mimeType"]) -> data["mimeType"]
            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"]
          end

        attachment_url =
          %{"href" => href}
          |> add_if_present("mediaType", media_type)
          |> add_if_present("type", Map.get(url || %{}, "type"))

        %{"url" => [attachment_url]}
        |> add_if_present("mediaType", media_type)
        |> add_if_present("type", data["type"])
        |> add_if_present("name", data["name"])
lain's avatar
lain committed
249
      end)
lain's avatar
lain committed
250

251
    Map.put(object, "attachment", attachments)
252
253
  end

254
  def fix_attachments(%{"attachment" => attachment} = object) when is_map(attachment) do
Maksim's avatar
Maksim committed
255
256
257
    object
    |> Map.put("attachment", [attachment])
    |> fix_attachments()
258
259
  end

260
  def fix_attachments(object), do: object
261

262
  def fix_url(%{"url" => url} = object) when is_map(url) do
263
    Map.put(object, "url", url["href"])
264
265
  end

266
267
  def fix_url(%{"type" => object_type, "url" => url} = object)
      when object_type in ["Video", "Audio"] and is_list(url) do
268
269
    first_element = Enum.at(url, 0)

270
    link_element = Enum.find(url, fn x -> is_map(x) and x["mimeType"] == "text/html" end)
271
272
273
274
275
276
277
278

    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
279
280
281
282
283
284
285
286
287
    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

288
    Map.put(object, "url", url_string)
289
290
291
292
  end

  def fix_url(object), do: object

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

300
        Map.put(mapping, name, data["icon"]["url"])
lain's avatar
lain committed
301
      end)
lain's avatar
lain committed
302
303
304
305

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

306
    Map.put(object, "emoji", emoji)
lain's avatar
lain committed
307
308
  end

309
310
311
312
  def fix_emoji(%{"tag" => %{"type" => "Emoji"} = tag} = object) do
    name = String.trim(tag["name"], ":")
    emoji = %{name => tag["icon"]["url"]}

313
    Map.put(object, "emoji", emoji)
314
315
  end

316
  def fix_emoji(object), do: object
317

318
  def fix_tag(%{"tag" => tag} = object) when is_list(tag) do
lain's avatar
lain committed
319
    tags =
320
      tag
lain's avatar
lain committed
321
322
      |> Enum.filter(fn data -> data["type"] == "Hashtag" and data["name"] end)
      |> Enum.map(fn data -> String.slice(data["name"], 1..-1) end)
323

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

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

330
    Map.put(object, "tag", combined)
331
332
  end

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

335
  def fix_tag(object), do: object
336

337
338
339
340
341
  # 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)

342
    Map.put(object, "content", content)
343
344
345
346
  end

  def fix_content_map(object), do: object

347
348
  def fix_type(object, options \\ [])

349
350
  def fix_type(%{"inReplyTo" => reply_id, "name" => _} = object, options)
      when is_binary(reply_id) do
351
    with true <- Federator.allowed_thread_distance?(options[:depth]),
352
         {:ok, %{data: %{"type" => "Question"} = _} = _} <- get_obj_helper(reply_id, options) do
353
354
      Map.put(object, "type", "Answer")
    else
355
      _ -> object
356
357
358
    end
  end

359
  def fix_type(object, _), do: object
360

Maksim's avatar
Maksim committed
361
362
363
364
365
366
367
368
  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
369
370
  end

Maksim's avatar
Maksim committed
371
  defp fix_content(object), do: object
Maksim's avatar
Maksim committed
372

Maksim's avatar
Maksim committed
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
  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

399
400
401
402
403
404
405
406
407
408
409
  # 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

410
411
  def handle_incoming(data, options \\ [])

412
413
  # Flag objects are placed ahead of the ID check because Mastodon 2.8 and earlier send them
  # with nil ID.
414
  def handle_incoming(%{"type" => "Flag", "object" => objects, "actor" => actor} = data, _options) do
415
416
417
418
    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.
419
         %User{} = account <- get_reported(objects),
420
421
         # Remove the reported user from the object list.
         statuses <- Enum.filter(objects, fn ap_id -> ap_id != account.ap_id end) do
422
      %{
423
424
425
426
427
        actor: actor,
        context: context,
        account: account,
        statuses: statuses,
        content: content,
428
        additional: %{"cc" => [account.ap_id]}
429
      }
430
      |> ActivityPub.flag()
431
432
433
    end
  end

434
  # disallow objects with bogus IDs
435
436
  def handle_incoming(%{"id" => nil}, _options), do: :error
  def handle_incoming(%{"id" => ""}, _options), do: :error
437
  # length of https:// = 8, should validate better, but good enough for now.
rinpatch's avatar
rinpatch committed
438
  def handle_incoming(%{"id" => id}, _options) when is_binary(id) and byte_size(id) < 8,
439
    do: :error
440

441
442
443
  # TODO: validate those with a Ecto scheme
  # - tags
  # - emoji
444
445
446
447
  def handle_incoming(
        %{"type" => "Create", "object" => %{"type" => objtype} = object} = data,
        options
      )
448
      when objtype in ["Article", "Event", "Note", "Video", "Page", "Question", "Answer", "Audio"] do
449
    actor = Containment.get_actor(data)
450
451
452
453

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

455
    with nil <- Activity.get_create_by_object_ap_id(object["id"]),
456
         {:ok, %User{} = user} <- User.get_or_fetch_by_ap_id(data["actor"]) do
457
      object = fix_object(object, options)
458

459
460
461
462
      params = %{
        to: data["to"],
        object: object,
        actor: user,
lain's avatar
lain committed
463
        context: object["conversation"],
464
465
        local: false,
        published: data["published"],
lain's avatar
lain committed
466
467
468
        additional:
          Map.take(data, [
            "cc",
469
            "directMessage",
lain's avatar
lain committed
470
471
            "id"
          ])
472
473
      }

474
      with {:ok, created_activity} <- ActivityPub.create(params) do
475
476
477
478
479
480
481
482
483
        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
484
485
486
487
        end

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

494
495
496
497
498
499
500
501
502
503
504
  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
505
506
      reply_depth = (options[:depth] || 0) + 1
      options = Keyword.put(options, :depth, reply_depth)
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
      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
525
  def handle_incoming(
526
527
        %{"type" => "Follow", "object" => followed, "actor" => follower, "id" => id} = data,
        _options
lain's avatar
lain committed
528
      ) do
529
530
531
532
    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})),
533
         {:ok, activity} <- ActivityPub.follow(follower, followed, id, false) do
534
      with deny_follow_blocked <- Pleroma.Config.get([:user, :deny_follow_blocked]),
535
           {_, false} <- {:user_blocked, User.blocks?(followed, follower) && deny_follow_blocked},
536
537
           {_, false} <- {:user_locked, User.locked?(followed)},
           {_, {:ok, follower}} <- {:follow, User.follow(follower, followed)},
538
           {_, {:ok, _}} <-
539
             {:follow_state_update, Utils.update_follow_state_for_all(activity, "accept")},
540
541
           {:ok, _relationship} <-
             FollowingRelationship.update(follower, followed, :follow_accept) do
kaniini's avatar
kaniini committed
542
543
        ActivityPub.accept(%{
          to: [follower.ap_id],
544
          actor: followed,
kaniini's avatar
kaniini committed
545
546
547
          object: data,
          local: true
        })
548
549
      else
        {:user_blocked, true} ->
550
          {:ok, _} = Utils.update_follow_state_for_all(activity, "reject")
551
          {:ok, _relationship} = FollowingRelationship.update(follower, followed, :follow_reject)
552
553
554
555
556
557
558
559
560

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

        {:follow, {:error, _}} ->
561
          {:ok, _} = Utils.update_follow_state_for_all(activity, "reject")
562
          {:ok, _relationship} = FollowingRelationship.update(follower, followed, :follow_reject)
563
564
565
566
567
568
569
570
571

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

        {:user_locked, true} ->
572
          {:ok, _relationship} = FollowingRelationship.update(follower, followed, :follow_pending)
573
          :noop
574
      end
lain's avatar
lain committed
575

576
577
      {:ok, activity}
    else
578
579
      _e ->
        :error
580
581
582
    end
  end

583
  def handle_incoming(
584
        %{"type" => "Accept", "object" => follow_object, "actor" => _actor, "id" => id} = data,
585
        _options
586
      ) do
587
    with actor <- Containment.get_actor(data),
588
         {:ok, %User{} = followed} <- User.get_or_fetch_by_ap_id(actor),
589
         {:ok, follow_activity} <- get_follow_activity(follow_object, followed),
590
         {:ok, follow_activity} <- Utils.update_follow_state_for_all(follow_activity, "accept"),
591
         %User{local: true} = follower <- User.get_cached_by_ap_id(follow_activity.data["actor"]),
592
         {:ok, _relationship} <- FollowingRelationship.update(follower, followed, :follow_accept) do
593
594
595
596
597
      ActivityPub.accept(%{
        to: follow_activity.data["to"],
        type: "Accept",
        actor: followed,
        object: follow_activity.data["id"],
598
599
        local: false,
        activity_id: id
600
      })
601
602
    else
      _e -> :error
603
604
605
606
    end
  end

  def handle_incoming(
607
        %{"type" => "Reject", "object" => follow_object, "actor" => _actor, "id" => id} = data,
608
        _options
609
      ) do
610
    with actor <- Containment.get_actor(data),
611
         {:ok, %User{} = followed} <- User.get_or_fetch_by_ap_id(actor),
612
         {:ok, follow_activity} <- get_follow_activity(follow_object, followed),
613
         {:ok, follow_activity} <- Utils.update_follow_state_for_all(follow_activity, "reject"),
614
         %User{local: true} = follower <- User.get_cached_by_ap_id(follow_activity.data["actor"]),
615
         {:ok, _relationship} <- FollowingRelationship.update(follower, followed, :follow_reject),
lain's avatar
lain committed
616
         {:ok, activity} <-
617
           ActivityPub.reject(%{
lain's avatar
lain committed
618
             to: follow_activity.data["to"],
619
             type: "Reject",
620
             actor: followed,
lain's avatar
lain committed
621
             object: follow_activity.data["id"],
622
623
             local: false,
             activity_id: id
lain's avatar
lain committed
624
           }) do
625
      {:ok, activity}
626
627
    else
      _e -> :error
628
629
630
    end
  end

631
632
633
634
635
636
637
638
639
640
  @misskey_reactions %{
    "like" => "👍",
    "love" => "❤️",
    "laugh" => "😆",
    "hmm" => "🤔",
    "surprise" => "😮",
    "congrats" => "🎉",
    "angry" => "💢",
    "confused" => "😥",
    "rip" => "😇",
641
642
    "pudding" => "🍮",
    "star" => "⭐"
643
644
  }

lain's avatar
lain committed
645
  @doc "Rewrite misskey likes into EmojiReacts"
646
647
648
649
650
651
652
653
  def handle_incoming(
        %{
          "type" => "Like",
          "_misskey_reaction" => reaction
        } = data,
        options
      ) do
    data
lain's avatar
lain committed
654
    |> Map.put("type", "EmojiReact")
655
    |> Map.put("content", @misskey_reactions[reaction] || reaction)
656
657
658
    |> handle_incoming(options)
  end

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

669
670
  def handle_incoming(
        %{
lain's avatar
lain committed
671
          "type" => "EmojiReact",
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
          "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
690
  def handle_incoming(
691
692
        %{"type" => "Announce", "object" => object_id, "actor" => _actor, "id" => id} = data,
        _options
lain's avatar
lain committed
693
      ) do
694
    with actor <- Containment.get_actor(data),
695
         {:ok, %User{} = actor} <- User.get_or_fetch_by_ap_id(actor),
696
         {:ok, object} <- get_embedded_obj_helper(object_id, actor),
lain's avatar
lain committed
697
         public <- Visibility.is_public?(data),
698
         {:ok, activity, _object} <- ActivityPub.announce(actor, object, id, false, public) do
lain's avatar
lain committed
699
700
701
702
703
704
      {:ok, activity}
    else
      _e -> :error
    end
  end

lain's avatar
lain committed
705
  def handle_incoming(
706
        %{"type" => "Update", "object" => %{"type" => object_type} = object, "actor" => actor_id} =
707
708
          data,
        _options
709
      )
710
711
712
713
      when object_type in [
             "Person",
             "Application",
             "Service",
714
             "Organization"
715
           ] do
minibikini's avatar
minibikini committed
716
    with %User{ap_id: ^actor_id} = actor <- User.get_cached_by_ap_id(object["id"]) do
lain's avatar
lain committed
717
718
719
      {:ok, new_user_data} = ActivityPub.user_data_from_user_object(object)

      actor
720
      |> User.remote_user_changeset(new_user_data)
lain's avatar
lain committed
721
      |> User.update_and_set_cache()
lain's avatar
lain committed
722

lain's avatar
lain committed
723
724
725
726
727
      ActivityPub.update(%{
        local: false,
        to: data["to"] || [],
        cc: data["cc"] || [],
        object: object,
728
729
        actor: actor_id,
        activity_id: data["id"]
lain's avatar
lain committed
730
      })
lain's avatar
lain committed
731
732
733
734
735
736
737
    else
      e ->
        Logger.error(e)
        :error
    end
  end

738
739
740
741
742
  # 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
743
  def handle_incoming(
744
        %{"type" => "Delete", "object" => object_id, "actor" => actor, "id" => id} = data,
745
        _options
lain's avatar
lain committed
746
      ) do
lain's avatar
lain committed
747
    object_id = Utils.get_ap_id(object_id)
lain's avatar
lain committed
748

749
    with actor <- Containment.get_actor(data),
750
         {:ok, %User{} = actor} <- User.get_or_fetch_by_ap_id(actor),
751
         {:ok, object} <- get_obj_helper(object_id),
752
         :ok <- Containment.contain_origin(actor.ap_id, object.data),
753
754
         {:ok, activity} <-
           ActivityPub.delete(object, local: false, activity_id: id, actor: actor.ap_id) do
lain's avatar
lain committed
755
756
      {:ok, activity}
    else
757
758
759
      nil ->
        case User.get_cached_by_ap_id(object_id) do
          %User{ap_id: ^actor} = user ->
760
            User.delete(user)
761
762
763
764
765
766
767

          nil ->
            :error
        end

      _e ->
        :error
lain's avatar
lain committed
768
769
770
    end
  end

771
  def handle_incoming(
772
773
        %{
          "type" => "Undo",
774
          "object" => %{"type" => "Announce", "object" => object_id},
Maksim's avatar
Maksim committed
775
          "actor" => _actor,
776
          "id" => id
777
778
        } = data,
        _options
779
      ) do
780
    with actor <- Containment.get_actor(data),
781
         {:ok, %User{} = actor} <- User.get_or_fetch_by_ap_id(actor),
782
         {:ok, object} <- get_obj_helper(object_id),
783
         {:ok, activity, _} <- ActivityPub.unannounce(actor, object, id, false) do
784
785
      {:ok, activity}
    else
Thog's avatar
Thog committed
786
      _e -> :error
787
788
789
    end
  end

normandy's avatar
normandy committed
790
791
792
793
794
795
  def handle_incoming(
        %{
          "type" => "Undo",
          "object" => %{"type" => "Follow", "object" => followed},
          "actor" => follower,
          "id" => id
796
797
        } = _data,
        _options
normandy's avatar
normandy committed
798
      ) do
normandy's avatar
normandy committed
799
    with %User{local: true} = followed <- User.get_cached_by_ap_id(followed),
800
         {:ok, %User{} = follower} <- User.get_or_fetch_by_ap_id(follower),
normandy's avatar
normandy committed
801
         {:ok, activity} <- ActivityPub.unfollow(follower, followed, id, false) do
normandy's avatar
normandy committed
802
803
804
      User.unfollow(follower, followed)
      {:ok, activity}
    else
Maksim's avatar
Maksim committed
805
      _e -> :error
normandy's avatar
normandy committed
806
807
808
    end
  end

809
810
811
  def handle_incoming(
        %{
          "type" => "Undo",
lain's avatar
lain committed
812
          "object" => %{"type" => "EmojiReact", "id" => reaction_activity_id},
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
          "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
831
832
833
834
835
836
  def handle_incoming(
        %{
          "type" => "Undo",
          "object" => %{"type" => "Block", "object" => blocked},
          "actor" => blocker,
          "id" => id
837
838
        } = _data,
        _options
normandy's avatar
normandy committed
839
      ) do
840
    with %User{local: true} = blocked <- User.get_cached_by_ap_id(blocked),
841
         {:ok, %User{} = blocker} <- User.get_or_fetch_by_ap_id(blocker),
normandy's avatar
normandy committed
842
         {:ok, activity} <- ActivityPub.unblock(blocker, blocked, id, false) do
normandy's avatar
normandy committed
843
      User.unblock(blocker, blocked)
normandy's avatar
normandy committed
844
845
      {:ok, activity}
    else
Maksim's avatar
Maksim committed
846
      _e -> :error
normandy's avatar
normandy committed
847
848
849
    end
  end

850
  def handle_incoming(
851
852
        %{"type" => "Block", "object" => blocked, "actor" => blocker, "id" => id} = _data,
        _options
853
      ) do
854
    with %User{local: true} = blocked = User.get_cached_by_ap_id(blocked),
0x1C3B00DA's avatar
0x1C3B00DA committed
855
         {:ok, %User{} = blocker} = User.get_or_fetch_by_ap_id(blocker),
normandy's avatar
normandy committed
856
         {:ok, activity} <- ActivityPub.block(blocker, blocked, id, false) do
857
      User.unfollow(blocker, blocked)
858
      User.block(blocker, blocked)
normandy's avatar
normandy committed
859
860
      {:ok, activity}
    else
Maksim's avatar
Maksim committed
861
      _e -> :error
normandy's avatar
normandy committed
862
863
    end
  end
864

Thog's avatar
Thog committed
865
866
867
  def handle_incoming(
        %{
          "type" => "Undo",
868
          "object" => %{"type" => "Like"}
869
870
        } = data,
        _options
Thog's avatar
Thog committed
871
      ) do
872
    with {:ok, activity, _} <- Pipeline.common_pipeline(data, local: false) do
Thog's avatar
Thog committed
873
874
875
876
      {:ok, activity}
    end
  end

877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
  # 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
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
  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

913
  def handle_incoming(_, _), do: :error
914

915
  @spec get_obj_helper(String.t(), Keyword.t()) :: {:ok, Object.t()} | nil
916
  def get_obj_helper(id, options \\ []) do
Maksim's avatar
Maksim committed
917
918
919
    case Object.normalize(id, true, options) do
      %Object{} = object -> {:ok, object}
      _ -> nil
920
    end
921
922
  end

923
  @spec get_embedded_obj_helper(String.t() | Object.t(), User.t()) :: {:ok, Object.t()} | nil
Thibaut Girka's avatar
Thibaut Girka committed
924
  def get_embedded_obj_helper(%{"attributedTo" => attributed_to, "id" => object_id} = data, %User{
925
926
        ap_id: ap_id
      })
Thibaut Girka's avatar
Thibaut Girka committed
927
      when attributed_to == ap_id do
928
929
930
931
932
    with {:ok, activity} <-
           handle_incoming(%{
             "type" => "Create",
             "to" => data["to"],
             "cc" => data["cc"],
Thibaut Girka's avatar
Thibaut Girka committed
933
             "actor" => attributed_to,
934
935
936
937
938
939
940
941
942
943
944
945
             "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

946
947
948
949
  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)
950
951
952
953
    else
      _e -> object
    end
  end
lain's avatar
lain committed
954

955
956
  def set_reply_to_uri(obj), do: obj

957
958
959
960
  @doc """
  Serialized Mastodon-compatible `replies` collection containing _self-replies_.
  Based on Mastodon's ActivityPub::NoteSerializer#replies.
  """
961
  def set_replies(obj_data)