transmogrifier.ex 19.8 KB
Newer Older
1
2
3
4
5
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
6
  alias Pleroma.Object
7
  alias Pleroma.Activity
lain's avatar
lain committed
8
  alias Pleroma.Repo
9
  alias Pleroma.Web.ActivityPub.ActivityPub
10
  alias Pleroma.Web.ActivityPub.Utils
11

lain's avatar
lain committed
12
13
  import Ecto.Query

14
15
  require Logger

16
17
18
19
20
21
22
23
  def get_actor(%{"actor" => actor}) when is_binary(actor) do
    actor
  end

  def get_actor(%{"actor" => actor}) when is_list(actor) do
    Enum.at(actor, 0)
  end

24
25
26
27
28
  def get_actor(%{"actor" => actor_list}) do
    Enum.find(actor_list, fn %{"type" => type} -> type == "Person" end)
    |> Map.get("id")
  end

29
30
31
32
33
  @doc """
  Modifies an incoming AP object (mastodon format) to our internal format.
  """
  def fix_object(object) do
    object
34
    |> fix_actor
lain's avatar
lain committed
35
    |> fix_attachments
lain's avatar
lain committed
36
    |> fix_context
lain's avatar
lain committed
37
    |> fix_in_reply_to
lain's avatar
lain committed
38
    |> fix_emoji
39
    |> fix_tag
40
    |> fix_content_map
lain's avatar
lain committed
41
42
  end

43
44
  def fix_actor(%{"attributedTo" => actor} = object) do
    object
45
    |> Map.put("actor", get_actor(%{"actor" => actor}))
46
47
  end

lain's avatar
lain committed
48
49
  def fix_in_reply_to(%{"inReplyTo" => in_reply_to_id} = object)
      when not is_nil(in_reply_to_id) do
lain's avatar
lain committed
50
    case ActivityPub.fetch_object_from_id(in_reply_to_id) do
lain's avatar
lain committed
51
      {:ok, replied_object} ->
52
53
54
55
56
57
58
59
60
61
62
63
64
        with %Activity{} = activity <-
               Activity.get_create_activity_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("inReplyToStatusId", activity.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 #{object["inReplyTo"]} #{inspect(e)}")
            object
        end
lain's avatar
lain committed
65

lain's avatar
lain committed
66
67
68
69
70
      e ->
        Logger.error("Couldn't fetch #{object["inReplyTo"]} #{inspect(e)}")
        object
    end
  end
lain's avatar
lain committed
71

lain's avatar
lain committed
72
73
  def fix_in_reply_to(object), do: object

lain's avatar
lain committed
74
75
76
  def fix_context(object) do
    object
    |> Map.put("context", object["conversation"])
lain's avatar
lain committed
77
78
79
  end

  def fix_attachments(object) do
lain's avatar
lain committed
80
81
82
83
84
85
    attachments =
      (object["attachment"] || [])
      |> Enum.map(fn data ->
        url = [%{"type" => "Link", "mediaType" => data["mediaType"], "href" => data["url"]}]
        Map.put(data, "url", url)
      end)
lain's avatar
lain committed
86
87
88

    object
    |> Map.put("attachment", attachments)
89
90
  end

lain's avatar
lain committed
91
  def fix_emoji(object) do
lain's avatar
lain committed
92
93
94
95
96
97
98
99
    tags = object["tag"] || []
    emoji = tags |> Enum.filter(fn data -> data["type"] == "Emoji" and data["icon"] end)

    emoji =
      emoji
      |> Enum.reduce(%{}, fn data, mapping ->
        name = data["name"]

eal's avatar
eal committed
100
101
        name =
          if String.starts_with?(name, ":") do
lain's avatar
lain committed
102
            name |> String.slice(1..-2)
eal's avatar
eal committed
103
104
105
          else
            name
          end
lain's avatar
lain committed
106

lain's avatar
lain committed
107
108
        mapping |> Map.put(name, data["icon"]["url"])
      end)
lain's avatar
lain committed
109
110
111
112
113
114
115
116

    # 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

117
  def fix_tag(object) do
lain's avatar
lain committed
118
119
120
121
    tags =
      (object["tag"] || [])
      |> Enum.filter(fn data -> data["type"] == "Hashtag" and data["name"] end)
      |> Enum.map(fn data -> String.slice(data["name"], 1..-1) end)
122
123
124
125
126
127
128

    combined = (object["tag"] || []) ++ tags

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

129
130
131
132
133
134
135
136
137
138
139
  # 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

140
141
142
  # TODO: validate those with a Ecto scheme
  # - tags
  # - emoji
kaniini's avatar
kaniini committed
143
144
  def handle_incoming(%{"type" => "Create", "object" => %{"type" => objtype} = object} = data)
      when objtype in ["Article", "Note"] do
145
146
147
    actor = get_actor(data)
    data = Map.put(data, "actor", actor)

lain's avatar
lain committed
148
149
    with nil <- Activity.get_create_activity_by_object_ap_id(object["id"]),
         %User{} = user <- User.get_or_fetch_by_ap_id(data["actor"]) do
150
      object = fix_object(data["object"])
151

152
153
154
155
      params = %{
        to: data["to"],
        object: object,
        actor: user,
lain's avatar
lain committed
156
        context: object["conversation"],
157
158
        local: false,
        published: data["published"],
lain's avatar
lain committed
159
160
161
162
163
        additional:
          Map.take(data, [
            "cc",
            "id"
          ])
164
165
166
167
      }

      ActivityPub.create(params)
    else
lain's avatar
lain committed
168
      %Activity{} = activity -> {:ok, activity}
169
170
171
172
      _e -> :error
    end
  end

lain's avatar
lain committed
173
174
175
  def handle_incoming(
        %{"type" => "Follow", "object" => followed, "actor" => follower, "id" => id} = data
      ) do
176
    with %User{local: true} = followed <- User.get_cached_by_ap_id(followed),
177
178
         %User{} = follower <- User.get_or_fetch_by_ap_id(follower),
         {:ok, activity} <- ActivityPub.follow(follower, followed, id, false) do
179
      if not User.locked?(followed) do
kaniini's avatar
kaniini committed
180
181
182
183
184
185
186
        ActivityPub.accept(%{
          to: [follower.ap_id],
          actor: followed.ap_id,
          object: data,
          local: true
        })

187
188
        User.follow(follower, followed)
      end
lain's avatar
lain committed
189

190
191
192
193
194
195
      {:ok, activity}
    else
      _e -> :error
    end
  end

196
197
198
199
200
201
202
203
204
  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
kaniini's avatar
kaniini committed
205

206
  defp mastodon_follow_hack(_), do: {:error, nil}
207

208
209
210
211
212
213
214
215
  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)
lain's avatar
lain committed
216

217
      _ ->
218
219
220
221
222
223
224
225
        {:error, nil}
    end
  end

  def handle_incoming(
        %{"type" => "Accept", "object" => follow_object, "actor" => actor, "id" => id} = data
      ) do
    with %User{} = followed <- User.get_or_fetch_by_ap_id(actor),
226
227
         {:ok, follow_activity} <- get_follow_activity(follow_object, followed),
         %User{local: true} = follower <- User.get_cached_by_ap_id(follow_activity.data["actor"]),
lain's avatar
lain committed
228
229
230
231
232
233
234
235
         {:ok, activity} <-
           ActivityPub.accept(%{
             to: follow_activity.data["to"],
             type: "Accept",
             actor: followed.ap_id,
             object: follow_activity.data["id"],
             local: false
           }) do
236
      if not User.following?(follower, followed) do
237
        {:ok, follower} = User.follow(follower, followed)
238
      end
239

240
      {:ok, activity}
241
242
    else
      _e -> :error
243
244
245
246
247
248
249
    end
  end

  def handle_incoming(
        %{"type" => "Reject", "object" => follow_object, "actor" => actor, "id" => id} = data
      ) do
    with %User{} = followed <- User.get_or_fetch_by_ap_id(actor),
250
251
         {:ok, follow_activity} <- get_follow_activity(follow_object, followed),
         %User{local: true} = follower <- User.get_cached_by_ap_id(follow_activity.data["actor"]),
lain's avatar
lain committed
252
253
254
255
256
257
258
259
         {:ok, activity} <-
           ActivityPub.accept(%{
             to: follow_activity.data["to"],
             type: "Accept",
             actor: followed.ap_id,
             object: follow_activity.data["id"],
             local: false
           }) do
260
261
      User.unfollow(follower, followed)

262
      {:ok, activity}
263
264
    else
      _e -> :error
265
266
267
    end
  end

lain's avatar
lain committed
268
  def handle_incoming(
feld's avatar
feld committed
269
        %{"type" => "Like", "object" => object_id, "actor" => actor, "id" => id} = _data
lain's avatar
lain committed
270
      ) do
lain's avatar
lain committed
271
    with %User{} = actor <- User.get_or_fetch_by_ap_id(actor),
lain's avatar
lain committed
272
273
         {:ok, object} <-
           get_obj_helper(object_id) || ActivityPub.fetch_object_from_id(object_id),
feld's avatar
feld committed
274
         {:ok, activity, _object} <- ActivityPub.like(actor, object, id, false) do
lain's avatar
lain committed
275
276
277
278
279
280
      {:ok, activity}
    else
      _e -> :error
    end
  end

lain's avatar
lain committed
281
  def handle_incoming(
feld's avatar
feld committed
282
        %{"type" => "Announce", "object" => object_id, "actor" => actor, "id" => id} = _data
lain's avatar
lain committed
283
      ) do
lain's avatar
lain committed
284
    with %User{} = actor <- User.get_or_fetch_by_ap_id(actor),
lain's avatar
lain committed
285
286
         {:ok, object} <-
           get_obj_helper(object_id) || ActivityPub.fetch_object_from_id(object_id),
feld's avatar
feld committed
287
         {:ok, activity, _object} <- ActivityPub.announce(actor, object, id, false) do
lain's avatar
lain committed
288
289
290
291
292
293
      {:ok, activity}
    else
      _e -> :error
    end
  end

lain's avatar
lain committed
294
295
296
297
  def handle_incoming(
        %{"type" => "Update", "object" => %{"type" => "Person"} = object, "actor" => actor_id} =
          data
      ) do
lain's avatar
lain committed
298
299
300
301
    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"]
302
      locked = new_user_data[:info]["locked"] || false
lain's avatar
lain committed
303
304
305
306

      update_data =
        new_user_data
        |> Map.take([:name, :bio, :avatar])
307
        |> Map.put(:info, Map.merge(actor.info, %{"banner" => banner, "locked" => locked}))
lain's avatar
lain committed
308
309
310

      actor
      |> User.upgrade_changeset(update_data)
lain's avatar
lain committed
311
      |> User.update_and_set_cache()
lain's avatar
lain committed
312

lain's avatar
lain committed
313
314
315
316
317
318
319
      ActivityPub.update(%{
        local: false,
        to: data["to"] || [],
        cc: data["cc"] || [],
        object: object,
        actor: actor_id
      })
lain's avatar
lain committed
320
321
322
323
324
325
326
    else
      e ->
        Logger.error(e)
        :error
    end
  end

lain's avatar
lain committed
327
  # TODO: Make secure.
lain's avatar
lain committed
328
  def handle_incoming(
feld's avatar
feld committed
329
        %{"type" => "Delete", "object" => object_id, "actor" => actor, "id" => _id} = _data
lain's avatar
lain committed
330
      ) do
lain's avatar
lain committed
331
    object_id = Utils.get_ap_id(object_id)
lain's avatar
lain committed
332

feld's avatar
feld committed
333
    with %User{} = _actor <- User.get_or_fetch_by_ap_id(actor),
lain's avatar
lain committed
334
335
         {:ok, object} <-
           get_obj_helper(object_id) || ActivityPub.fetch_object_from_id(object_id),
lain's avatar
lain committed
336
337
338
         {:ok, activity} <- ActivityPub.delete(object, false) do
      {:ok, activity}
    else
feld's avatar
feld committed
339
      _e -> :error
lain's avatar
lain committed
340
341
342
    end
  end

343
  def handle_incoming(
344
345
        %{
          "type" => "Undo",
346
          "object" => %{"type" => "Announce", "object" => object_id},
347
348
          "actor" => actor,
          "id" => id
Thog's avatar
Thog committed
349
        } = _data
350
      ) do
351
352
353
    with %User{} = actor <- User.get_or_fetch_by_ap_id(actor),
         {:ok, object} <-
           get_obj_helper(object_id) || ActivityPub.fetch_object_from_id(object_id),
354
         {:ok, activity, _} <- ActivityPub.unannounce(actor, object, id, false) do
355
356
      {:ok, activity}
    else
Thog's avatar
Thog committed
357
      _e -> :error
358
359
360
    end
  end

normandy's avatar
normandy committed
361
362
363
364
365
366
  def handle_incoming(
        %{
          "type" => "Undo",
          "object" => %{"type" => "Follow", "object" => followed},
          "actor" => follower,
          "id" => id
normandy's avatar
normandy committed
367
        } = _data
normandy's avatar
normandy committed
368
      ) do
normandy's avatar
normandy committed
369
370
    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
371
         {:ok, activity} <- ActivityPub.unfollow(follower, followed, id, false) do
normandy's avatar
normandy committed
372
373
374
375
376
377
378
      User.unfollow(follower, followed)
      {:ok, activity}
    else
      e -> :error
    end
  end

379
380
381
  @ap_config Application.get_env(:pleroma, :activitypub)
  @accept_blocks Keyword.get(@ap_config, :accept_blocks)

normandy's avatar
normandy committed
382
383
384
385
386
387
388
389
  def handle_incoming(
        %{
          "type" => "Undo",
          "object" => %{"type" => "Block", "object" => blocked},
          "actor" => blocker,
          "id" => id
        } = _data
      ) do
390
391
    with true <- @accept_blocks,
         %User{local: true} = blocked <- User.get_cached_by_ap_id(blocked),
normandy's avatar
normandy committed
392
393
         %User{} = blocker <- User.get_or_fetch_by_ap_id(blocker),
         {:ok, activity} <- ActivityPub.unblock(blocker, blocked, id, false) do
normandy's avatar
normandy committed
394
      User.unblock(blocker, blocked)
normandy's avatar
normandy committed
395
396
397
398
399
400
      {:ok, activity}
    else
      e -> :error
    end
  end

401
402
403
  def handle_incoming(
        %{"type" => "Block", "object" => blocked, "actor" => blocker, "id" => id} = data
      ) do
404
405
    with true <- @accept_blocks,
         %User{local: true} = blocked = User.get_cached_by_ap_id(blocked),
normandy's avatar
normandy committed
406
         %User{} = blocker = User.get_or_fetch_by_ap_id(blocker),
normandy's avatar
normandy committed
407
         {:ok, activity} <- ActivityPub.block(blocker, blocked, id, false) do
408
      User.unfollow(blocker, blocked)
409
      User.block(blocker, blocked)
normandy's avatar
normandy committed
410
411
412
413
414
      {:ok, activity}
    else
      e -> :error
    end
  end
415

Thog's avatar
Thog committed
416
417
418
419
420
421
  def handle_incoming(
        %{
          "type" => "Undo",
          "object" => %{"type" => "Like", "object" => object_id},
          "actor" => actor,
          "id" => id
Thog's avatar
Thog committed
422
        } = _data
Thog's avatar
Thog committed
423
424
425
426
427
428
429
      ) do
    with %User{} = actor <- User.get_or_fetch_by_ap_id(actor),
         {:ok, object} <-
           get_obj_helper(object_id) || ActivityPub.fetch_object_from_id(object_id),
         {:ok, activity, _, _} <- ActivityPub.unlike(actor, object, id, false) do
      {:ok, activity}
    else
Thog's avatar
Thog committed
430
      _e -> :error
Thog's avatar
Thog committed
431
432
433
    end
  end

434
435
  def handle_incoming(_), do: :error

436
  def get_obj_helper(id) do
437
    if object = Object.normalize(id), do: {:ok, object}, else: nil
438
439
  end

440
441
442
443
444
445
446
447
  def set_reply_to_uri(%{"inReplyTo" => inReplyTo} = object) do
    with false <- String.starts_with?(inReplyTo, "http"),
         {:ok, %{data: replied_to_object}} <- get_obj_helper(inReplyTo) do
      Map.put(object, "inReplyTo", replied_to_object["external_url"] || inReplyTo)
    else
      _e -> object
    end
  end
lain's avatar
lain committed
448

449
450
451
  def set_reply_to_uri(obj), do: obj

  # Prepares the object of an outgoing create activity.
lain's avatar
lain committed
452
453
  def prepare_object(object) do
    object
lain's avatar
lain committed
454
    |> set_sensitive
lain's avatar
lain committed
455
    |> add_hashtags
lain's avatar
lain committed
456
    |> add_mention_tags
lain's avatar
lain committed
457
    |> add_emoji_tags
lain's avatar
lain committed
458
    |> add_attributed_to
lain's avatar
lain committed
459
    |> prepare_attachments
lain's avatar
lain committed
460
    |> set_conversation
461
    |> set_reply_to_uri
lain's avatar
lain committed
462
463
  end

feld's avatar
feld committed
464
465
466
467
  #  @doc
  #  """
  #  internal -> Mastodon
  #  """
lain's avatar
lain committed
468

lain's avatar
lain committed
469
  def prepare_outgoing(%{"type" => "Create", "object" => %{"type" => "Note"} = object} = data) do
lain's avatar
lain committed
470
471
472
473
474
475
476
477
    object =
      object
      |> prepare_object

    data =
      data
      |> Map.put("object", object)
      |> Map.put("@context", "https://www.w3.org/ns/activitystreams")
lain's avatar
lain committed
478
479
480
481

    {:ok, data}
  end

kaniini's avatar
kaniini committed
482
483
484
  # Mastodon Accept/Reject requires a non-normalized object containing the actor URIs,
  # because of course it does.
  def prepare_outgoing(%{"type" => "Accept"} = data) do
485
    with follow_activity <- Activity.normalize(data["object"]) do
kaniini's avatar
kaniini committed
486
487
488
489
490
491
492
493
494
495
      object = %{
        "actor" => follow_activity.actor,
        "object" => follow_activity.data["object"],
        "id" => follow_activity.data["id"],
        "type" => "Follow"
      }

      data =
        data
        |> Map.put("object", object)
496
        |> Map.put("@context", "https://www.w3.org/ns/activitystreams")
kaniini's avatar
kaniini committed
497
498
499
500
501

      {:ok, data}
    end
  end

502
  def prepare_outgoing(%{"type" => "Reject"} = data) do
503
    with follow_activity <- Activity.normalize(data["object"]) do
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
      object = %{
        "actor" => follow_activity.actor,
        "object" => follow_activity.data["object"],
        "id" => follow_activity.data["id"],
        "type" => "Follow"
      }

      data =
        data
        |> Map.put("object", object)
        |> Map.put("@context", "https://www.w3.org/ns/activitystreams")

      {:ok, data}
    end
  end

feld's avatar
feld committed
520
  def prepare_outgoing(%{"type" => _type} = data) do
lain's avatar
lain committed
521
522
523
524
    data =
      data
      |> maybe_fix_object_url
      |> Map.put("@context", "https://www.w3.org/ns/activitystreams")
525
526
527
528

    {:ok, data}
  end

529
530
531
532
533
  def maybe_fix_object_url(data) do
    if is_binary(data["object"]) and not String.starts_with?(data["object"], "http") do
      case ActivityPub.fetch_object_from_id(data["object"]) do
        {:ok, relative_object} ->
          if relative_object.data["external_url"] do
feld's avatar
feld committed
534
            _data =
lain's avatar
lain committed
535
536
              data
              |> Map.put("object", relative_object.data["external_url"])
537
538
539
          else
            data
          end
lain's avatar
lain committed
540

541
542
543
544
545
546
547
548
549
        e ->
          Logger.error("Couldn't fetch #{data["object"]} #{inspect(e)}")
          data
      end
    else
      data
    end
  end

lain's avatar
lain committed
550
  def add_hashtags(object) do
lain's avatar
lain committed
551
552
553
554
555
556
557
558
559
    tags =
      (object["tag"] || [])
      |> Enum.map(fn tag ->
        %{
          "href" => Pleroma.Web.Endpoint.url() <> "/tags/#{tag}",
          "name" => "##{tag}",
          "type" => "Hashtag"
        }
      end)
lain's avatar
lain committed
560
561
562
563
564

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

lain's avatar
lain committed
565
  def add_mention_tags(object) do
lain's avatar
lain committed
566
    recipients = object["to"] ++ (object["cc"] || [])
lain's avatar
lain committed
567
568
569
570
571
572
573
574

    mentions =
      recipients
      |> Enum.map(fn ap_id -> User.get_cached_by_ap_id(ap_id) end)
      |> Enum.filter(& &1)
      |> Enum.map(fn user ->
        %{"type" => "Mention", "href" => user.ap_id, "name" => "@#{user.nickname}"}
      end)
lain's avatar
lain committed
575

lain's avatar
lain committed
576
    tags = object["tag"] || []
lain's avatar
lain committed
577
578

    object
lain's avatar
lain committed
579
    |> Map.put("tag", tags ++ mentions)
lain's avatar
lain committed
580
581
  end

lain's avatar
lain committed
582
583
584
585
  # 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
586
587
588
589
590
591
592
593
594
595
596
597

    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
598
599
600
601
602

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

lain's avatar
lain committed
603
604
605
606
  def set_conversation(object) do
    Map.put(object, "conversation", object["context"])
  end

lain's avatar
lain committed
607
608
609
610
611
  def set_sensitive(object) do
    tags = object["tag"] || []
    Map.put(object, "sensitive", "nsfw" in tags)
  end

lain's avatar
lain committed
612
613
614
615
616
  def add_attributed_to(object) do
    attributedTo = object["attributedTo"] || object["actor"]

    object
    |> Map.put("attributedTo", attributedTo)
617
  end
lain's avatar
lain committed
618
619

  def prepare_attachments(object) do
lain's avatar
lain committed
620
621
622
623
624
625
    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
626
627
628
629

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

lain's avatar
lain committed
631
632
  defp user_upgrade_task(user) do
    old_follower_address = User.ap_followers(user)
lain's avatar
lain committed
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650

    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
651
652
    Repo.update_all(q, [])

653
654
    maybe_retire_websub(user.ap_id)

lain's avatar
lain committed
655
    # Only do this for recent activties, don't go through the whole db.
lain's avatar
lain committed
656
657
    # Only look at the last 1000 activities.
    since = (Repo.aggregate(Activity, :max, :id) || 0) - 1_000
lain's avatar
lain committed
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676

    q =
      from(
        a in Activity,
        where: ^old_follower_address in a.recipients,
        where: a.id > ^since,
        update: [
          set: [
            recipients:
              fragment(
                "array_replace(?,?,?)",
                a.recipients,
                ^old_follower_address,
                ^user.follower_address
              )
          ]
        ]
      )

lain's avatar
lain committed
677
678
679
680
    Repo.update_all(q, [])
  end

  def upgrade_user_from_ap_id(ap_id, async \\ true) do
681
    with %User{local: false} = user <- User.get_by_ap_id(ap_id),
lain's avatar
lain committed
682
         {:ok, data} <- ActivityPub.fetch_and_prepare_user_from_ap_id(ap_id) do
lain's avatar
lain committed
683
684
685
      data =
        data
        |> Map.put(:info, Map.merge(user.info, data[:info]))
lain's avatar
lain committed
686

lain's avatar
lain committed
687
      already_ap = User.ap_enabled?(user)
lain's avatar
lain committed
688
689
690
691

      {:ok, user} =
        User.upgrade_changeset(user, data)
        |> Repo.update()
lain's avatar
lain committed
692

lain's avatar
lain committed
693
694
695
696
697
698
699
      if !already_ap do
        # This could potentially take a long time, do it in the background
        if async do
          Task.start(fn ->
            user_upgrade_task(user)
          end)
        else
lain's avatar
lain committed
700
          user_upgrade_task(user)
lain's avatar
lain committed
701
        end
lain's avatar
lain committed
702
      end
lain's avatar
lain committed
703
704
705
706
707
708

      {:ok, user}
    else
      e -> e
    end
  end
709
710
711

  def maybe_retire_websub(ap_id) do
    # some sanity checks
lain's avatar
lain committed
712
713
714
715
716
717
718
    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}%")
        )

719
720
721
      Repo.delete_all(q)
    end
  end
722
723
724

  def maybe_fix_user_url(data) do
    if is_map(data["url"]) do
Thog's avatar
Thog committed
725
726
727
      Map.put(data, "url", data["url"]["href"])
    else
      data
728
729
730
731
732
733
734
    end
  end

  def maybe_fix_user_object(data) do
    data
    |> maybe_fix_user_url
  end
735
end