transmogrifier.ex 32.9 KB
Newer Older
1
# Pleroma: A lightweight social networking server
kaniini's avatar
kaniini committed
2
# Copyright © 2017-2019 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
10
  alias Pleroma.Activity
  alias Pleroma.Object
rinpatch's avatar
rinpatch committed
11
  alias Pleroma.Object.Containment
Haelwenn's avatar
Haelwenn committed
12
  alias Pleroma.Repo
13
  alias Pleroma.User
Haelwenn's avatar
Haelwenn committed
14
15
  alias Pleroma.Web.ActivityPub.ActivityPub
  alias Pleroma.Web.ActivityPub.Utils
lain's avatar
lain committed
16
  alias Pleroma.Web.ActivityPub.Visibility
17
  alias Pleroma.Web.Federator
18
  alias Pleroma.Workers.TransmogrifierWorker
19

lain's avatar
lain committed
20
21
  import Ecto.Query

22
  require Logger
23
  require Pleroma.Constants
24

25
26
27
  @doc """
  Modifies an incoming AP object (mastodon format) to our internal format.
  """
28
  def fix_object(object, options \\ []) do
29
    object
30
    |> strip_internal_fields
31
    |> fix_actor
32
    |> fix_url
33
    |> fix_attachments
lain's avatar
lain committed
34
    |> fix_context
35
    |> fix_in_reply_to(options)
lain's avatar
lain committed
36
    |> fix_emoji
37
    |> fix_tag
38
    |> fix_content_map
39
    |> fix_addressing
40
    |> fix_summary
41
    |> fix_type(options)
42
43
44
  end

  def fix_summary(%{"summary" => nil} = object) do
45
    Map.put(object, "summary", "")
46
47
48
49
50
51
52
  end

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

53
  def fix_summary(object), do: Map.put(object, "summary", "")
54
55

  def fix_addressing_list(map, field) do
56
57
58
59
60
61
62
63
64
    cond do
      is_binary(map[field]) ->
        Map.put(map, field, [map[field]])

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

      true ->
        map
65
66
67
    end
  end

68
69
70
71
72
  def fix_explicit_addressing(
        %{"to" => to, "cc" => cc} = object,
        explicit_mentions,
        follower_collection
      ) do
73
    explicit_to = Enum.filter(to, fn x -> x in explicit_mentions end)
74

75
    explicit_cc = Enum.filter(to, fn x -> x not in explicit_mentions end)
76
77
78

    final_cc =
      (cc ++ explicit_cc)
79
      |> Enum.reject(fn x -> String.ends_with?(x, "/followers") and x != follower_collection end)
80
81
82
83
84
85
86
      |> Enum.uniq()

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

87
  def fix_explicit_addressing(object, _explicit_mentions, _followers_collection), do: object
88

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

92
  def fix_explicit_addressing(object) do
93
    explicit_mentions = Utils.determine_explicit_mentions(object)
94

95
96
97
98
    %User{follower_address: follower_collection} =
      object
      |> Containment.get_actor()
      |> User.get_cached_by_ap_id()
99

100
101
102
103
104
105
    explicit_mentions =
      explicit_mentions ++
        [
          Pleroma.Constants.as_public(),
          follower_collection
        ]
106

107
    fix_explicit_addressing(object, explicit_mentions, follower_collection)
lain's avatar
lain committed
108
109
  end

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

121
        Pleroma.Constants.as_public() in to ->
122
123
124
125
126
127
          cc = cc ++ [followers_collection]
          Map.put(object, "cc", cc)

        true ->
          object
      end
128
    else
129
      object
130
131
132
    end
  end

133
134
  def fix_implicit_addressing(object, _), do: object

135
  def fix_addressing(object) do
Alexander Strizhakov's avatar
Alexander Strizhakov committed
136
    {:ok, %User{} = user} = User.get_or_fetch_by_ap_id(object["actor"])
137
138
    followers_collection = User.ap_followers(user)

139
    object
140
141
142
143
    |> fix_addressing_list("to")
    |> fix_addressing_list("cc")
    |> fix_addressing_list("bto")
    |> fix_addressing_list("bcc")
144
    |> fix_explicit_addressing()
145
    |> fix_implicit_addressing(followers_collection)
lain's avatar
lain committed
146
147
  end

148
  def fix_actor(%{"attributedTo" => actor} = object) do
149
    Map.put(object, "actor", Containment.get_actor(%{"actor" => actor}))
150
151
  end

152
153
154
  def fix_in_reply_to(object, options \\ [])

  def fix_in_reply_to(%{"inReplyTo" => in_reply_to} = object, options)
155
      when not is_nil(in_reply_to) do
156
    in_reply_to_id = prepare_in_reply_to(in_reply_to)
157
    object = Map.put(object, "inReplyToAtomUri", in_reply_to_id)
lain's avatar
lain committed
158

159
    if Federator.allowed_incoming_reply_depth?(options[:depth]) do
160
161
162
163
164
165
166
167
      with {:ok, replied_object} <- get_obj_helper(in_reply_to_id, options),
           %Activity{} = _ <- Activity.get_create_by_object_ap_id(replied_object.data["id"]) do
        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
168
        e ->
feld's avatar
feld committed
169
          Logger.error("Couldn't fetch #{inspect(in_reply_to_id)}, error: #{inspect(e)}")
170
171
172
173
          object
      end
    else
      object
lain's avatar
lain committed
174
175
    end
  end
lain's avatar
lain committed
176

177
  def fix_in_reply_to(object, _options), do: object
lain's avatar
lain committed
178

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

lain's avatar
lain committed
198
    object
Haelwenn's avatar
Haelwenn committed
199
200
    |> Map.put("context", context)
    |> Map.put("conversation", context)
lain's avatar
lain committed
201
202
  end

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

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

215
    Map.put(object, "attachment", attachments)
216
217
  end

218
  def fix_attachments(%{"attachment" => attachment} = object) when is_map(attachment) do
Maksim's avatar
Maksim committed
219
220
    object
    |> Map.put("attachment", [attachment])
221
    |> fix_attachments()
222
223
  end

224
  def fix_attachments(object), do: object
225

226
  def fix_url(%{"url" => url} = object) when is_map(url) do
227
    Map.put(object, "url", url["href"])
228
229
  end

230
231
232
  def fix_url(%{"type" => "Video", "url" => url} = object) when is_list(url) do
    first_element = Enum.at(url, 0)

233
    link_element = Enum.find(url, fn x -> is_map(x) and x["mimeType"] == "text/html" end)
234
235
236
237
238
239
240
241

    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
242
243
244
245
246
247
248
249
250
    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

251
    Map.put(object, "url", url_string)
252
253
254
255
  end

  def fix_url(object), do: object

256
  def fix_emoji(%{"tag" => tags} = object) when is_list(tags) do
lain's avatar
lain committed
257
    emoji =
258
259
      tags
      |> Enum.filter(fn data -> data["type"] == "Emoji" and data["icon"] end)
lain's avatar
lain committed
260
      |> Enum.reduce(%{}, fn data, mapping ->
261
        name = String.trim(data["name"], ":")
lain's avatar
lain committed
262

263
        Map.put(mapping, name, data["icon"]["url"])
lain's avatar
lain committed
264
      end)
lain's avatar
lain committed
265
266
267
268

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

269
    Map.put(object, "emoji", emoji)
lain's avatar
lain committed
270
271
  end

272
273
274
275
  def fix_emoji(%{"tag" => %{"type" => "Emoji"} = tag} = object) do
    name = String.trim(tag["name"], ":")
    emoji = %{name => tag["icon"]["url"]}

276
    Map.put(object, "emoji", emoji)
277
278
  end

279
  def fix_emoji(object), do: object
280

281
  def fix_tag(%{"tag" => tag} = object) when is_list(tag) do
lain's avatar
lain committed
282
    tags =
283
      tag
lain's avatar
lain committed
284
285
      |> Enum.filter(fn data -> data["type"] == "Hashtag" and data["name"] end)
      |> Enum.map(fn data -> String.slice(data["name"], 1..-1) end)
286

287
    Map.put(object, "tag", tag ++ tags)
288
289
  end

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

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

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

298
  def fix_tag(object), do: object
299

300
301
302
303
304
  # 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)

305
    Map.put(object, "content", content)
306
307
308
309
  end

  def fix_content_map(object), do: object

310
311
  def fix_type(object, options \\ [])

312
313
  def fix_type(%{"inReplyTo" => reply_id, "name" => _} = object, options)
      when is_binary(reply_id) do
314
315
    with true <- Federator.allowed_incoming_reply_depth?(options[:depth]),
         {:ok, %{data: %{"type" => "Question"} = _} = _} <- get_obj_helper(reply_id, options) do
316
317
      Map.put(object, "type", "Answer")
    else
318
      _ -> object
319
320
321
    end
  end

322
  def fix_type(object, _), do: object
323

Maksim's avatar
Maksim committed
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
  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

350
351
352
353
354
355
356
357
358
359
360
  # 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

361
362
  def handle_incoming(data, options \\ [])

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

385
  # disallow objects with bogus IDs
386
387
  def handle_incoming(%{"id" => nil}, _options), do: :error
  def handle_incoming(%{"id" => ""}, _options), do: :error
388
  # length of https:// = 8, should validate better, but good enough for now.
389
390
  def handle_incoming(%{"id" => id}, _options) when not (is_binary(id) and length(id) > 8),
    do: :error
391

392
393
394
  # TODO: validate those with a Ecto scheme
  # - tags
  # - emoji
395
396
397
398
  def handle_incoming(
        %{"type" => "Create", "object" => %{"type" => objtype} = object} = data,
        options
      )
399
      when objtype in ["Article", "Note", "Video", "Page", "Question", "Answer"] do
400
    actor = Containment.get_actor(data)
401
402
403
404

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

406
    with nil <- Activity.get_create_by_object_ap_id(object["id"]),
407
         {:ok, %User{} = user} <- User.get_or_fetch_by_ap_id(data["actor"]) do
408
409
      options = Keyword.put(options, :depth, (options[:depth] || 0) + 1)
      object = fix_object(data["object"], options)
410

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

      ActivityPub.create(params)
    else
lain's avatar
lain committed
428
      %Activity{} = activity -> {:ok, activity}
429
430
431
432
      _e -> :error
    end
  end

433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
  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
      options = Keyword.put(options, :depth, (options[:depth] || 0) + 1)
      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
463
  def handle_incoming(
464
465
        %{"type" => "Follow", "object" => followed, "actor" => follower, "id" => id} = data,
        _options
lain's avatar
lain committed
466
      ) do
467
468
469
470
    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})),
471
         {:ok, activity} <- ActivityPub.follow(follower, followed, id, false) do
472
      with deny_follow_blocked <- Pleroma.Config.get([:user, :deny_follow_blocked]),
473
           {_, false} <- {:user_blocked, User.blocks?(followed, follower) && deny_follow_blocked},
474
475
           {_, false} <- {:user_locked, User.locked?(followed)},
           {_, {:ok, follower}} <- {:follow, User.follow(follower, followed)},
476
477
           {_, {:ok, _}} <-
             {:follow_state_update, Utils.update_follow_state_for_all(activity, "accept")} do
kaniini's avatar
kaniini committed
478
479
        ActivityPub.accept(%{
          to: [follower.ap_id],
480
          actor: followed,
kaniini's avatar
kaniini committed
481
482
483
          object: data,
          local: true
        })
484
485
      else
        {:user_blocked, true} ->
486
          {:ok, _} = Utils.update_follow_state_for_all(activity, "reject")
487
488
489
490
491
492
493
494
495

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

        {:follow, {:error, _}} ->
496
          {:ok, _} = Utils.update_follow_state_for_all(activity, "reject")
497
498
499
500
501
502
503
504
505
506

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

        {:user_locked, true} ->
          :noop
507
      end
lain's avatar
lain committed
508

509
510
      {:ok, activity}
    else
511
512
      _e ->
        :error
513
514
515
    end
  end

516
  def handle_incoming(
517
518
        %{"type" => "Accept", "object" => follow_object, "actor" => _actor, "id" => _id} = data,
        _options
519
      ) do
520
    with actor <- Containment.get_actor(data),
521
         {:ok, %User{} = followed} <- User.get_or_fetch_by_ap_id(actor),
522
         {:ok, follow_activity} <- get_follow_activity(follow_object, followed),
523
         {:ok, follow_activity} <- Utils.update_follow_state_for_all(follow_activity, "accept"),
524
         %User{local: true} = follower <- User.get_cached_by_ap_id(follow_activity.data["actor"]),
525
526
527
528
529
530
531
532
         {:ok, _follower} = User.follow(follower, followed) do
      ActivityPub.accept(%{
        to: follow_activity.data["to"],
        type: "Accept",
        actor: followed,
        object: follow_activity.data["id"],
        local: false
      })
533
534
    else
      _e -> :error
535
536
537
538
    end
  end

  def handle_incoming(
539
540
        %{"type" => "Reject", "object" => follow_object, "actor" => _actor, "id" => _id} = data,
        _options
541
      ) do
542
    with actor <- Containment.get_actor(data),
543
         {:ok, %User{} = followed} <- User.get_or_fetch_by_ap_id(actor),
544
         {:ok, follow_activity} <- get_follow_activity(follow_object, followed),
545
         {:ok, follow_activity} <- Utils.update_follow_state_for_all(follow_activity, "reject"),
546
         %User{local: true} = follower <- User.get_cached_by_ap_id(follow_activity.data["actor"]),
lain's avatar
lain committed
547
         {:ok, activity} <-
548
           ActivityPub.reject(%{
lain's avatar
lain committed
549
             to: follow_activity.data["to"],
550
             type: "Reject",
551
             actor: followed,
lain's avatar
lain committed
552
553
554
             object: follow_activity.data["id"],
             local: false
           }) do
555
556
      User.unfollow(follower, followed)

557
      {:ok, activity}
558
559
    else
      _e -> :error
560
561
562
    end
  end

lain's avatar
lain committed
563
  def handle_incoming(
564
565
        %{"type" => "Like", "object" => object_id, "actor" => _actor, "id" => id} = data,
        _options
lain's avatar
lain committed
566
      ) do
567
    with actor <- Containment.get_actor(data),
568
         {:ok, %User{} = actor} <- User.get_or_fetch_by_ap_id(actor),
569
         {:ok, object} <- get_obj_helper(object_id),
feld's avatar
feld committed
570
         {:ok, activity, _object} <- ActivityPub.like(actor, object, id, false) do
lain's avatar
lain committed
571
572
573
574
575
576
      {:ok, activity}
    else
      _e -> :error
    end
  end

577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
  def handle_incoming(
        %{
          "type" => "EmojiReaction",
          "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
598
  def handle_incoming(
599
600
        %{"type" => "Announce", "object" => object_id, "actor" => _actor, "id" => id} = data,
        _options
lain's avatar
lain committed
601
      ) do
602
    with actor <- Containment.get_actor(data),
603
         {:ok, %User{} = actor} <- User.get_or_fetch_by_ap_id(actor),
604
         {:ok, object} <- get_obj_helper(object_id),
lain's avatar
lain committed
605
         public <- Visibility.is_public?(data),
606
         {:ok, activity, _object} <- ActivityPub.announce(actor, object, id, false, public) do
lain's avatar
lain committed
607
608
609
610
611
612
      {:ok, activity}
    else
      _e -> :error
    end
  end

lain's avatar
lain committed
613
  def handle_incoming(
614
        %{"type" => "Update", "object" => %{"type" => object_type} = object, "actor" => actor_id} =
615
616
          data,
        _options
617
618
      )
      when object_type in ["Person", "Application", "Service", "Organization"] do
minibikini's avatar
minibikini committed
619
    with %User{ap_id: ^actor_id} = actor <- User.get_cached_by_ap_id(object["id"]) do
lain's avatar
lain committed
620
621
      {:ok, new_user_data} = ActivityPub.user_data_from_user_object(object)

rinpatch's avatar
rinpatch committed
622
623
      banner = new_user_data[:info][:banner]
      locked = new_user_data[:info][:locked] || false
624
625
626
627
628
629
      attachment = get_in(new_user_data, [:info, :source_data, "attachment"]) || []

      fields =
        attachment
        |> Enum.filter(fn %{"type" => t} -> t == "PropertyValue" end)
        |> Enum.map(fn fields -> Map.take(fields, ["name", "value"]) end)
lain's avatar
lain committed
630
631
632
633

      update_data =
        new_user_data
        |> Map.take([:name, :bio, :avatar])
634
        |> Map.put(:info, %{banner: banner, locked: locked, fields: fields})
lain's avatar
lain committed
635
636

      actor
637
      |> User.upgrade_changeset(update_data, true)
lain's avatar
lain committed
638
      |> User.update_and_set_cache()
lain's avatar
lain committed
639

lain's avatar
lain committed
640
641
642
643
644
645
646
      ActivityPub.update(%{
        local: false,
        to: data["to"] || [],
        cc: data["cc"] || [],
        object: object,
        actor: actor_id
      })
lain's avatar
lain committed
647
648
649
650
651
652
653
    else
      e ->
        Logger.error(e)
        :error
    end
  end

654
655
656
657
658
  # 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
659
  def handle_incoming(
660
        %{"type" => "Delete", "object" => object_id, "actor" => actor, "id" => _id} = data,
661
        _options
lain's avatar
lain committed
662
      ) do
lain's avatar
lain committed
663
    object_id = Utils.get_ap_id(object_id)
lain's avatar
lain committed
664

665
    with actor <- Containment.get_actor(data),
666
         {:ok, %User{} = actor} <- User.get_or_fetch_by_ap_id(actor),
667
         {:ok, object} <- get_obj_helper(object_id),
668
         :ok <- Containment.contain_origin(actor.ap_id, object.data),
lain's avatar
lain committed
669
670
671
         {:ok, activity} <- ActivityPub.delete(object, false) do
      {:ok, activity}
    else
672
673
674
      nil ->
        case User.get_cached_by_ap_id(object_id) do
          %User{ap_id: ^actor} = user ->
675
            User.delete(user)
676
677
678
679
680
681
682

          nil ->
            :error
        end

      _e ->
        :error
lain's avatar
lain committed
683
684
685
    end
  end

686
  def handle_incoming(
687
688
        %{
          "type" => "Undo",
689
          "object" => %{"type" => "Announce", "object" => object_id},
Maksim's avatar
Maksim committed
690
          "actor" => _actor,
691
          "id" => id
692
693
        } = data,
        _options
694
      ) do
695
    with actor <- Containment.get_actor(data),
696
         {:ok, %User{} = actor} <- User.get_or_fetch_by_ap_id(actor),
697
         {:ok, object} <- get_obj_helper(object_id),
698
         {:ok, activity, _} <- ActivityPub.unannounce(actor, object, id, false) do
699
700
      {:ok, activity}
    else
Thog's avatar
Thog committed
701
      _e -> :error
702
703
704
    end
  end

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

724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
  def handle_incoming(
        %{
          "type" => "Undo",
          "object" => %{"type" => "EmojiReaction", "id" => reaction_activity_id},
          "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
746
747
748
749
750
751
  def handle_incoming(
        %{
          "type" => "Undo",
          "object" => %{"type" => "Block", "object" => blocked},
          "actor" => blocker,
          "id" => id
752
753
        } = _data,
        _options
normandy's avatar
normandy committed
754
      ) do
755
    with %User{local: true} = blocked <- User.get_cached_by_ap_id(blocked),
756
         {:ok, %User{} = blocker} <- User.get_or_fetch_by_ap_id(blocker),
normandy's avatar
normandy committed
757
         {:ok, activity} <- ActivityPub.unblock(blocker, blocked, id, false) do
normandy's avatar
normandy committed
758
      User.unblock(blocker, blocked)
normandy's avatar
normandy committed
759
760
      {:ok, activity}
    else
Maksim's avatar
Maksim committed
761
      _e -> :error
normandy's avatar
normandy committed
762
763
764
    end
  end

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

Thog's avatar
Thog committed
780
781
782
783
  def handle_incoming(
        %{
          "type" => "Undo",
          "object" => %{"type" => "Like", "object" => object_id},
Maksim's avatar
Maksim committed
784
          "actor" => _actor,
Thog's avatar
Thog committed
785
          "id" => id
786
787
        } = data,
        _options
Thog's avatar
Thog committed
788
      ) do
789
    with actor <- Containment.get_actor(data),
790
         {:ok, %User{} = actor} <- User.get_or_fetch_by_ap_id(actor),
791
         {:ok, object} <- get_obj_helper(object_id),
Thog's avatar
Thog committed
792
793
794
         {:ok, activity, _, _} <- ActivityPub.unlike(actor, object, id, false) do
      {:ok, activity}
    else
Thog's avatar
Thog committed
795
      _e -> :error
Thog's avatar
Thog committed
796
797
798
    end
  end

799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
  # 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

817
  def handle_incoming(_, _), do: :error
818

819
  @spec get_obj_helper(String.t(), Keyword.t()) :: {:ok, Object.t()} | nil
820
  def get_obj_helper(id, options \\ []) do
Maksim's avatar
Maksim committed
821
822
823
    case Object.normalize(id, true, options) do
      %Object{} = object -> {:ok, object}
      _ -> nil
824
    end
825
826
  end

827
828
829
830
  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)
831
832
833
834
    else
      _e -> object
    end
  end
lain's avatar
lain committed
835

836
837
838
  def set_reply_to_uri(obj), do: obj

  # Prepares the object of an outgoing create activity.
lain's avatar
lain committed
839
840
  def prepare_object(object) do
    object
lain's avatar
lain committed
841
    |> set_sensitive
lain's avatar
lain committed
842
    |> add_hashtags
lain's avatar
lain committed
843
    |> add_mention_tags
lain's avatar
lain committed
844
    |> add_emoji_tags
lain's avatar
lain committed
845
    |> add_attributed_to
lain's avatar
lain committed
846
    |> prepare_attachments
lain's avatar
lain committed
847
    |> set_conversation
848
    |> set_reply_to_uri
849
850
    |> strip_internal_fields
    |> strip_internal_tags
851
    |> set_type
lain's avatar
lain committed
852
853
  end

feld's avatar
feld committed
854
855
856
857
  #  @doc
  #  """
  #  internal -> Mastodon
  #  """
lain's avatar
lain committed
858

859
860
  def prepare_outgoing(%{"type" => activity_type, "object" => object_id} = data)
      when activity_type in ["Create", "Listen"] do
lain's avatar
lain committed
861
    object =
minibikini's avatar
minibikini committed
862
863
864
      object_id
      |> Object.normalize()
      |> Map.get(:data)
lain's avatar
lain committed
865
866
867
868
869
      |> prepare_object

    data =
      data
      |> Map.put("object", object)
lain's avatar
lain committed
870
      |> Map.merge(Utils.make_json_ld_header())
minibikini's avatar
minibikini committed
871
      |> Map.delete("bcc")
lain's avatar
lain committed
872
873
874
875

    {:ok, data}
  end

876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
  def prepare_outgoing(%{"type" => "Announce", "actor" => ap_id, "object" => object_id} = data) do
    object =
      object_id
      |> Object.normalize()

    data =
      if Visibility.is_private?(object) && object.data["actor"] == ap_id do
        data |> Map.put("object", object |> Map.get(:data) |> prepare_object)
      else
        data |> maybe_fix_object_url
      end

    data =
      data
      |> strip_internal_fields
      |> Map.merge(Utils.make_json_ld_header())
      |> Map.delete("bcc")

    {:ok, data}
  end

kaniini's avatar
kaniini committed
897
898
899
  # Mastodon Accept/Reject requires a non-normalized object containing the actor URIs,
  # because of course it does.
  def prepare_outgoing(%{"type" => "Accept"} = data) do
900
    with follow_activity <- Activity.normalize(data["object"]) do
kaniini's avatar
kaniini committed
901
902
903
904
905
906
907
908
909
910
      object = %{
        "actor" => follow_activity.actor,
        "object" => follow_activity.data["object"],
        "id" => follow_activity.data["id"],
        "type" => "Follow"
      }

      data =
        data
        |> Map.put("object", object)
lain's avatar
lain committed
911
        |> Map.merge(Utils.make_json_ld_header())
kaniini's avatar
kaniini committed
912
913
914
915
916

      {:ok, data}
    end
  end

917
  def prepare_outgoing(%{"type" => "Reject"} = data) do
918
    with follow_activity <- Activity.normalize(data["object"]) do
919
920
921
922
923
924
925
926
927
928
      object = %{
        "actor" => follow_activity.actor,
        "object" => follow_activity.data["object"],
        "id" => follow_activity.data["id"],
        "type" => "Follow"
      }

      data =
        data
        |> Map.put("object", object)
lain's avatar
lain committed
929
        |> Map.merge(Utils.make_json_ld_header())
930
931
932
933
934

      {:ok, data}
    end
  end

feld's avatar
feld committed
935
  def prepare_outgoing(%{"type" => _type} = data) do
lain's avatar
lain committed
936
937
    data =
      data
938
      |> strip_internal_fields
lain's avatar
lain committed
939
      |> maybe_fix_object_url
lain's avatar
lain committed
940
      |> Map.merge(Utils.make_json_ld_header())
941
942
943
944

    {:ok, data}
  end

945
946
947
948
949
950
  def maybe_fix_object_url(%{"object" => object} = data) when is_binary(object) do
    with false <- String.starts_with?(object, "http"),
         {:fetch, {:ok, relative_object}} <- {:fetch, get_obj_helper(object)},
         %{data: %{"external_url" => external_url}} when not is_nil(external_url) <-
           relative_object do
      Map.put(data, "object", external_url)
951
    else
952
953
954
955
956
957
      {:fetch, e} ->
        Logger.error("Couldn't fetch #{object} #{inspect(e)}")
        data

      _ ->
        data
958
959
960
    end
  end

961
962
  def maybe_fix_object_url(data), do: data

lain's avatar
lain committed
963
  def add_hashtags(object) do
lain's avatar
lain committed
964
965
    tags =
      (object["tag"] || [])
966
967
968
969
970
971
972
973
974
975
976
977
      |> Enum.map(fn
        # Expand internal representation tags into AS2 tags.
        tag when is_binary(tag) ->
          %{
            "href" => Pleroma.Web.Endpoint.url() <> "/tags/#{tag}",
            "name" => "##{tag}",
            "type" => "Hashtag"
          }

        # Do not process tags which are already AS2 tag objects.
        tag when is_map(tag) ->
          tag
lain's avatar
lain committed
978
      end)
lain's avatar
lain committed
979

980
    Map.put(object, "tag", tags)