transmogrifier.ex 34.4 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
  alias Pleroma.Web.ActivityPub.Builder
18
  alias Pleroma.Web.ActivityPub.ObjectValidator
19
  alias Pleroma.Web.ActivityPub.ObjectValidators.Types
20
  alias Pleroma.Web.ActivityPub.Pipeline
Haelwenn's avatar
Haelwenn committed
21
  alias Pleroma.Web.ActivityPub.Utils
lain's avatar
lain committed
22
  alias Pleroma.Web.ActivityPub.Visibility
23
  alias Pleroma.Web.Federator
24
  alias Pleroma.Workers.TransmogrifierWorker
25

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

28
  require Logger
29
  require Pleroma.Constants
30

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

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

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

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

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

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

      true ->
        map
72
73
74
    end
  end

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

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

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

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

94
  def fix_explicit_addressing(object, _explicit_mentions, _followers_collection), do: object
95

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

99
  def fix_explicit_addressing(object) do
100
    explicit_mentions = Utils.determine_explicit_mentions(object)
101

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

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

114
    fix_explicit_addressing(object, explicit_mentions, follower_collection)
lain's avatar
lain committed
115
116
  end

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

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

        true ->
          object
      end
135
    else
136
      object
137
138
139
    end
  end

140
141
  def fix_implicit_addressing(object, _), do: object

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

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

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

159
160
161
  def fix_in_reply_to(object, options \\ [])

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

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

185
  def fix_in_reply_to(object, _options), do: object
lain's avatar
lain committed
186

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

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

211
212
213
214
215
216
  defp add_if_present(map, _key, nil), do: map

  defp add_if_present(map, key, value) do
    Map.put(map, key, value)
  end

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

227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
        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
251
      end)
lain's avatar
lain committed
252

253
    Map.put(object, "attachment", attachments)
254
255
  end

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

262
  def fix_attachments(object), do: object
263

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

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

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

    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
281
282
283
284
285
286
287
288
289
    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

290
    Map.put(object, "url", url_string)
291
292
293
294
  end

  def fix_url(object), do: object

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

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

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

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

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

315
    Map.put(object, "emoji", emoji)
316
317
  end

318
  def fix_emoji(object), do: object
319

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

326
    Map.put(object, "tag", tag ++ tags)
327
328
  end

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

332
    Map.put(object, "tag", combined)
333
334
  end

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

337
  def fix_tag(object), do: object
338

339
340
341
342
343
  # 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)

344
    Map.put(object, "content", content)
345
346
347
348
  end

  def fix_content_map(object), do: object

349
350
  def fix_type(object, options \\ [])

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

361
  def fix_type(object, _), do: object
362

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

Maksim's avatar
Maksim committed
373
  defp fix_content(object), do: object
Maksim's avatar
Maksim committed
374

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

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

412
413
  def handle_incoming(data, options \\ [])

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

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

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

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

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

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

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

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

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

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

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

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

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

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

585
  def handle_incoming(
586
        %{"type" => "Accept", "object" => follow_object, "actor" => _actor, "id" => id} = data,
587
        _options
588
      ) do
589
    with actor <- Containment.get_actor(data),
590
         {:ok, %User{} = followed} <- User.get_or_fetch_by_ap_id(actor),
591
         {:ok, follow_activity} <- get_follow_activity(follow_object, followed),
592
         {:ok, follow_activity} <- Utils.update_follow_state_for_all(follow_activity, "accept"),
593
         %User{local: true} = follower <- User.get_cached_by_ap_id(follow_activity.data["actor"]),
594
         {:ok, _relationship} <- FollowingRelationship.update(follower, followed, :follow_accept) do
595
596
597
      User.update_follower_count(followed)
      User.update_following_count(follower)

598
599
600
601
602
      ActivityPub.accept(%{
        to: follow_activity.data["to"],
        type: "Accept",
        actor: followed,
        object: follow_activity.data["id"],
603
604
        local: false,
        activity_id: id
605
      })
606
    else
607
608
      _e ->
        :error
609
610
611
612
    end
  end

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

637
638
639
640
641
642
643
644
645
646
  @misskey_reactions %{
    "like" => "👍",
    "love" => "❤️",
    "laugh" => "😆",
    "hmm" => "🤔",
    "surprise" => "😮",
    "congrats" => "🎉",
    "angry" => "💢",
    "confused" => "😥",
    "rip" => "😇",
647
648
    "pudding" => "🍮",
    "star" => "⭐"
649
650
  }

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

665
  def handle_incoming(%{"type" => type} = data, _options) when type in ["Like", "EmojiReact"] do
lain's avatar
lain committed
666
667
668
    with :ok <- ObjectValidator.fetch_actor_and_object(data),
         {:ok, activity, _meta} <-
           Pipeline.common_pipeline(data, local: false) do
lain's avatar
lain committed
669
670
      {:ok, activity}
    else
671
      e -> {:error, e}
lain's avatar
lain committed
672
673
674
    end
  end

lain's avatar
lain committed
675
  def handle_incoming(
676
677
        %{"type" => "Announce", "object" => object_id, "actor" => _actor, "id" => id} = data,
        _options
lain's avatar
lain committed
678
      ) do
679
    with actor <- Containment.get_actor(data),
680
681
         {_, {:ok, %User{} = actor}} <- {:fetch_user, User.get_or_fetch_by_ap_id(actor)},
         {_, {:ok, object}} <- {:get_embedded, get_embedded_obj_helper(object_id, actor)},
lain's avatar
lain committed
682
         public <- Visibility.is_public?(data),
683
684
         {_, {:ok, activity, _object}} <-
           {:announce, ActivityPub.announce(actor, object, id, false, public)} do
lain's avatar
lain committed
685
686
      {:ok, activity}
    else
687
      e -> {:error, e}
lain's avatar
lain committed
688
689
690
    end
  end

lain's avatar
lain committed
691
  def handle_incoming(
692
        %{"type" => "Update", "object" => %{"type" => object_type} = object, "actor" => actor_id} =
693
694
          data,
        _options
695
      )
696
697
698
699
      when object_type in [
             "Person",
             "Application",
             "Service",
700
             "Organization"
701
           ] do
minibikini's avatar
minibikini committed
702
    with %User{ap_id: ^actor_id} = actor <- User.get_cached_by_ap_id(object["id"]) do
lain's avatar
lain committed
703
704
705
      {:ok, new_user_data} = ActivityPub.user_data_from_user_object(object)

      actor
706
      |> User.remote_user_changeset(new_user_data)
lain's avatar
lain committed
707
      |> User.update_and_set_cache()
lain's avatar
lain committed
708

lain's avatar
lain committed
709
710
711
712
713
      ActivityPub.update(%{
        local: false,
        to: data["to"] || [],
        cc: data["cc"] || [],
        object: object,
714
715
        actor: actor_id,
        activity_id: data["id"]
lain's avatar
lain committed
716
      })
lain's avatar
lain committed
717
718
719
720
721
722
723
    else
      e ->
        Logger.error(e)
        :error
    end
  end

lain's avatar
lain committed
724
  def handle_incoming(
725
        %{"type" => "Delete"} = data,
726
        _options
lain's avatar
lain committed
727
      ) do
728
    with {:ok, activity, _} <- Pipeline.common_pipeline(data, local: false) do
lain's avatar
lain committed
729
      {:ok, activity}
730
731
732
733
734
735
736
737
738
739
740
741
742
    else
      {:error, {:validate_object, _}} = e ->
        # Check if we have a create activity for this
        with {:ok, object_id} <- Types.ObjectID.cast(data["object"]),
             %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
743
744
745
    end
  end

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

765
766
767
  def handle_incoming(
        %{
          "type" => "Undo",
768
          "object" => %{"type" => type}
769
770
        } = data,
        _options
771
      )
772
      when type in ["Like", "EmojiReact", "Announce", "Block"] do
773
    with {:ok, activity, _} <- Pipeline.common_pipeline(data, local: false) do
774
775
776
777
      {:ok, activity}
    end
  end

778
  # For Undos that don't have the complete object attached, try to find it in our database.
normandy's avatar
normandy committed
779
780
781
  def handle_incoming(
        %{
          "type" => "Undo",
782
783
784
785
786
787
788
789
790
          "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
791
    else
Maksim's avatar
Maksim committed
792
      _e -> :error
normandy's avatar
normandy committed
793
794
795
    end
  end

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

minibikini's avatar
minibikini committed
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
  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

829
  def handle_incoming(_, _), do: :error
830

831
  @spec get_obj_helper(String.t(), Keyword.t()) :: {:ok, Object.t()} | nil
832
  def get_obj_helper(id, options \\ []) do
Maksim's avatar
Maksim committed
833
834
835
    case Object.normalize(id, true, options) do
      %Object{} = object -> {:ok, object}
      _ -> nil
836
    end
837
838
  end

839
  @spec get_embedded_obj_helper(String.t() | Object.t(), User.t()) :: {:ok, Object.t()} | nil
Thibaut Girka's avatar
Thibaut Girka committed
840
  def get_embedded_obj_helper(%{"attributedTo" => attributed_to, "id" => object_id} = data, %User{
841
842
        ap_id: ap_id
      })
Thibaut Girka's avatar
Thibaut Girka committed
843
      when attributed_to == ap_id do
844
845
846
847
848
    with {:ok, activity} <-
           handle_incoming(%{
             "type" => "Create",
             "to" => data["to"],
             "cc" => data["cc"],
Thibaut Girka's avatar
Thibaut Girka committed
849
             "actor" => attributed_to,
850
851
852
853
854
855
856
857
858
859
860
861
             "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

862
863
864
865
  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)
866
867
868
869
    else
      _e -> object
    end
  end
lain's avatar
lain committed
870

871
872
  def set_reply_to_uri(obj), do: obj

873
874
875
876
  @doc """
  Serialized Mastodon-compatible `replies` collection containing _self-replies_.
  Based on Mastodon's ActivityPub::NoteSerializer#replies.
  """
877
  def set_replies(obj_data) do
878
    replies_uris =
Ivan Tashkinov's avatar
Ivan Tashkinov committed
879
880
      with limit when limit > 0 <-
             Pleroma.Config.get([:activitypub, :note_replies_output_limit], 0),
881
882
883
884
           %Object{} = object <- Object.get_cached_by_ap_id(obj_data["id"]) do
        object
        |> Object.self_replies()
        |> select([o], fragment("?->>'id'", o.data))
885
886
        |> limit(^limit)
        |> Repo.all()
Ivan Tashkinov's avatar
Ivan Tashkinov committed
887
888
      else
        _ -> []
889
890
      end

Ivan Tashkinov's avatar
Ivan Tashkinov committed
891
    set_replies(obj_data, replies_uris)
892
893
  end

Ivan Tashkinov's avatar
Ivan Tashkinov committed
894
  defp set_replies(obj, []) do
895
896
897
898
899
900
    obj
  end

  defp set_replies(obj, replies_uris) do
    replies_collection = %{
      "type" => "Collection",
901
      "items" => replies_uris
902
903
904
905
906
    }

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

Ivan Tashkinov's avatar
Ivan Tashkinov committed
907
908
909
  def replies(%{"replies" => %{"first" => %{"items" => items}}}) when not is_nil(items) do
    items
  end
910

Ivan Tashkinov's avatar
Ivan Tashkinov committed
911
912
  def replies(%{"replies" => %{"items" => items}}) when not is_nil(items) do
    items
913
914
915
916
  end

  def replies(_), do: []

917
  # Prepares the object of an outgoing create activity.
lain's avatar
lain committed
918
919
  def prepare_object(object) do
    object
lain's avatar
lain committed
920
    |> set_sensitive
lain's avatar
lain committed
921
    |> add_hashtags
lain's avatar
lain committed
922
    |> add_mention_tags
lain's avatar
lain committed
923
    |> add_emoji_tags
lain's avatar
lain committed
924
    |> add_attributed_to
lain's avatar
lain committed
925
    |> prepare_attachments
lain's avatar
lain committed
926
    |> set_conversation
927
    |> set_reply_to_uri
928
    |> set_replies
929
930
    |> strip_internal_fields
    |> strip_internal_tags
931
    |> set_type
lain's avatar
lain committed
932
933
  end

feld's avatar
feld committed
934
935
936
937
  #  @doc
  #  """
  #  internal -> Mastodon
  #  """
lain's avatar
lain committed
938