transmogrifier.ex 31.5 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.
  """
9
  alias Pleroma.Activity
Haelwenn's avatar
Haelwenn committed
10
  alias Pleroma.Object
rinpatch's avatar
rinpatch committed
11
  alias Pleroma.Object.Containment
lain's avatar
lain committed
12
  alias Pleroma.Repo
13
  alias Pleroma.User
14
  alias Pleroma.Web.ActivityPub.ActivityPub
15
  alias Pleroma.Web.ActivityPub.Utils
lain's avatar
lain committed
16
  alias Pleroma.Web.ActivityPub.Visibility
17
  alias Pleroma.Web.Federator
18

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

21
22
  require Logger

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

  def fix_summary(%{"summary" => nil} = object) do
    object
    |> Map.put("summary", "")
  end

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

  def fix_summary(object) do
    object
    |> Map.put("summary", "")
55
56
57
  end

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

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

      true ->
        map
67
68
69
    end
  end

70
71
72
73
74
  def fix_explicit_addressing(
        %{"to" => to, "cc" => cc} = object,
        explicit_mentions,
        follower_collection
      ) do
75
76
77
78
79
80
81
82
83
84
    explicit_to =
      to
      |> Enum.filter(fn x -> x in explicit_mentions end)

    explicit_cc =
      to
      |> Enum.filter(fn x -> x not in explicit_mentions end)

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

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

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

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

98
  def fix_explicit_addressing(object) do
99
100
101
102
    explicit_mentions =
      object
      |> Utils.determine_explicit_mentions()

103
    follower_collection = User.get_cached_by_ap_id(Containment.get_actor(object)).follower_address
104

105
106
    explicit_mentions =
      explicit_mentions ++ ["https://www.w3.org/ns/activitystreams#Public", follower_collection]
107

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

111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
  # 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
        "https://www.w3.org/ns/activitystreams#Public" in cc ->
          to = to ++ [followers_collection]
          Map.put(object, "to", to)

        "https://www.w3.org/ns/activitystreams#Public" in to ->
          cc = cc ++ [followers_collection]
          Map.put(object, "cc", cc)

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

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

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

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

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

154
155
156
157
158
  # Check for standardisation
  # This is what Peertube does
  # curl -H 'Accept: application/activity+json' $likes | jq .totalItems
  # Prismo returns only an integer (count) as "likes"
  def fix_likes(%{"likes" => likes} = object) when not is_map(likes) do
159
160
161
162
163
164
165
166
167
    object
    |> Map.put("likes", [])
    |> Map.put("like_count", 0)
  end

  def fix_likes(object) do
    object
  end

168
169
170
  def fix_in_reply_to(object, options \\ [])

  def fix_in_reply_to(%{"inReplyTo" => in_reply_to} = object, options)
171
172
      when not is_nil(in_reply_to) do
    in_reply_to_id =
173
      cond do
174
175
176
177
178
179
180
181
182
        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)

183
        # Maybe I should output an error too?
184
185
        true ->
          ""
186
187
      end

188
    object = Map.put(object, "inReplyToAtomUri", in_reply_to_id)
lain's avatar
lain committed
189

190
    if Federator.allowed_incoming_reply_depth?(options[:depth]) do
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
      case get_obj_helper(in_reply_to_id, options) do
        {:ok, replied_object} ->
          with %Activity{} = _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
            e ->
              Logger.error("Couldn't fetch \"#{inspect(in_reply_to_id)}\", error: #{inspect(e)}")
              object
          end

        e ->
          Logger.error("Couldn't fetch \"#{inspect(in_reply_to_id)}\", error: #{inspect(e)}")
          object
      end
    else
      object
lain's avatar
lain committed
212
213
    end
  end
lain's avatar
lain committed
214

215
  def fix_in_reply_to(object, _options), do: object
lain's avatar
lain committed
216

lain's avatar
lain committed
217
  def fix_context(object) do
Haelwenn's avatar
Haelwenn committed
218
219
    context = object["context"] || object["conversation"] || Utils.generate_context_id()

lain's avatar
lain committed
220
    object
Haelwenn's avatar
Haelwenn committed
221
222
    |> Map.put("context", context)
    |> Map.put("conversation", context)
lain's avatar
lain committed
223
224
  end

225
  def fix_attachments(%{"attachment" => attachment} = object) when is_list(attachment) do
lain's avatar
lain committed
226
    attachments =
227
      attachment
lain's avatar
lain committed
228
      |> Enum.map(fn data ->
229
230
231
232
233
234
235
236
        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
237
      end)
lain's avatar
lain committed
238
239
240

    object
    |> Map.put("attachment", attachments)
241
242
  end

243
  def fix_attachments(%{"attachment" => attachment} = object) when is_map(attachment) do
244
245
    Map.put(object, "attachment", [attachment])
    |> fix_attachments()
246
247
  end

248
  def fix_attachments(object), do: object
249

250
251
252
253
254
  def fix_url(%{"url" => url} = object) when is_map(url) do
    object
    |> Map.put("url", url["href"])
  end

255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
  def fix_url(%{"type" => "Video", "url" => url} = object) when is_list(url) do
    first_element = Enum.at(url, 0)

    link_element =
      url
      |> Enum.filter(fn x -> is_map(x) end)
      |> Enum.filter(fn x -> x["mimeType"] == "text/html" end)
      |> Enum.at(0)

    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
271
272
273
274
275
276
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

    object
    |> Map.put("url", url_string)
  end

  def fix_url(object), do: object

286
  def fix_emoji(%{"tag" => tags} = object) when is_list(tags) do
lain's avatar
lain committed
287
288
289
290
291
    emoji = tags |> Enum.filter(fn data -> data["type"] == "Emoji" and data["icon"] end)

    emoji =
      emoji
      |> Enum.reduce(%{}, fn data, mapping ->
292
        name = String.trim(data["name"], ":")
lain's avatar
lain committed
293

lain's avatar
lain committed
294
295
        mapping |> Map.put(name, data["icon"]["url"])
      end)
lain's avatar
lain committed
296
297
298
299
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)

    object
    |> Map.put("emoji", emoji)
  end

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

    object
    |> Map.put("emoji", emoji)
  end

312
  def fix_emoji(object), do: object
313

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

320
    combined = tag ++ tags
321
322
323
324
325

    object
    |> Map.put("tag", combined)
  end

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

    object
    |> Map.put("tag", combined)
  end

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

335
  def fix_tag(object), do: object
336

337
338
339
340
341
342
343
344
345
346
347
  # 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)

    object
    |> Map.put("content", content)
  end

  def fix_content_map(object), do: object

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

  def fix_type(%{"inReplyTo" => reply_id} = object, options) when is_binary(reply_id) do
    reply =
352
      if Federator.allowed_incoming_reply_depth?(options[:depth]) do
353
354
        Object.normalize(reply_id, true)
      end
355

356
    if reply && (reply.data["type"] == "Question" and object["name"]) do
357
358
359
360
361
362
      Map.put(object, "type", "Answer")
    else
      object
    end
  end

363
  def fix_type(object, _), do: object
364

Maksim's avatar
Maksim committed
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
  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

391
392
  def handle_incoming(data, options \\ [])

393
394
  # Flag objects are placed ahead of the ID check because Mastodon 2.8 and earlier send them
  # with nil ID.
395
  def handle_incoming(%{"type" => "Flag", "object" => objects, "actor" => actor} = data, _options) do
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
    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.
         %User{} = account <-
           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),

         # Remove the reported user from the object list.
         statuses <- Enum.filter(objects, fn ap_id -> ap_id != account.ap_id end) do
      params = %{
        actor: actor,
        context: context,
        account: account,
        statuses: statuses,
        content: content,
        additional: %{
          "cc" => [account.ap_id]
        }
      }

      ActivityPub.flag(params)
    end
  end

427
  # disallow objects with bogus IDs
428
429
  def handle_incoming(%{"id" => nil}, _options), do: :error
  def handle_incoming(%{"id" => ""}, _options), do: :error
430
  # length of https:// = 8, should validate better, but good enough for now.
431
432
  def handle_incoming(%{"id" => id}, _options) when not (is_binary(id) and length(id) > 8),
    do: :error
433

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

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

448
    with nil <- Activity.get_create_by_object_ap_id(object["id"]),
449
         {:ok, %User{} = user} <- User.get_or_fetch_by_ap_id(data["actor"]) do
450
451
      options = Keyword.put(options, :depth, (options[:depth] || 0) + 1)
      object = fix_object(data["object"], options)
452

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

      ActivityPub.create(params)
    else
lain's avatar
lain committed
470
      %Activity{} = activity -> {:ok, activity}
471
472
473
474
      _e -> :error
    end
  end

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

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

        {:follow, {:error, _}} ->
507
          {:ok, _} = Utils.update_follow_state_for_all(activity, "reject")
508
509
510
511
512
513
514
515
516
517

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

        {:user_locked, true} ->
          :noop
518
      end
lain's avatar
lain committed
519

520
521
      {:ok, activity}
    else
522
523
      _e ->
        :error
524
525
526
    end
  end

527
  def handle_incoming(
528
529
        %{"type" => "Accept", "object" => follow_object, "actor" => _actor, "id" => _id} = data,
        _options
530
      ) do
531
    with actor <- Containment.get_actor(data),
532
         {:ok, %User{} = followed} <- User.get_or_fetch_by_ap_id(actor),
533
         {:ok, follow_activity} <- get_follow_activity(follow_object, followed),
534
         {:ok, follow_activity} <- Utils.update_follow_state_for_all(follow_activity, "accept"),
535
         %User{local: true} = follower <- User.get_cached_by_ap_id(follow_activity.data["actor"]),
536
537
538
539
540
541
542
543
         {: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
      })
544
545
    else
      _e -> :error
546
547
548
549
    end
  end

  def handle_incoming(
550
551
        %{"type" => "Reject", "object" => follow_object, "actor" => _actor, "id" => _id} = data,
        _options
552
      ) do
553
    with actor <- Containment.get_actor(data),
554
         {:ok, %User{} = followed} <- User.get_or_fetch_by_ap_id(actor),
555
         {:ok, follow_activity} <- get_follow_activity(follow_object, followed),
556
         {:ok, follow_activity} <- Utils.update_follow_state_for_all(follow_activity, "reject"),
557
         %User{local: true} = follower <- User.get_cached_by_ap_id(follow_activity.data["actor"]),
lain's avatar
lain committed
558
         {:ok, activity} <-
559
           ActivityPub.reject(%{
lain's avatar
lain committed
560
             to: follow_activity.data["to"],
561
             type: "Reject",
562
             actor: followed,
lain's avatar
lain committed
563
564
565
             object: follow_activity.data["id"],
             local: false
           }) do
566
567
      User.unfollow(follower, followed)

568
      {:ok, activity}
569
570
    else
      _e -> :error
571
572
573
    end
  end

lain's avatar
lain committed
574
  def handle_incoming(
575
576
        %{"type" => "Like", "object" => object_id, "actor" => _actor, "id" => id} = data,
        _options
lain's avatar
lain committed
577
      ) do
578
    with actor <- Containment.get_actor(data),
579
         {:ok, %User{} = actor} <- User.get_or_fetch_by_ap_id(actor),
580
         {:ok, object} <- get_obj_helper(object_id),
feld's avatar
feld committed
581
         {:ok, activity, _object} <- ActivityPub.like(actor, object, id, false) do
lain's avatar
lain committed
582
583
584
585
586
587
      {:ok, activity}
    else
      _e -> :error
    end
  end

lain's avatar
lain committed
588
  def handle_incoming(
589
590
        %{"type" => "Announce", "object" => object_id, "actor" => _actor, "id" => id} = data,
        _options
lain's avatar
lain committed
591
      ) do
592
    with actor <- Containment.get_actor(data),
593
         {:ok, %User{} = actor} <- User.get_or_fetch_by_ap_id(actor),
594
         {:ok, object} <- get_obj_helper(object_id),
lain's avatar
lain committed
595
         public <- Visibility.is_public?(data),
596
         {:ok, activity, _object} <- ActivityPub.announce(actor, object, id, false, public) do
lain's avatar
lain committed
597
598
599
600
601
602
      {:ok, activity}
    else
      _e -> :error
    end
  end

lain's avatar
lain committed
603
  def handle_incoming(
604
        %{"type" => "Update", "object" => %{"type" => object_type} = object, "actor" => actor_id} =
605
606
          data,
        _options
607
608
      )
      when object_type in ["Person", "Application", "Service", "Organization"] do
minibikini's avatar
minibikini committed
609
    with %User{ap_id: ^actor_id} = actor <- User.get_cached_by_ap_id(object["id"]) do
lain's avatar
lain committed
610
611
612
      {:ok, new_user_data} = ActivityPub.user_data_from_user_object(object)

      banner = new_user_data[:info]["banner"]
613
      locked = new_user_data[:info]["locked"] || false
lain's avatar
lain committed
614
615
616
617

      update_data =
        new_user_data
        |> Map.take([:name, :bio, :avatar])
lain's avatar
lain committed
618
        |> Map.put(:info, %{"banner" => banner, "locked" => locked})
lain's avatar
lain committed
619
620
621

      actor
      |> User.upgrade_changeset(update_data)
lain's avatar
lain committed
622
      |> User.update_and_set_cache()
lain's avatar
lain committed
623

lain's avatar
lain committed
624
625
626
627
628
629
630
      ActivityPub.update(%{
        local: false,
        to: data["to"] || [],
        cc: data["cc"] || [],
        object: object,
        actor: actor_id
      })
lain's avatar
lain committed
631
632
633
634
635
636
637
    else
      e ->
        Logger.error(e)
        :error
    end
  end

638
639
640
641
642
  # 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
643
  def handle_incoming(
644
        %{"type" => "Delete", "object" => object_id, "actor" => actor, "id" => _id} = data,
645
        _options
lain's avatar
lain committed
646
      ) do
lain's avatar
lain committed
647
    object_id = Utils.get_ap_id(object_id)
lain's avatar
lain committed
648

649
    with actor <- Containment.get_actor(data),
650
         {:ok, %User{} = actor} <- User.get_or_fetch_by_ap_id(actor),
651
         {:ok, object} <- get_obj_helper(object_id),
652
         :ok <- Containment.contain_origin(actor.ap_id, object.data),
lain's avatar
lain committed
653
654
655
         {:ok, activity} <- ActivityPub.delete(object, false) do
      {:ok, activity}
    else
656
657
658
      nil ->
        case User.get_cached_by_ap_id(object_id) do
          %User{ap_id: ^actor} = user ->
659
            User.delete(user)
660
661
662
663
664
665
666

          nil ->
            :error
        end

      _e ->
        :error
lain's avatar
lain committed
667
668
669
    end
  end

670
  def handle_incoming(
671
672
        %{
          "type" => "Undo",
673
          "object" => %{"type" => "Announce", "object" => object_id},
Maksim's avatar
Maksim committed
674
          "actor" => _actor,
675
          "id" => id
676
677
        } = data,
        _options
678
      ) do
679
    with actor <- Containment.get_actor(data),
680
         {:ok, %User{} = actor} <- User.get_or_fetch_by_ap_id(actor),
681
         {:ok, object} <- get_obj_helper(object_id),
682
         {:ok, activity, _} <- ActivityPub.unannounce(actor, object, id, false) do
683
684
      {:ok, activity}
    else
Thog's avatar
Thog committed
685
      _e -> :error
686
687
688
    end
  end

normandy's avatar
normandy committed
689
690
691
692
693
694
  def handle_incoming(
        %{
          "type" => "Undo",
          "object" => %{"type" => "Follow", "object" => followed},
          "actor" => follower,
          "id" => id
695
696
        } = _data,
        _options
normandy's avatar
normandy committed
697
      ) do
normandy's avatar
normandy committed
698
    with %User{local: true} = followed <- User.get_cached_by_ap_id(followed),
699
         {:ok, %User{} = follower} <- User.get_or_fetch_by_ap_id(follower),
normandy's avatar
normandy committed
700
         {:ok, activity} <- ActivityPub.unfollow(follower, followed, id, false) do
normandy's avatar
normandy committed
701
702
703
      User.unfollow(follower, followed)
      {:ok, activity}
    else
Maksim's avatar
Maksim committed
704
      _e -> :error
normandy's avatar
normandy committed
705
706
707
    end
  end

normandy's avatar
normandy committed
708
709
710
711
712
713
  def handle_incoming(
        %{
          "type" => "Undo",
          "object" => %{"type" => "Block", "object" => blocked},
          "actor" => blocker,
          "id" => id
714
715
        } = _data,
        _options
normandy's avatar
normandy committed
716
      ) do
href's avatar
href committed
717
    with true <- Pleroma.Config.get([:activitypub, :accept_blocks]),
718
         %User{local: true} = blocked <- User.get_cached_by_ap_id(blocked),
719
         {:ok, %User{} = blocker} <- User.get_or_fetch_by_ap_id(blocker),
normandy's avatar
normandy committed
720
         {:ok, activity} <- ActivityPub.unblock(blocker, blocked, id, false) do
normandy's avatar
normandy committed
721
      User.unblock(blocker, blocked)
normandy's avatar
normandy committed
722
723
      {:ok, activity}
    else
Maksim's avatar
Maksim committed
724
      _e -> :error
normandy's avatar
normandy committed
725
726
727
    end
  end

728
  def handle_incoming(
729
730
        %{"type" => "Block", "object" => blocked, "actor" => blocker, "id" => id} = _data,
        _options
731
      ) do
href's avatar
href committed
732
    with true <- Pleroma.Config.get([:activitypub, :accept_blocks]),
733
         %User{local: true} = blocked = User.get_cached_by_ap_id(blocked),
0x1C3B00DA's avatar
0x1C3B00DA committed
734
         {:ok, %User{} = blocker} = User.get_or_fetch_by_ap_id(blocker),
normandy's avatar
normandy committed
735
         {:ok, activity} <- ActivityPub.block(blocker, blocked, id, false) do
736
      User.unfollow(blocker, blocked)
737
      User.block(blocker, blocked)
normandy's avatar
normandy committed
738
739
      {:ok, activity}
    else
Maksim's avatar
Maksim committed
740
      _e -> :error
normandy's avatar
normandy committed
741
742
    end
  end
743

Thog's avatar
Thog committed
744
745
746
747
  def handle_incoming(
        %{
          "type" => "Undo",
          "object" => %{"type" => "Like", "object" => object_id},
Maksim's avatar
Maksim committed
748
          "actor" => _actor,
Thog's avatar
Thog committed
749
          "id" => id
750
751
        } = data,
        _options
Thog's avatar
Thog committed
752
      ) do
753
    with actor <- Containment.get_actor(data),
754
         {:ok, %User{} = actor} <- User.get_or_fetch_by_ap_id(actor),
755
         {:ok, object} <- get_obj_helper(object_id),
Thog's avatar
Thog committed
756
757
758
         {:ok, activity, _, _} <- ActivityPub.unlike(actor, object, id, false) do
      {:ok, activity}
    else
Thog's avatar
Thog committed
759
      _e -> :error
Thog's avatar
Thog committed
760
761
762
    end
  end

763
  def handle_incoming(_, _), do: :error
764

765
766
  def get_obj_helper(id, options \\ []) do
    if object = Object.normalize(id, true, options), do: {:ok, object}, else: nil
767
768
  end

769
770
771
772
  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)
773
774
775
776
    else
      _e -> object
    end
  end
lain's avatar
lain committed
777

778
779
780
  def set_reply_to_uri(obj), do: obj

  # Prepares the object of an outgoing create activity.
lain's avatar
lain committed
781
782
  def prepare_object(object) do
    object
lain's avatar
lain committed
783
    |> set_sensitive
lain's avatar
lain committed
784
    |> add_hashtags
lain's avatar
lain committed
785
    |> add_mention_tags
lain's avatar
lain committed
786
    |> add_emoji_tags
lain's avatar
lain committed
787
    |> add_attributed_to
788
    |> add_likes
lain's avatar
lain committed
789
    |> prepare_attachments
lain's avatar
lain committed
790
    |> set_conversation
791
    |> set_reply_to_uri
792
793
    |> strip_internal_fields
    |> strip_internal_tags
794
    |> set_type
lain's avatar
lain committed
795
796
  end

feld's avatar
feld committed
797
798
799
800
  #  @doc
  #  """
  #  internal -> Mastodon
  #  """
lain's avatar
lain committed
801

802
  def prepare_outgoing(%{"type" => "Create", "object" => object_id} = data) do
lain's avatar
lain committed
803
    object =
minibikini's avatar
minibikini committed
804
805
806
      object_id
      |> Object.normalize()
      |> Map.get(:data)
lain's avatar
lain committed
807
808
809
810
811
      |> prepare_object

    data =
      data
      |> Map.put("object", object)
lain's avatar
lain committed
812
      |> Map.merge(Utils.make_json_ld_header())
minibikini's avatar
minibikini committed
813
      |> Map.delete("bcc")
lain's avatar
lain committed
814
815
816
817

    {:ok, data}
  end

kaniini's avatar
kaniini committed
818
819
820
  # Mastodon Accept/Reject requires a non-normalized object containing the actor URIs,
  # because of course it does.
  def prepare_outgoing(%{"type" => "Accept"} = data) do
821
    with follow_activity <- Activity.normalize(data["object"]) do
kaniini's avatar
kaniini committed
822
823
824
825
826
827
828
829
830
831
      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
832
        |> Map.merge(Utils.make_json_ld_header())
kaniini's avatar
kaniini committed
833
834
835
836
837

      {:ok, data}
    end
  end

838
  def prepare_outgoing(%{"type" => "Reject"} = data) do
839
    with follow_activity <- Activity.normalize(data["object"]) do
840
841
842
843
844
845
846
847
848
849
      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
850
        |> Map.merge(Utils.make_json_ld_header())
851
852
853
854
855

      {:ok, data}
    end
  end

feld's avatar
feld committed
856
  def prepare_outgoing(%{"type" => _type} = data) do
lain's avatar
lain committed
857
858
    data =
      data
859
      |> strip_internal_fields
lain's avatar
lain committed
860
      |> maybe_fix_object_url
lain's avatar
lain committed
861
      |> Map.merge(Utils.make_json_ld_header())
862
863
864
865

    {:ok, data}
  end

866
867
  def maybe_fix_object_url(data) do
    if is_binary(data["object"]) and not String.starts_with?(data["object"], "http") do
868
      case get_obj_helper(data["object"]) do
869
870
        {:ok, relative_object} ->
          if relative_object.data["external_url"] do
feld's avatar
feld committed
871
            _data =
lain's avatar
lain committed
872
873
              data
              |> Map.put("object", relative_object.data["external_url"])
874
875
876
          else
            data
          end
lain's avatar
lain committed
877

878
879
880
881
882
883
884
885
886
        e ->
          Logger.error("Couldn't fetch #{data["object"]} #{inspect(e)}")
          data
      end
    else
      data
    end
  end

lain's avatar
lain committed
887
  def add_hashtags(object) do
lain's avatar
lain committed
888
889
    tags =
      (object["tag"] || [])
890
891
892
893
894
895
896
897
898
899
900
901
      |> 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
902
      end)
lain's avatar
lain committed
903
904
905
906
907

    object
    |> Map.put("tag", tags)
  end

lain's avatar
lain committed
908
  def add_mention_tags(object) do
lain's avatar
lain committed
909
    mentions =
910
911
      object
      |> Utils.get_notified_from_object()
lain's avatar
lain committed
912
913
914
      |> Enum.map(fn user ->
        %{"type" => "Mention", "href" => user.ap_id, "name" => "@#{user.nickname}"}
      end)
lain's avatar
lain committed
915

lain's avatar
lain committed
916
    tags = object["tag"] || []
lain's avatar
lain committed
917
918

    object
lain's avatar
lain committed
919
    |> Map.put("tag", tags ++ mentions)
lain's avatar
lain committed
920
921
  end

Haelwenn's avatar
Haelwenn committed
922
923
924
925
926
927
928
  def add_emoji_tags(%User{info: %{"emoji" => _emoji} = user_info} = object) do
    user_info = add_emoji_tags(user_info)

    object
    |> Map.put(:info, user_info)
  end

lain's avatar
lain committed
929
  # TODO: we should probably send mtime instead of unix epoch time for updated
Haelwenn's avatar
Haelwenn committed
930
  def add_emoji_tags(%{"emoji" => emoji} = object) do
lain's avatar
lain committed
931
    tags = object["tag"] || []
lain's avatar
lain committed
932
933
934
935
936
937
938
939
940
941
942
943

    out =
      emoji
      |> Enum.map(fn {name, url} ->
        %{
          "icon" => %{"url" => url, "type" => "Image"},
          "name" => ":" <> name <> ":",
          "type" => "Emoji",
          "updated" => "1970-01-01T00:00:00Z",
          "id" => url
        }
      end)
lain's avatar
lain committed
944
945
946
947
948

    object
    |> Map.put("tag", tags ++ out)
  end

Haelwenn's avatar
Haelwenn committed
949
950
951
952
  def add_emoji_tags(object) do
    object
  end

lain's avatar
lain committed
953
954
955
956
  def set_conversation(object) do
    Map.put(object, "conversation", object["context"])
  end

lain's avatar
lain committed
957
958
959
960
961
  def set_sensitive(object) do
    tags = object["tag"] || []
    Map.put(object, "sensitive", "nsfw" in tags)
  end

962
963
964
965
966
967
  def set_type(%{"type" => "Answer"} = object) do
    Map.put(object, "type", "Note")
  end

  def set_type(object), do: object

lain's avatar
lain committed
968
  def add_attributed_to(object) do
969
    attributed_to = object["attributedTo"] || object["actor"]
lain's avatar
lain committed
970
971

    object
972
    |> Map.put("attributedTo", attributed_to)
973
  end
lain's avatar
lain committed
974

975
976
977
978
979
980
981
982
983
984
985
  def add_likes(%{"id" => id, "like_count" => likes} = object) do
    likes = %{
      "id" => "#{id}/likes",
      "first" => "#{id}/likes?page=1",
      "type" => "OrderedCollection",
      "totalItems" => likes
    }

    object
    |> Map.put("likes", likes)
  end
lain's avatar
lain committed
986

987
  def add_likes(object) do
lain's avatar
lain committed
988
    object
989
  end
lain's avatar
lain committed
990
991

  def prepare_attachments(object) do
lain's avatar
lain committed
992
993
994
995
996
997
    attachments =
      (object["attachment"] || [])
      |> Enum.map(fn data ->
        [%{"mediaType" => media_type, "href" => href} | _] = data["url"]
        %{"url" => href, "mediaType" => media_type, "name" => data["name"], "type" => "Document"}
      end)
lain's avatar
lain committed
998
999
1000

    object
    |> Map.put("attachment", attachments)
For faster browsing, not all history is shown. View entire blame