transmogrifier.ex 27.6 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
9
defmodule Pleroma.Web.ActivityPub.Transmogrifier do
  @moduledoc """
  A module to handle coding from internal to wire ActivityPub and back.
  """
  alias Pleroma.User
lain's avatar
lain committed
10
  alias Pleroma.Object
11
  alias Pleroma.Object.Containment
12
  alias Pleroma.Activity
Haelwenn's avatar
Haelwenn committed
13
  alias Pleroma.Object
lain's avatar
lain committed
14
  alias Pleroma.Repo
15
  alias Pleroma.User
16
  alias Pleroma.Web.ActivityPub.ActivityPub
17
  alias Pleroma.Web.ActivityPub.Utils
lain's avatar
lain committed
18
  alias Pleroma.Web.ActivityPub.Visibility
19

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

22
23
  require Logger

24
25
26
27
28
  @doc """
  Modifies an incoming AP object (mastodon format) to our internal format.
  """
  def fix_object(object) do
    object
29
    |> fix_actor
30
    |> fix_url
31
    |> fix_attachments
lain's avatar
lain committed
32
    |> fix_context
lain's avatar
lain committed
33
    |> fix_in_reply_to
lain's avatar
lain committed
34
    |> fix_emoji
35
    |> fix_tag
36
    |> fix_content_map
37
    |> fix_likes
38
    |> fix_addressing
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
    |> fix_summary
  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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
  def fix_explicit_addressing(%{"to" => to, "cc" => cc} = object, explicit_mentions) do
    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)
      |> Enum.uniq()

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

  def fix_explicit_addressing(object, _explicit_mentions), do: object

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

93
  def fix_explicit_addressing(object) do
94
95
96
97
98
99
100
101
    explicit_mentions =
      object
      |> Utils.determine_explicit_mentions()

    explicit_mentions = explicit_mentions ++ ["https://www.w3.org/ns/activitystreams#Public"]

    object
    |> fix_explicit_addressing(explicit_mentions)
lain's avatar
lain committed
102
103
  end

104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
  # if as:Public is addressed, then make sure the followers collection is also addressed
  # so that the activities will be delivered to local users.
  def fix_implicit_addressing(%{"to" => to, "cc" => cc} = object, followers_collection) do
    recipients = to ++ cc

    if followers_collection not in recipients do
      cond do
        "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
122
    else
123
      object
124
125
126
    end
  end

127
128
  def fix_implicit_addressing(object, _), do: object

129
  def fix_addressing(object) do
130
    %User{} = user = User.get_or_fetch_by_ap_id(object["actor"])
131
132
    followers_collection = User.ap_followers(user)

133
    object
134
135
136
137
    |> fix_addressing_list("to")
    |> fix_addressing_list("cc")
    |> fix_addressing_list("bto")
    |> fix_addressing_list("bcc")
138
    |> fix_explicit_addressing
139
    |> fix_implicit_addressing(followers_collection)
lain's avatar
lain committed
140
141
  end

142
143
  def fix_actor(%{"attributedTo" => actor} = object) do
    object
144
    |> Map.put("actor", Containment.get_actor(%{"actor" => actor}))
145
146
  end

147
148
149
150
151
  # 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
152
153
154
155
156
157
158
159
160
    object
    |> Map.put("likes", [])
    |> Map.put("like_count", 0)
  end

  def fix_likes(object) do
    object
  end

161
162
163
  def fix_in_reply_to(%{"inReplyTo" => in_reply_to} = object)
      when not is_nil(in_reply_to) do
    in_reply_to_id =
164
      cond do
165
166
167
168
169
170
171
172
173
        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)

174
        # Maybe I should output an error too?
175
176
        true ->
          ""
177
178
      end

179
    case get_obj_helper(in_reply_to_id) do
lain's avatar
lain committed
180
      {:ok, replied_object} ->
rinpatch's avatar
rinpatch committed
181
        with %Activity{} = _activity <-
182
               Activity.get_create_by_object_ap_id(replied_object.data["id"]) do
183
184
185
186
187
188
189
          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 ->
190
            Logger.error("Couldn't fetch \"#{inspect(in_reply_to_id)}\", error: #{inspect(e)}")
191
192
            object
        end
lain's avatar
lain committed
193

lain's avatar
lain committed
194
      e ->
195
        Logger.error("Couldn't fetch \"#{inspect(in_reply_to_id)}\", error: #{inspect(e)}")
lain's avatar
lain committed
196
197
198
        object
    end
  end
lain's avatar
lain committed
199

lain's avatar
lain committed
200
201
  def fix_in_reply_to(object), do: object

lain's avatar
lain committed
202
  def fix_context(object) do
Haelwenn's avatar
Haelwenn committed
203
204
    context = object["context"] || object["conversation"] || Utils.generate_context_id()

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

210
  def fix_attachments(%{"attachment" => attachment} = object) when is_list(attachment) do
lain's avatar
lain committed
211
    attachments =
212
      attachment
lain's avatar
lain committed
213
      |> Enum.map(fn data ->
214
215
216
217
218
219
220
221
        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
222
      end)
lain's avatar
lain committed
223
224
225

    object
    |> Map.put("attachment", attachments)
226
227
  end

228
  def fix_attachments(%{"attachment" => attachment} = object) when is_map(attachment) do
229
230
    Map.put(object, "attachment", [attachment])
    |> fix_attachments()
231
232
  end

233
  def fix_attachments(object), do: object
234

235
236
237
238
239
  def fix_url(%{"url" => url} = object) when is_map(url) do
    object
    |> Map.put("url", url["href"])
  end

240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
  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
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
    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

271
  def fix_emoji(%{"tag" => tags} = object) when is_list(tags) do
lain's avatar
lain committed
272
273
274
275
276
    emoji = tags |> Enum.filter(fn data -> data["type"] == "Emoji" and data["icon"] end)

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

lain's avatar
lain committed
279
280
        mapping |> Map.put(name, data["icon"]["url"])
      end)
lain's avatar
lain committed
281
282
283
284
285
286
287
288

    # 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

289
290
291
292
293
294
295
296
  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

297
  def fix_emoji(object), do: object
298

299
  def fix_tag(%{"tag" => tag} = object) when is_list(tag) do
lain's avatar
lain committed
300
    tags =
301
      tag
lain's avatar
lain committed
302
303
      |> Enum.filter(fn data -> data["type"] == "Hashtag" and data["name"] end)
      |> Enum.map(fn data -> String.slice(data["name"], 1..-1) end)
304

305
    combined = tag ++ tags
306
307
308
309
310

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

311
312
  def fix_tag(%{"tag" => %{"type" => "Hashtag", "name" => hashtag} = tag} = object) do
    combined = [tag, String.slice(hashtag, 1..-1)]
313
314
315
316
317

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

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

320
  def fix_tag(object), do: object
321

322
323
324
325
326
327
328
329
330
331
332
  # 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

Maksim's avatar
Maksim committed
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
  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

359
360
361
362
363
364
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
391
392
  # Flag objects are placed ahead of the ID check because Mastodon 2.8 and earlier send them
  # with nil ID.
  def handle_incoming(%{"type" => "Flag", "object" => objects, "actor" => actor} = data) do
    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

393
394
395
396
397
398
  # disallow objects with bogus IDs
  def handle_incoming(%{"id" => nil}), do: :error
  def handle_incoming(%{"id" => ""}), do: :error
  # length of https:// = 8, should validate better, but good enough for now.
  def handle_incoming(%{"id" => id}) when not (is_binary(id) and length(id) > 8), do: :error

399
400
401
  # TODO: validate those with a Ecto scheme
  # - tags
  # - emoji
kaniini's avatar
kaniini committed
402
  def handle_incoming(%{"type" => "Create", "object" => %{"type" => objtype} = object} = data)
403
      when objtype in ["Article", "Note", "Video", "Page"] do
404
    actor = Containment.get_actor(data)
405
406
407
408

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

410
    with nil <- Activity.get_create_by_object_ap_id(object["id"]),
lain's avatar
lain committed
411
         %User{} = user <- User.get_or_fetch_by_ap_id(data["actor"]) do
412
      object = fix_object(data["object"])
413

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

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

lain's avatar
lain committed
436
437
438
  def handle_incoming(
        %{"type" => "Follow", "object" => followed, "actor" => follower, "id" => id} = data
      ) do
439
    with %User{local: true} = followed <- User.get_cached_by_ap_id(followed),
440
441
         %User{} = follower <- User.get_or_fetch_by_ap_id(follower),
         {:ok, activity} <- ActivityPub.follow(follower, followed, id, false) do
442
      if not User.locked?(followed) do
kaniini's avatar
kaniini committed
443
444
        ActivityPub.accept(%{
          to: [follower.ap_id],
445
          actor: followed,
kaniini's avatar
kaniini committed
446
447
448
449
          object: data,
          local: true
        })

450
451
        User.follow(follower, followed)
      end
lain's avatar
lain committed
452

453
454
455
456
457
458
      {:ok, activity}
    else
      _e -> :error
    end
  end

459
  def handle_incoming(
Maksim's avatar
Maksim committed
460
        %{"type" => "Accept", "object" => follow_object, "actor" => _actor, "id" => _id} = data
461
      ) do
462
    with actor <- Containment.get_actor(data),
463
         %User{} = followed <- User.get_or_fetch_by_ap_id(actor),
464
         {:ok, follow_activity} <- get_follow_activity(follow_object, followed),
465
         {:ok, follow_activity} <- Utils.update_follow_state(follow_activity, "accept"),
466
         %User{local: true} = follower <- User.get_cached_by_ap_id(follow_activity.data["actor"]),
lain's avatar
lain committed
467
468
469
470
         {:ok, activity} <-
           ActivityPub.accept(%{
             to: follow_activity.data["to"],
             type: "Accept",
471
             actor: followed,
lain's avatar
lain committed
472
473
474
             object: follow_activity.data["id"],
             local: false
           }) do
475
      if not User.following?(follower, followed) do
Maksim's avatar
Maksim committed
476
        {:ok, _follower} = User.follow(follower, followed)
477
      end
478

479
      {:ok, activity}
480
481
    else
      _e -> :error
482
483
484
485
    end
  end

  def handle_incoming(
Maksim's avatar
Maksim committed
486
        %{"type" => "Reject", "object" => follow_object, "actor" => _actor, "id" => _id} = data
487
      ) do
488
    with actor <- Containment.get_actor(data),
489
         %User{} = followed <- User.get_or_fetch_by_ap_id(actor),
490
         {:ok, follow_activity} <- get_follow_activity(follow_object, followed),
491
         {:ok, follow_activity} <- Utils.update_follow_state(follow_activity, "reject"),
492
         %User{local: true} = follower <- User.get_cached_by_ap_id(follow_activity.data["actor"]),
lain's avatar
lain committed
493
         {:ok, activity} <-
494
           ActivityPub.reject(%{
lain's avatar
lain committed
495
             to: follow_activity.data["to"],
496
             type: "Reject",
497
             actor: followed,
lain's avatar
lain committed
498
499
500
             object: follow_activity.data["id"],
             local: false
           }) do
501
502
      User.unfollow(follower, followed)

503
      {:ok, activity}
504
505
    else
      _e -> :error
506
507
508
    end
  end

lain's avatar
lain committed
509
  def handle_incoming(
Maksim's avatar
Maksim committed
510
        %{"type" => "Like", "object" => object_id, "actor" => _actor, "id" => id} = data
lain's avatar
lain committed
511
      ) do
512
    with actor <- Containment.get_actor(data),
513
         %User{} = actor <- User.get_or_fetch_by_ap_id(actor),
514
         {:ok, object} <- get_obj_helper(object_id),
feld's avatar
feld committed
515
         {:ok, activity, _object} <- ActivityPub.like(actor, object, id, false) do
lain's avatar
lain committed
516
517
518
519
520
521
      {:ok, activity}
    else
      _e -> :error
    end
  end

lain's avatar
lain committed
522
  def handle_incoming(
Maksim's avatar
Maksim committed
523
        %{"type" => "Announce", "object" => object_id, "actor" => _actor, "id" => id} = data
lain's avatar
lain committed
524
      ) do
525
    with actor <- Containment.get_actor(data),
526
         %User{} = actor <- User.get_or_fetch_by_ap_id(actor),
527
         {:ok, object} <- get_obj_helper(object_id),
lain's avatar
lain committed
528
         public <- Visibility.is_public?(data),
529
         {:ok, activity, _object} <- ActivityPub.announce(actor, object, id, false, public) do
lain's avatar
lain committed
530
531
532
533
534
535
      {:ok, activity}
    else
      _e -> :error
    end
  end

lain's avatar
lain committed
536
  def handle_incoming(
537
        %{"type" => "Update", "object" => %{"type" => object_type} = object, "actor" => actor_id} =
lain's avatar
lain committed
538
          data
539
540
      )
      when object_type in ["Person", "Application", "Service", "Organization"] do
lain's avatar
lain committed
541
542
543
544
    with %User{ap_id: ^actor_id} = actor <- User.get_by_ap_id(object["id"]) do
      {:ok, new_user_data} = ActivityPub.user_data_from_user_object(object)

      banner = new_user_data[:info]["banner"]
545
      locked = new_user_data[:info]["locked"] || false
lain's avatar
lain committed
546
547
548
549

      update_data =
        new_user_data
        |> Map.take([:name, :bio, :avatar])
lain's avatar
lain committed
550
        |> Map.put(:info, %{"banner" => banner, "locked" => locked})
lain's avatar
lain committed
551
552
553

      actor
      |> User.upgrade_changeset(update_data)
lain's avatar
lain committed
554
      |> User.update_and_set_cache()
lain's avatar
lain committed
555

lain's avatar
lain committed
556
557
558
559
560
561
562
      ActivityPub.update(%{
        local: false,
        to: data["to"] || [],
        cc: data["cc"] || [],
        object: object,
        actor: actor_id
      })
lain's avatar
lain committed
563
564
565
566
567
568
569
    else
      e ->
        Logger.error(e)
        :error
    end
  end

570
571
572
573
574
  # 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
575
  def handle_incoming(
576
        %{"type" => "Delete", "object" => object_id, "actor" => _actor, "id" => _id} = data
lain's avatar
lain committed
577
      ) do
lain's avatar
lain committed
578
    object_id = Utils.get_ap_id(object_id)
lain's avatar
lain committed
579

580
    with actor <- Containment.get_actor(data),
581
         %User{} = actor <- User.get_or_fetch_by_ap_id(actor),
582
         {:ok, object} <- get_obj_helper(object_id),
583
         :ok <- Containment.contain_origin(actor.ap_id, object.data),
lain's avatar
lain committed
584
585
586
         {:ok, activity} <- ActivityPub.delete(object, false) do
      {:ok, activity}
    else
feld's avatar
feld committed
587
      _e -> :error
lain's avatar
lain committed
588
589
590
    end
  end

591
  def handle_incoming(
592
593
        %{
          "type" => "Undo",
594
          "object" => %{"type" => "Announce", "object" => object_id},
Maksim's avatar
Maksim committed
595
          "actor" => _actor,
596
          "id" => id
597
        } = data
598
      ) do
599
    with actor <- Containment.get_actor(data),
600
         %User{} = actor <- User.get_or_fetch_by_ap_id(actor),
601
         {:ok, object} <- get_obj_helper(object_id),
602
         {:ok, activity, _} <- ActivityPub.unannounce(actor, object, id, false) do
603
604
      {:ok, activity}
    else
Thog's avatar
Thog committed
605
      _e -> :error
606
607
608
    end
  end

normandy's avatar
normandy committed
609
610
611
612
613
614
  def handle_incoming(
        %{
          "type" => "Undo",
          "object" => %{"type" => "Follow", "object" => followed},
          "actor" => follower,
          "id" => id
normandy's avatar
normandy committed
615
        } = _data
normandy's avatar
normandy committed
616
      ) do
normandy's avatar
normandy committed
617
618
    with %User{local: true} = followed <- User.get_cached_by_ap_id(followed),
         %User{} = follower <- User.get_or_fetch_by_ap_id(follower),
normandy's avatar
normandy committed
619
         {:ok, activity} <- ActivityPub.unfollow(follower, followed, id, false) do
normandy's avatar
normandy committed
620
621
622
      User.unfollow(follower, followed)
      {:ok, activity}
    else
Maksim's avatar
Maksim committed
623
      _e -> :error
normandy's avatar
normandy committed
624
625
626
    end
  end

normandy's avatar
normandy committed
627
628
629
630
631
632
633
634
  def handle_incoming(
        %{
          "type" => "Undo",
          "object" => %{"type" => "Block", "object" => blocked},
          "actor" => blocker,
          "id" => id
        } = _data
      ) do
href's avatar
href committed
635
    with true <- Pleroma.Config.get([:activitypub, :accept_blocks]),
636
         %User{local: true} = blocked <- User.get_cached_by_ap_id(blocked),
normandy's avatar
normandy committed
637
638
         %User{} = blocker <- User.get_or_fetch_by_ap_id(blocker),
         {:ok, activity} <- ActivityPub.unblock(blocker, blocked, id, false) do
normandy's avatar
normandy committed
639
      User.unblock(blocker, blocked)
normandy's avatar
normandy committed
640
641
      {:ok, activity}
    else
Maksim's avatar
Maksim committed
642
      _e -> :error
normandy's avatar
normandy committed
643
644
645
    end
  end

646
  def handle_incoming(
Maksim's avatar
Maksim committed
647
        %{"type" => "Block", "object" => blocked, "actor" => blocker, "id" => id} = _data
648
      ) do
href's avatar
href committed
649
    with true <- Pleroma.Config.get([:activitypub, :accept_blocks]),
650
         %User{local: true} = blocked = User.get_cached_by_ap_id(blocked),
normandy's avatar
normandy committed
651
         %User{} = blocker = User.get_or_fetch_by_ap_id(blocker),
normandy's avatar
normandy committed
652
         {:ok, activity} <- ActivityPub.block(blocker, blocked, id, false) do
653
      User.unfollow(blocker, blocked)
654
      User.block(blocker, blocked)
normandy's avatar
normandy committed
655
656
      {:ok, activity}
    else
Maksim's avatar
Maksim committed
657
      _e -> :error
normandy's avatar
normandy committed
658
659
    end
  end
660

Thog's avatar
Thog committed
661
662
663
664
  def handle_incoming(
        %{
          "type" => "Undo",
          "object" => %{"type" => "Like", "object" => object_id},
Maksim's avatar
Maksim committed
665
          "actor" => _actor,
Thog's avatar
Thog committed
666
          "id" => id
667
        } = data
Thog's avatar
Thog committed
668
      ) do
669
    with actor <- Containment.get_actor(data),
670
         %User{} = actor <- User.get_or_fetch_by_ap_id(actor),
671
         {:ok, object} <- get_obj_helper(object_id),
Thog's avatar
Thog committed
672
673
674
         {:ok, activity, _, _} <- ActivityPub.unlike(actor, object, id, false) do
      {:ok, activity}
    else
Thog's avatar
Thog committed
675
      _e -> :error
Thog's avatar
Thog committed
676
677
678
    end
  end

679
680
  def handle_incoming(_), do: :error

681
  def get_obj_helper(id) do
682
    if object = Object.normalize(id), do: {:ok, object}, else: nil
683
684
  end

685
686
687
688
  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)
689
690
691
692
    else
      _e -> object
    end
  end
lain's avatar
lain committed
693

694
695
696
  def set_reply_to_uri(obj), do: obj

  # Prepares the object of an outgoing create activity.
lain's avatar
lain committed
697
698
  def prepare_object(object) do
    object
lain's avatar
lain committed
699
    |> set_sensitive
lain's avatar
lain committed
700
    |> add_hashtags
lain's avatar
lain committed
701
    |> add_mention_tags
lain's avatar
lain committed
702
    |> add_emoji_tags
lain's avatar
lain committed
703
    |> add_attributed_to
704
    |> add_likes
lain's avatar
lain committed
705
    |> prepare_attachments
lain's avatar
lain committed
706
    |> set_conversation
707
    |> set_reply_to_uri
708
709
    |> strip_internal_fields
    |> strip_internal_tags
lain's avatar
lain committed
710
711
  end

feld's avatar
feld committed
712
713
714
715
  #  @doc
  #  """
  #  internal -> Mastodon
  #  """
lain's avatar
lain committed
716

717
  def prepare_outgoing(%{"type" => "Create", "object" => object_id} = data) do
lain's avatar
lain committed
718
    object =
719
      Object.normalize(object_id).data
lain's avatar
lain committed
720
721
722
723
724
      |> prepare_object

    data =
      data
      |> Map.put("object", object)
lain's avatar
lain committed
725
      |> Map.merge(Utils.make_json_ld_header())
lain's avatar
lain committed
726
727
728
729

    {:ok, data}
  end

kaniini's avatar
kaniini committed
730
731
732
  # Mastodon Accept/Reject requires a non-normalized object containing the actor URIs,
  # because of course it does.
  def prepare_outgoing(%{"type" => "Accept"} = data) do
733
    with follow_activity <- Activity.normalize(data["object"]) do
kaniini's avatar
kaniini committed
734
735
736
737
738
739
740
741
742
743
      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
744
        |> Map.merge(Utils.make_json_ld_header())
kaniini's avatar
kaniini committed
745
746
747
748
749

      {:ok, data}
    end
  end

750
  def prepare_outgoing(%{"type" => "Reject"} = data) do
751
    with follow_activity <- Activity.normalize(data["object"]) do
752
753
754
755
756
757
758
759
760
761
      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
762
        |> Map.merge(Utils.make_json_ld_header())
763
764
765
766
767

      {:ok, data}
    end
  end

feld's avatar
feld committed
768
  def prepare_outgoing(%{"type" => _type} = data) do
lain's avatar
lain committed
769
770
    data =
      data
771
      |> strip_internal_fields
lain's avatar
lain committed
772
      |> maybe_fix_object_url
lain's avatar
lain committed
773
      |> Map.merge(Utils.make_json_ld_header())
774
775
776
777

    {:ok, data}
  end

778
779
  def maybe_fix_object_url(data) do
    if is_binary(data["object"]) and not String.starts_with?(data["object"], "http") do
780
      case get_obj_helper(data["object"]) do
781
782
        {:ok, relative_object} ->
          if relative_object.data["external_url"] do
feld's avatar
feld committed
783
            _data =
lain's avatar
lain committed
784
785
              data
              |> Map.put("object", relative_object.data["external_url"])
786
787
788
          else
            data
          end
lain's avatar
lain committed
789

790
791
792
793
794
795
796
797
798
        e ->
          Logger.error("Couldn't fetch #{data["object"]} #{inspect(e)}")
          data
      end
    else
      data
    end
  end

lain's avatar
lain committed
799
  def add_hashtags(object) do
lain's avatar
lain committed
800
801
    tags =
      (object["tag"] || [])
802
803
804
805
806
807
808
809
810
811
812
813
      |> 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
814
      end)
lain's avatar
lain committed
815
816
817
818
819

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

lain's avatar
lain committed
820
  def add_mention_tags(object) do
lain's avatar
lain committed
821
    mentions =
822
823
      object
      |> Utils.get_notified_from_object()
lain's avatar
lain committed
824
825
826
      |> Enum.map(fn user ->
        %{"type" => "Mention", "href" => user.ap_id, "name" => "@#{user.nickname}"}
      end)
lain's avatar
lain committed
827

lain's avatar
lain committed
828
    tags = object["tag"] || []
lain's avatar
lain committed
829
830

    object
lain's avatar
lain committed
831
    |> Map.put("tag", tags ++ mentions)
lain's avatar
lain committed
832
833
  end

lain's avatar
lain committed
834
835
836
837
  # TODO: we should probably send mtime instead of unix epoch time for updated
  def add_emoji_tags(object) do
    tags = object["tag"] || []
    emoji = object["emoji"] || []
lain's avatar
lain committed
838
839
840
841
842
843
844
845
846
847
848
849

    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
850
851
852
853
854

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

lain's avatar
lain committed
855
856
857
858
  def set_conversation(object) do
    Map.put(object, "conversation", object["context"])
  end

lain's avatar
lain committed
859
860
861
862
863
  def set_sensitive(object) do
    tags = object["tag"] || []
    Map.put(object, "sensitive", "nsfw" in tags)
  end

lain's avatar
lain committed
864
  def add_attributed_to(object) do
865
    attributed_to = object["attributedTo"] || object["actor"]
lain's avatar
lain committed
866
867

    object
868
    |> Map.put("attributedTo", attributed_to)
869
  end
lain's avatar
lain committed
870

871
872
873
874
875
876
877
878
879
880
881
  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
882

883
  def add_likes(object) do
lain's avatar
lain committed
884
    object
885
  end
lain's avatar
lain committed
886
887

  def prepare_attachments(object) do
lain's avatar
lain committed
888
889
890
891
892
893
    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
894
895
896
897

    object
    |> Map.put("attachment", attachments)
  end
lain's avatar
lain committed
898

899
900
901
902
903
904
905
  defp strip_internal_fields(object) do
    object
    |> Map.drop([
      "like_count",
      "announcements",
      "announcement_count",
      "emoji",
906
907
      "context_id",
      "deleted_activity_id"
908
909
910
911
912
913
914
915
916
917
918
919
920
921
    ])
  end

  defp strip_internal_tags(%{"tag" => tags} = object) do
    tags =
      tags
      |> Enum.filter(fn x -> is_map(x) end)

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

  defp strip_internal_tags(object), do: object

922
  def perform(:user_upgrade, user) do
923
924
    # we pass a fake user so that the followers collection is stripped away
    old_follower_address = User.ap_followers(%User{nickname: user.nickname})
lain's avatar
lain committed
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942

    q =
      from(
        u in User,
        where: ^old_follower_address in u.following,
        update: [
          set: [
            following:
              fragment(
                "array_replace(?,?,?)",
                u.following,
                ^old_follower_address,
                ^user.follower_address
              )
          ]
        ]
      )

lain's avatar
lain committed
943
944
    Repo.update_all(q, [])

945
946
    maybe_retire_websub(user.ap_id)

lain's avatar
lain committed
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
    q =
      from(
        a in Activity,
        where: ^old_follower_address in a.recipients,
        update: [
          set: [
            recipients:
              fragment(
                "array_replace(?,?,?)",
                a.recipients,
                ^old_follower_address,
                ^user.follower_address
              )
          ]
        ]
      )

lain's avatar
lain committed
964
965
966
    Repo.update_all(q, [])
  end

967
  def upgrade_user_from_ap_id(ap_id) do
968
    with %User{local: false} = user <- User.get_by_ap_id(ap_id),
969
970
971
972
973
         {:ok, data} <- ActivityPub.fetch_and_prepare_user_from_ap_id(ap_id),
         already_ap <- User.ap_enabled?(user),
         {:ok, user} <- user |> User.upgrade_changeset(data) |> User.update_and_set_cache() do
      unless already_ap do
        PleromaJobQueue.enqueue(:transmogrifier, __MODULE__, [:user_upgrade, user])
lain's avatar
lain committed
974
      end
lain's avatar
lain committed
975
976
977

      {:ok, user}
    else
978
      %User{} = user -> {:ok, user}
lain's avatar
lain committed
979
980
981
      e -> e
    end
  end
982
983
984

  def maybe_retire_websub(ap_id) do
    # some sanity checks
lain's avatar
lain committed
985
986
987
988
989
990
991
    if is_binary(ap_id) && String.length(ap_id) > 8 do
      q =
        from(
          ws in Pleroma.Web.Websub.WebsubClientSubscription,
          where: fragment("? like ?", ws.topic, ^"#{ap_id}%")
        )

992
993
994
      Repo.delete_all(q)
    end
  end
995
996
997

  def maybe_fix_user_url(data) do
    if is_map(data["url"]) do
Thog's avatar
Thog committed
998
999
1000
      Map.put(data, "url", data["url"]["href"])
    else
      data
For faster browsing, not all history is shown. View entire blame