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

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

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

30
  require Logger
31
  require Pleroma.Constants
32

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

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

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

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

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

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

      true ->
        map
74
75
76
    end
  end

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

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

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

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

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

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

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

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

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

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

119
120
121
122
123
124
125
  # if as:Public is addressed, then make sure the followers collection is also addressed
  # so that the activities will be delivered to local users.
  def fix_implicit_addressing(%{"to" => to, "cc" => cc} = object, followers_collection) do
    recipients = to ++ cc

    if followers_collection not in recipients do
      cond do
126
        Pleroma.Constants.as_public() in cc ->
127
128
129
          to = to ++ [followers_collection]
          Map.put(object, "to", to)

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

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

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

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

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

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

161
162
163
  def fix_in_reply_to(object, options \\ [])

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

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

187
  def fix_in_reply_to(object, _options), do: object
lain's avatar
lain committed
188

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

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

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

        media_type =
          cond do
225
226
227
            is_map(url) && MIME.valid?(url["mediaType"]) -> url["mediaType"]
            MIME.valid?(data["mediaType"]) -> data["mediaType"]
            MIME.valid?(data["mimeType"]) -> data["mimeType"]
228
229
230
231
232
233
234
235
236
237
238
239
            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}
240
241
          |> Maps.put_if_present("mediaType", media_type)
          |> Maps.put_if_present("type", Map.get(url || %{}, "type"))
242

243
        %{"url" => [attachment_url]}
244
245
246
        |> Maps.put_if_present("mediaType", media_type)
        |> Maps.put_if_present("type", data["type"])
        |> Maps.put_if_present("name", data["name"])
lain's avatar
lain committed
247
      end)
lain's avatar
lain committed
248

249
    Map.put(object, "attachment", attachments)
250
251
  end

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

258
  def fix_attachments(object), do: object
259

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

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

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

    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
277
278
279
280
281
282
283
284
285
    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

286
    Map.put(object, "url", url_string)
287
288
289
290
  end

  def fix_url(object), do: object

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

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

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

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

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

311
    Map.put(object, "emoji", emoji)
312
313
  end

314
  def fix_emoji(object), do: object
315

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

322
    Map.put(object, "tag", tag ++ tags)
323
324
  end

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

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

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

333
  def fix_tag(object), do: object
334

335
336
337
338
339
  # 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)

340
    Map.put(object, "content", content)
341
342
343
344
  end

  def fix_content_map(object), do: object

345
346
  def fix_type(object, options \\ [])

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

357
  def fix_type(object, _), do: object
358

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

Maksim's avatar
Maksim committed
369
  defp fix_content(object), do: object
Maksim's avatar
Maksim committed
370

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

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

408
409
  def handle_incoming(data, options \\ [])

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

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

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

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

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

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

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

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

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

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

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

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

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

575
      ActivityPub.notify_and_stream(activity)
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
      User.update_follower_count(followed)
      User.update_following_count(follower)

596
597
      Notification.update_notification_type(followed, follow_activity)

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

lain's avatar
lain committed
665
666
  def handle_incoming(
        %{"type" => "Create", "object" => %{"type" => "ChatMessage"}} = data,
667
668
        _options
      ) do
669
670
671
    with {:ok, %User{}} <- ObjectValidator.fetch_actor(data),
         {:ok, activity, _} <- Pipeline.common_pipeline(data, local: false) do
      {:ok, activity}
672
673
    end
  end
lain's avatar
lain committed
674

675
676
  def handle_incoming(%{"type" => type} = data, _options)
      when type in ["Like", "EmojiReact", "Announce"] do
lain's avatar
lain committed
677
678
679
    with :ok <- ObjectValidator.fetch_actor_and_object(data),
         {:ok, activity, _meta} <-
           Pipeline.common_pipeline(data, local: false) do
lain's avatar
lain committed
680
681
      {:ok, activity}
    else
682
      e -> {:error, e}
lain's avatar
lain committed
683
684
685
    end
  end

lain's avatar
lain committed
686
  def handle_incoming(
687
        %{"type" => "Update"} = data,
688
        _options
689
690
691
692
      ) do
    with {:ok, %User{}} <- ObjectValidator.fetch_actor(data),
         {:ok, activity, _} <- Pipeline.common_pipeline(data, local: false) do
      {:ok, activity}
lain's avatar
lain committed
693
694
695
    end
  end

lain's avatar
lain committed
696
  def handle_incoming(
697
        %{"type" => "Delete"} = data,
698
        _options
lain's avatar
lain committed
699
      ) do
700
    with {:ok, activity, _} <- Pipeline.common_pipeline(data, local: false) do
lain's avatar
lain committed
701
      {:ok, activity}
702
703
704
    else
      {:error, {:validate_object, _}} = e ->
        # Check if we have a create activity for this
705
        with {:ok, object_id} <- ObjectValidators.ObjectID.cast(data["object"]),
706
707
708
709
710
711
712
713
714
             %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
715
716
717
    end
  end

normandy's avatar
normandy committed
718
719
720
721
722
723
  def handle_incoming(
        %{
          "type" => "Undo",
          "object" => %{"type" => "Follow", "object" => followed},
          "actor" => follower,
          "id" => id
724
725
        } = _data,
        _options
normandy's avatar
normandy committed
726
      ) do
normandy's avatar
normandy committed
727
    with %User{local: true} = followed <- User.get_cached_by_ap_id(followed),
728
         {:ok, %User{} = follower} <- User.get_or_fetch_by_ap_id(follower),
normandy's avatar
normandy committed
729
         {:ok, activity} <- ActivityPub.unfollow(follower, followed, id, false) do
normandy's avatar
normandy committed
730
731
732
      User.unfollow(follower, followed)
      {:ok, activity}
    else
Maksim's avatar
Maksim committed
733
      _e -> :error
normandy's avatar
normandy committed
734
735
736
    end
  end

737
738
739
  def handle_incoming(
        %{
          "type" => "Undo",
740
          "object" => %{"type" => type}
741
742
        } = data,
        _options
743
      )
744
      when type in ["Like", "EmojiReact", "Announce", "Block"] do
745
    with {:ok, activity, _} <- Pipeline.common_pipeline(data, local: false) do
746
747
748
749
      {:ok, activity}
    end
  end

750
  # For Undos that don't have the complete object attached, try to find it in our database.
normandy's avatar
normandy committed
751
752
753
  def handle_incoming(
        %{
          "type" => "Undo",
754
755
756
757
758
759
760
761
762
          "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
763
    else
Maksim's avatar
Maksim committed
764
      _e -> :error
normandy's avatar
normandy committed
765
766
767
    end
  end

768
  def handle_incoming(
769
770
        %{"type" => "Block", "object" => blocked, "actor" => blocker, "id" => id} = _data,
        _options
771
      ) do
772
    with %User{local: true} = blocked = User.get_cached_by_ap_id(blocked),
0x1C3B00DA's avatar
0x1C3B00DA committed
773
         {:ok, %User{} = blocker} = User.get_or_fetch_by_ap_id(blocker),
normandy's avatar
normandy committed
774
         {:ok, activity} <- ActivityPub.block(blocker, blocked, id, false) do
775
      User.unfollow(blocker, blocked)
776
      User.block(blocker, blocked)
normandy's avatar
normandy committed
777
778
      {:ok, activity}
    else
Maksim's avatar
Maksim committed
779
      _e -> :error
normandy's avatar
normandy committed
780
781
    end
  end
782

minibikini's avatar
minibikini committed
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
  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

801
  def handle_incoming(_, _), do: :error
802

803
  @spec get_obj_helper(String.t(), Keyword.t()) :: {:ok, Object.t()} | nil
804
  def get_obj_helper(id, options \\ []) do
Maksim's avatar
Maksim committed
805
806
807
    case Object.normalize(id, true, options) do
      %Object{} = object -> {:ok, object}
      _ -> nil
808
    end
809
810
  end

811
  @spec get_embedded_obj_helper(String.t() | Object.t(), User.t()) :: {:ok, Object.t()} | nil
Thibaut Girka's avatar
Thibaut Girka committed
812
  def get_embedded_obj_helper(%{"attributedTo" => attributed_to, "id" => object_id} = data, %User{
813
814
        ap_id: ap_id
      })
Thibaut Girka's avatar
Thibaut Girka committed
815
      when attributed_to == ap_id do
816
817
818
819
820
    with {:ok, activity} <-
           handle_incoming(%{
             "type" => "Create",
             "to" => data["to"],
             "cc" => data["cc"],
Thibaut Girka's avatar
Thibaut Girka committed
821
             "actor" => attributed_to,
822
823
824
825
826
827
828
829
830
831
832
833
             "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

834
835
836
837
  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)
838
839
840
841
    else
      _e -> object
    end
  end
lain's avatar
lain committed
842

843
844
  def set_reply_to_uri(obj), do: obj

845
846
847
848
  @doc """
  Serialized Mastodon-compatible `replies` collection containing _self-replies_.
  Based on Mastodon's ActivityPub::NoteSerializer#replies.
  """
849
  def set_replies(obj_data) do
850
    replies_uris =
Ivan Tashkinov's avatar
Ivan Tashkinov committed
851
852
      with limit when limit > 0 <-
             Pleroma.Config.get([:activitypub, :note_replies_output_limit], 0),
853
854
855
856
           %Object{} = object <- Object.get_cached_by_ap_id(obj_data["id"]) do
        object
        |> Object.self_replies()
        |> select([o], fragment("?->>'id'", o.data))
857
858
        |> limit(^limit)
        |> Repo.all()
Ivan Tashkinov's avatar
Ivan Tashkinov committed
859
860
      else
        _ -> []
861
862
      end

Ivan Tashkinov's avatar
Ivan Tashkinov committed
863
    set_replies(obj_data, replies_uris)
864
865
  end

Ivan Tashkinov's avatar
Ivan Tashkinov committed
866
  defp set_replies(obj, []) do
867
868
869
870
871
872
    obj
  end

  defp set_replies(obj, replies_uris) do
    replies_collection = %{
      "type" => "Collection",
873
      "items" => replies_uris
874
875
876
877
878
    }

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

Ivan Tashkinov's avatar
Ivan Tashkinov committed
879
880
881
  def replies(%{"replies" => %{"first" => %{"items" => items}}}) when not is_nil(items) do
    items
  end
882

Ivan Tashkinov's avatar
Ivan Tashkinov committed
883
884
  def replies(%{"replies" => %{"items" => items}}) when not is_nil(items) do
    items
885
886
887
888
  end

  def replies(_), do: []

889
  # Prepares the object of an outgoing create activity.
lain's avatar
lain committed
890
891
  def prepare_object(object) do
    object
lain's avatar
lain committed
892
    |> set_sensitive
lain's avatar
lain committed
893
    |> add_hashtags
lain's avatar
lain committed
894
    |> add_mention_tags
lain's avatar
lain committed
895
    |> add_emoji_tags
lain's avatar
lain committed
896
    |> add_attributed_to
lain's avatar
lain committed
897
    |> prepare_attachments
lain's avatar
lain committed
898
    |> set_conversation
899
    |> set_reply_to_uri
900
    |> set_replies
901
902
    |> strip_internal_fields
    |> strip_internal_tags
903
    |> set_type
lain's avatar
lain committed
904
905
  end

feld's avatar
feld committed
906
907
908
909
  #  @doc
  #  """
  #  internal -> Mastodon
  #  """
lain's avatar
lain committed
910

911
912
  def prepare_outgoing(%{"type" => activity_type, "object" => object_id} = data)
      when activity_type in ["Create", "Listen"] do
lain's avatar
lain committed
913
    object =
minibikini's avatar
minibikini committed
914
915
916
      object_id
      |> Object.normalize()
      |> Map.get(:data)
lain's avatar
lain committed
917
918
919
920
921
      |> prepare_object

    data =
      data
      |> Map.put("object", object)
lain's avatar
lain committed
922
      |> Map.merge(Utils.make_json_ld_header())
minibikini's avatar
minibikini committed
923
      |> Map.delete("bcc")
lain's avatar
lain committed
924
925
926
927

    {:ok, data}
  end

928
929
930
931
932
9