transmogrifier.ex 19.6 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
  @doc """
  Modifies an incoming AP object (mastodon format) to our internal format.
  """
  def fix_object(object) do
    object
    |> Map.put("actor", object["attributedTo"])
lain's avatar
lain committed
22
    |> fix_attachments
lain's avatar
lain committed
23
    |> fix_context
lain's avatar
lain committed
24
    |> fix_in_reply_to
lain's avatar
lain committed
25
    |> fix_emoji
26
    |> fix_tag
27
    |> fix_content_map
lain's avatar
lain committed
28
29
  end

lain's avatar
lain committed
30
31
  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
32
    case ActivityPub.fetch_object_from_id(in_reply_to_id) do
lain's avatar
lain committed
33
      {:ok, replied_object} ->
34
35
36
37
38
39
40
41
42
43
44
45
46
        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
47

lain's avatar
lain committed
48
49
50
51
52
      e ->
        Logger.error("Couldn't fetch #{object["inReplyTo"]} #{inspect(e)}")
        object
    end
  end
lain's avatar
lain committed
53

lain's avatar
lain committed
54
55
  def fix_in_reply_to(object), do: object

lain's avatar
lain committed
56
57
58
  def fix_context(object) do
    object
    |> Map.put("context", object["conversation"])
lain's avatar
lain committed
59
60
61
  end

  def fix_attachments(object) do
lain's avatar
lain committed
62
63
64
65
66
67
    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
68
69
70

    object
    |> Map.put("attachment", attachments)
71
72
  end

lain's avatar
lain committed
73
  def fix_emoji(object) do
lain's avatar
lain committed
74
75
76
77
78
79
80
81
    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
82
83
        name =
          if String.starts_with?(name, ":") do
lain's avatar
lain committed
84
            name |> String.slice(1..-2)
eal's avatar
eal committed
85
86
87
          else
            name
          end
lain's avatar
lain committed
88

lain's avatar
lain committed
89
90
        mapping |> Map.put(name, data["icon"]["url"])
      end)
lain's avatar
lain committed
91
92
93
94
95
96
97
98

    # 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

99
  def fix_tag(object) do
lain's avatar
lain committed
100
101
102
103
    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)
104
105
106
107
108
109
110

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

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

111
112
113
114
115
116
117
118
119
120
121
  # 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

122
123
124
125
  # TODO: validate those with a Ecto scheme
  # - tags
  # - emoji
  def handle_incoming(%{"type" => "Create", "object" => %{"type" => "Note"} = object} = data) do
lain's avatar
lain committed
126
127
    with nil <- Activity.get_create_activity_by_object_ap_id(object["id"]),
         %User{} = user <- User.get_or_fetch_by_ap_id(data["actor"]) do
128
      object = fix_object(data["object"])
129

130
131
132
133
      params = %{
        to: data["to"],
        object: object,
        actor: user,
lain's avatar
lain committed
134
        context: object["conversation"],
135
136
        local: false,
        published: data["published"],
lain's avatar
lain committed
137
138
139
140
141
        additional:
          Map.take(data, [
            "cc",
            "id"
          ])
142
143
144
145
      }

      ActivityPub.create(params)
    else
lain's avatar
lain committed
146
      %Activity{} = activity -> {:ok, activity}
147
148
149
150
      _e -> :error
    end
  end

lain's avatar
lain committed
151
152
153
  def handle_incoming(
        %{"type" => "Follow", "object" => followed, "actor" => follower, "id" => id} = data
      ) do
154
    with %User{local: true} = followed <- User.get_cached_by_ap_id(followed),
155
156
         %User{} = follower <- User.get_or_fetch_by_ap_id(follower),
         {:ok, activity} <- ActivityPub.follow(follower, followed, id, false) do
157
      if not User.locked?(followed) do
kaniini's avatar
kaniini committed
158
159
160
161
162
163
164
        ActivityPub.accept(%{
          to: [follower.ap_id],
          actor: followed.ap_id,
          object: data,
          local: true
        })

165
166
        User.follow(follower, followed)
      end
lain's avatar
lain committed
167

168
169
170
171
172
173
      {:ok, activity}
    else
      _e -> :error
    end
  end

174
175
176
177
178
179
180
181
182
  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
183

184
  defp mastodon_follow_hack(_), do: {:error, nil}
185

186
187
188
189
190
191
192
193
  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
194

195
      _ ->
196
197
198
199
200
201
202
203
        {: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),
204
205
         {: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
206
207
208
209
210
211
212
213
         {:ok, activity} <-
           ActivityPub.accept(%{
             to: follow_activity.data["to"],
             type: "Accept",
             actor: followed.ap_id,
             object: follow_activity.data["id"],
             local: false
           }) do
214
      if not User.following?(follower, followed) do
215
        {:ok, follower} = User.follow(follower, followed)
216
      end
217

218
      {:ok, activity}
219
220
    else
      _e -> :error
221
222
223
224
225
226
227
    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),
228
229
         {: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
230
231
232
233
234
235
236
237
         {:ok, activity} <-
           ActivityPub.accept(%{
             to: follow_activity.data["to"],
             type: "Accept",
             actor: followed.ap_id,
             object: follow_activity.data["id"],
             local: false
           }) do
238
239
      User.unfollow(follower, followed)

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

lain's avatar
lain committed
246
  def handle_incoming(
feld's avatar
feld committed
247
        %{"type" => "Like", "object" => object_id, "actor" => actor, "id" => id} = _data
lain's avatar
lain committed
248
      ) do
lain's avatar
lain committed
249
    with %User{} = actor <- User.get_or_fetch_by_ap_id(actor),
lain's avatar
lain committed
250
251
         {:ok, object} <-
           get_obj_helper(object_id) || ActivityPub.fetch_object_from_id(object_id),
feld's avatar
feld committed
252
         {:ok, activity, _object} <- ActivityPub.like(actor, object, id, false) do
lain's avatar
lain committed
253
254
255
256
257
258
      {:ok, activity}
    else
      _e -> :error
    end
  end

lain's avatar
lain committed
259
  def handle_incoming(
feld's avatar
feld committed
260
        %{"type" => "Announce", "object" => object_id, "actor" => actor, "id" => id} = _data
lain's avatar
lain committed
261
      ) do
lain's avatar
lain committed
262
    with %User{} = actor <- User.get_or_fetch_by_ap_id(actor),
lain's avatar
lain committed
263
264
         {:ok, object} <-
           get_obj_helper(object_id) || ActivityPub.fetch_object_from_id(object_id),
feld's avatar
feld committed
265
         {:ok, activity, _object} <- ActivityPub.announce(actor, object, id, false) do
lain's avatar
lain committed
266
267
268
269
270
271
      {:ok, activity}
    else
      _e -> :error
    end
  end

lain's avatar
lain committed
272
273
274
275
  def handle_incoming(
        %{"type" => "Update", "object" => %{"type" => "Person"} = object, "actor" => actor_id} =
          data
      ) do
lain's avatar
lain committed
276
277
278
279
    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"]
280
      locked = new_user_data[:info]["locked"] || false
lain's avatar
lain committed
281
282
283
284

      update_data =
        new_user_data
        |> Map.take([:name, :bio, :avatar])
285
        |> Map.put(:info, Map.merge(actor.info, %{"banner" => banner, "locked" => locked}))
lain's avatar
lain committed
286
287
288

      actor
      |> User.upgrade_changeset(update_data)
lain's avatar
lain committed
289
      |> User.update_and_set_cache()
lain's avatar
lain committed
290

lain's avatar
lain committed
291
292
293
294
295
296
297
      ActivityPub.update(%{
        local: false,
        to: data["to"] || [],
        cc: data["cc"] || [],
        object: object,
        actor: actor_id
      })
lain's avatar
lain committed
298
299
300
301
302
303
304
    else
      e ->
        Logger.error(e)
        :error
    end
  end

lain's avatar
lain committed
305
  # TODO: Make secure.
lain's avatar
lain committed
306
  def handle_incoming(
feld's avatar
feld committed
307
        %{"type" => "Delete", "object" => object_id, "actor" => actor, "id" => _id} = _data
lain's avatar
lain committed
308
      ) do
lain's avatar
lain committed
309
    object_id = Utils.get_ap_id(object_id)
lain's avatar
lain committed
310

feld's avatar
feld committed
311
    with %User{} = _actor <- User.get_or_fetch_by_ap_id(actor),
lain's avatar
lain committed
312
313
         {:ok, object} <-
           get_obj_helper(object_id) || ActivityPub.fetch_object_from_id(object_id),
lain's avatar
lain committed
314
315
316
         {:ok, activity} <- ActivityPub.delete(object, false) do
      {:ok, activity}
    else
feld's avatar
feld committed
317
      _e -> :error
lain's avatar
lain committed
318
319
320
    end
  end

321
  def handle_incoming(
322
323
        %{
          "type" => "Undo",
324
          "object" => %{"type" => "Announce", "object" => object_id},
325
326
          "actor" => actor,
          "id" => id
Thog's avatar
Thog committed
327
        } = _data
328
      ) do
329
330
331
    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),
332
         {:ok, activity, _} <- ActivityPub.unannounce(actor, object, id, false) do
333
334
      {:ok, activity}
    else
Thog's avatar
Thog committed
335
      _e -> :error
336
337
338
    end
  end

normandy's avatar
normandy committed
339
340
341
342
343
344
  def handle_incoming(
        %{
          "type" => "Undo",
          "object" => %{"type" => "Follow", "object" => followed},
          "actor" => follower,
          "id" => id
normandy's avatar
normandy committed
345
        } = _data
normandy's avatar
normandy committed
346
      ) do
normandy's avatar
normandy committed
347
348
    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
349
         {:ok, activity} <- ActivityPub.unfollow(follower, followed, id, false) do
normandy's avatar
normandy committed
350
351
352
353
354
355
356
      User.unfollow(follower, followed)
      {:ok, activity}
    else
      e -> :error
    end
  end

357
358
359
  @ap_config Application.get_env(:pleroma, :activitypub)
  @accept_blocks Keyword.get(@ap_config, :accept_blocks)

normandy's avatar
normandy committed
360
361
362
363
364
365
366
367
  def handle_incoming(
        %{
          "type" => "Undo",
          "object" => %{"type" => "Block", "object" => blocked},
          "actor" => blocker,
          "id" => id
        } = _data
      ) do
368
369
    with true <- @accept_blocks,
         %User{local: true} = blocked <- User.get_cached_by_ap_id(blocked),
normandy's avatar
normandy committed
370
371
         %User{} = blocker <- User.get_or_fetch_by_ap_id(blocker),
         {:ok, activity} <- ActivityPub.unblock(blocker, blocked, id, false) do
normandy's avatar
normandy committed
372
      User.unblock(blocker, blocked)
normandy's avatar
normandy committed
373
374
375
376
377
378
      {:ok, activity}
    else
      e -> :error
    end
  end

379
380
381
  def handle_incoming(
        %{"type" => "Block", "object" => blocked, "actor" => blocker, "id" => id} = data
      ) do
382
383
    with true <- @accept_blocks,
         %User{local: true} = blocked = User.get_cached_by_ap_id(blocked),
normandy's avatar
normandy committed
384
         %User{} = blocker = User.get_or_fetch_by_ap_id(blocker),
normandy's avatar
normandy committed
385
         {:ok, activity} <- ActivityPub.block(blocker, blocked, id, false) do
386
      User.unfollow(blocker, blocked)
387
      User.block(blocker, blocked)
normandy's avatar
normandy committed
388
389
390
391
392
      {:ok, activity}
    else
      e -> :error
    end
  end
393

Thog's avatar
Thog committed
394
395
396
397
398
399
  def handle_incoming(
        %{
          "type" => "Undo",
          "object" => %{"type" => "Like", "object" => object_id},
          "actor" => actor,
          "id" => id
Thog's avatar
Thog committed
400
        } = _data
Thog's avatar
Thog committed
401
402
403
404
405
406
407
      ) 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
408
      _e -> :error
Thog's avatar
Thog committed
409
410
411
    end
  end

412
413
  def handle_incoming(_), do: :error

414
  def get_obj_helper(id) do
415
    if object = Object.normalize(id), do: {:ok, object}, else: nil
416
417
  end

418
419
420
421
422
423
424
425
  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
426

427
428
429
  def set_reply_to_uri(obj), do: obj

  # Prepares the object of an outgoing create activity.
lain's avatar
lain committed
430
431
  def prepare_object(object) do
    object
lain's avatar
lain committed
432
    |> set_sensitive
lain's avatar
lain committed
433
    |> add_hashtags
lain's avatar
lain committed
434
    |> add_mention_tags
lain's avatar
lain committed
435
    |> add_emoji_tags
lain's avatar
lain committed
436
    |> add_attributed_to
lain's avatar
lain committed
437
    |> prepare_attachments
lain's avatar
lain committed
438
    |> set_conversation
439
    |> set_reply_to_uri
lain's avatar
lain committed
440
441
  end

feld's avatar
feld committed
442
443
444
445
  #  @doc
  #  """
  #  internal -> Mastodon
  #  """
lain's avatar
lain committed
446

lain's avatar
lain committed
447
  def prepare_outgoing(%{"type" => "Create", "object" => %{"type" => "Note"} = object} = data) do
lain's avatar
lain committed
448
449
450
451
452
453
454
455
    object =
      object
      |> prepare_object

    data =
      data
      |> Map.put("object", object)
      |> Map.put("@context", "https://www.w3.org/ns/activitystreams")
lain's avatar
lain committed
456
457
458
459

    {:ok, data}
  end

kaniini's avatar
kaniini committed
460
461
462
  # Mastodon Accept/Reject requires a non-normalized object containing the actor URIs,
  # because of course it does.
  def prepare_outgoing(%{"type" => "Accept"} = data) do
463
464
465
466
467
468
469
470
    follow_activity_id =
      if is_binary(data["object"]) do
        data["object"]
      else
        data["object"]["id"]
      end

    with follow_activity <- Activity.get_by_ap_id(follow_activity_id) do
kaniini's avatar
kaniini committed
471
472
473
474
475
476
477
478
479
480
      object = %{
        "actor" => follow_activity.actor,
        "object" => follow_activity.data["object"],
        "id" => follow_activity.data["id"],
        "type" => "Follow"
      }

      data =
        data
        |> Map.put("object", object)
481
        |> Map.put("@context", "https://www.w3.org/ns/activitystreams")
kaniini's avatar
kaniini committed
482
483
484
485
486

      {:ok, data}
    end
  end

487
  def prepare_outgoing(%{"type" => "Reject"} = data) do
488
489
490
491
492
493
494
495
    follow_activity_id =
      if is_binary(data["object"]) do
        data["object"]
      else
        data["object"]["id"]
      end

    with follow_activity <- Activity.get_by_ap_id(follow_activity_id) do
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
      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
512
  def prepare_outgoing(%{"type" => _type} = data) do
lain's avatar
lain committed
513
514
515
516
    data =
      data
      |> maybe_fix_object_url
      |> Map.put("@context", "https://www.w3.org/ns/activitystreams")
517
518
519
520

    {:ok, data}
  end

521
522
523
524
525
  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
526
            _data =
lain's avatar
lain committed
527
528
              data
              |> Map.put("object", relative_object.data["external_url"])
529
530
531
          else
            data
          end
lain's avatar
lain committed
532

533
534
535
536
537
538
539
540
541
        e ->
          Logger.error("Couldn't fetch #{data["object"]} #{inspect(e)}")
          data
      end
    else
      data
    end
  end

lain's avatar
lain committed
542
  def add_hashtags(object) do
lain's avatar
lain committed
543
544
545
546
547
548
549
550
551
    tags =
      (object["tag"] || [])
      |> Enum.map(fn tag ->
        %{
          "href" => Pleroma.Web.Endpoint.url() <> "/tags/#{tag}",
          "name" => "##{tag}",
          "type" => "Hashtag"
        }
      end)
lain's avatar
lain committed
552
553
554
555
556

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

lain's avatar
lain committed
557
  def add_mention_tags(object) do
lain's avatar
lain committed
558
    recipients = object["to"] ++ (object["cc"] || [])
lain's avatar
lain committed
559
560
561
562
563
564
565
566

    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
567

lain's avatar
lain committed
568
    tags = object["tag"] || []
lain's avatar
lain committed
569
570

    object
lain's avatar
lain committed
571
    |> Map.put("tag", tags ++ mentions)
lain's avatar
lain committed
572
573
  end

lain's avatar
lain committed
574
575
576
577
  # 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
578
579
580
581
582
583
584
585
586
587
588
589

    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
590
591
592
593
594

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

lain's avatar
lain committed
595
596
597
598
  def set_conversation(object) do
    Map.put(object, "conversation", object["context"])
  end

lain's avatar
lain committed
599
600
601
602
603
  def set_sensitive(object) do
    tags = object["tag"] || []
    Map.put(object, "sensitive", "nsfw" in tags)
  end

lain's avatar
lain committed
604
605
606
607
608
  def add_attributed_to(object) do
    attributedTo = object["attributedTo"] || object["actor"]

    object
    |> Map.put("attributedTo", attributedTo)
609
  end
lain's avatar
lain committed
610
611

  def prepare_attachments(object) do
lain's avatar
lain committed
612
613
614
615
616
617
    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
618
619
620
621

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

lain's avatar
lain committed
623
624
  defp user_upgrade_task(user) do
    old_follower_address = User.ap_followers(user)
lain's avatar
lain committed
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642

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

645
646
    maybe_retire_websub(user.ap_id)

lain's avatar
lain committed
647
    # Only do this for recent activties, don't go through the whole db.
lain's avatar
lain committed
648
649
    # Only look at the last 1000 activities.
    since = (Repo.aggregate(Activity, :max, :id) || 0) - 1_000
lain's avatar
lain committed
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668

    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
669
670
671
672
    Repo.update_all(q, [])
  end

  def upgrade_user_from_ap_id(ap_id, async \\ true) do
673
    with %User{local: false} = user <- User.get_by_ap_id(ap_id),
lain's avatar
lain committed
674
         {:ok, data} <- ActivityPub.fetch_and_prepare_user_from_ap_id(ap_id) do
lain's avatar
lain committed
675
676
677
      data =
        data
        |> Map.put(:info, Map.merge(user.info, data[:info]))
lain's avatar
lain committed
678

lain's avatar
lain committed
679
      already_ap = User.ap_enabled?(user)
lain's avatar
lain committed
680
681
682
683

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

lain's avatar
lain committed
685
686
687
688
689
690
691
      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
692
          user_upgrade_task(user)
lain's avatar
lain committed
693
        end
lain's avatar
lain committed
694
      end
lain's avatar
lain committed
695
696
697
698
699
700

      {:ok, user}
    else
      e -> e
    end
  end
701
702
703

  def maybe_retire_websub(ap_id) do
    # some sanity checks
lain's avatar
lain committed
704
705
706
707
708
709
710
    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}%")
        )

711
712
713
      Repo.delete_all(q)
    end
  end
714
715
716

  def maybe_fix_user_url(data) do
    if is_map(data["url"]) do
Thog's avatar
Thog committed
717
718
719
      Map.put(data, "url", data["url"]["href"])
    else
      data
720
721
722
723
724
725
726
    end
  end

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