transmogrifier.ex 22 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
  def get_actor(%{"actor" => actor}) when is_binary(actor) do
    actor
  end

  def get_actor(%{"actor" => actor}) when is_list(actor) do
21
22
23
24
25
26
    if is_binary(Enum.at(actor, 0)) do
      Enum.at(actor, 0)
    else
      Enum.find(actor, fn %{"type" => type} -> type == "Person" end)
      |> Map.get("id")
    end
27
28
  end

29
30
31
32
  def get_actor(%{"actor" => actor}) when is_map(actor) do
    actor["id"]
  end

33
34
35
  @doc """
  Checks that an imported AP object's actor matches the domain it came from.
  """
36
  def contain_origin(id, %{"actor" => actor} = params) do
37
    id_uri = URI.parse(id)
38
    actor_uri = URI.parse(get_actor(params))
39
40
41
42
43
44
45
46

    if id_uri.host == actor_uri.host do
      :ok
    else
      :error
    end
  end

47
48
49
50
51
  @doc """
  Modifies an incoming AP object (mastodon format) to our internal format.
  """
  def fix_object(object) do
    object
52
    |> fix_actor
lain's avatar
lain committed
53
    |> fix_attachments
lain's avatar
lain committed
54
    |> fix_context
lain's avatar
lain committed
55
    |> fix_in_reply_to
lain's avatar
lain committed
56
    |> fix_emoji
57
    |> fix_tag
58
    |> fix_content_map
59
    |> fix_likes
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
    |> fix_addressing
  end

  def fix_addressing_list(map, field) do
    if is_binary(map[field]) do
      map
      |> Map.put(field, [map[field]])
    else
      map
    end
  end

  def fix_addressing(map) do
    map
    |> fix_addressing_list("to")
    |> fix_addressing_list("cc")
    |> fix_addressing_list("bto")
    |> fix_addressing_list("bcc")
lain's avatar
lain committed
78
79
  end

80
81
  def fix_actor(%{"attributedTo" => actor} = object) do
    object
82
    |> Map.put("actor", get_actor(%{"actor" => actor}))
83
84
  end

85
86
87
88
89
90
91
92
93
94
95
96
97
98
  def fix_likes(%{"likes" => likes} = object)
      when is_bitstring(likes) do
    # Check for standardisation
    # This is what Peertube does
    # curl -H 'Accept: application/activity+json' $likes | jq .totalItems
    object
    |> Map.put("likes", [])
    |> Map.put("like_count", 0)
  end

  def fix_likes(object) do
    object
  end

99
100
101
102
103
104
105
106
107
108
109
  def fix_in_reply_to(%{"inReplyTo" => in_reply_to} = object)
      when not is_nil(in_reply_to) do
    in_reply_to_id =
      if is_bitstring(in_reply_to) do
        in_reply_to
      else
        if is_map(in_reply_to) && in_reply_to["id"] do
          in_reply_to["id"]
        end
      end

lain's avatar
lain committed
110
    case ActivityPub.fetch_object_from_id(in_reply_to_id) do
lain's avatar
lain committed
111
      {:ok, replied_object} ->
112
113
114
115
116
117
118
119
120
121
122
123
124
        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
125

lain's avatar
lain committed
126
127
128
129
130
      e ->
        Logger.error("Couldn't fetch #{object["inReplyTo"]} #{inspect(e)}")
        object
    end
  end
lain's avatar
lain committed
131

lain's avatar
lain committed
132
133
  def fix_in_reply_to(object), do: object

lain's avatar
lain committed
134
  def fix_context(object) do
Haelwenn's avatar
Haelwenn committed
135
136
    context = object["context"] || object["conversation"] || Utils.generate_context_id()

lain's avatar
lain committed
137
    object
Haelwenn's avatar
Haelwenn committed
138
139
    |> Map.put("context", context)
    |> Map.put("conversation", context)
lain's avatar
lain committed
140
141
  end

142
  def fix_attachments(%{"attachment" => attachment} = object) when is_list(attachment) do
lain's avatar
lain committed
143
    attachments =
144
      attachment
lain's avatar
lain committed
145
146
147
148
      |> Enum.map(fn data ->
        url = [%{"type" => "Link", "mediaType" => data["mediaType"], "href" => data["url"]}]
        Map.put(data, "url", url)
      end)
lain's avatar
lain committed
149
150
151

    object
    |> Map.put("attachment", attachments)
152
153
  end

154
155
156
157
158
159
160
161
162
163
164
165
166
  def fix_attachments(%{"attachment" => attachment} = object) when is_map(attachment) do
    attachment =
      Map.put(attachment, "url", [
        %{"type" => "Link", "mediaType" => attachment["mediaType"], "href" => attachment["url"]}
      ])

    Map.put(object, "attachment", attachment)
  end

  def fix_attachments(object) do
    object
  end

lain's avatar
lain committed
167
  def fix_emoji(object) do
lain's avatar
lain committed
168
169
170
171
172
173
174
175
    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
176
177
        name =
          if String.starts_with?(name, ":") do
lain's avatar
lain committed
178
            name |> String.slice(1..-2)
eal's avatar
eal committed
179
180
181
          else
            name
          end
lain's avatar
lain committed
182

lain's avatar
lain committed
183
184
        mapping |> Map.put(name, data["icon"]["url"])
      end)
lain's avatar
lain committed
185
186
187
188
189
190
191
192

    # 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

193
  def fix_tag(object) do
lain's avatar
lain committed
194
195
196
197
    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)
198
199
200
201
202
203
204

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

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

205
206
207
208
209
210
211
212
213
214
215
  # 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

216
217
218
219
220
221
  # 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

222
223
224
  # TODO: validate those with a Ecto scheme
  # - tags
  # - emoji
kaniini's avatar
kaniini committed
225
  def handle_incoming(%{"type" => "Create", "object" => %{"type" => objtype} = object} = data)
Haelwenn's avatar
Haelwenn committed
226
      when objtype in ["Article", "Note", "Video"] do
227
    actor = get_actor(data)
228
229
230
231

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

lain's avatar
lain committed
233
234
    with nil <- Activity.get_create_activity_by_object_ap_id(object["id"]),
         %User{} = user <- User.get_or_fetch_by_ap_id(data["actor"]) do
235
      object = fix_object(data["object"])
236

237
238
239
240
      params = %{
        to: data["to"],
        object: object,
        actor: user,
lain's avatar
lain committed
241
        context: object["conversation"],
242
243
        local: false,
        published: data["published"],
lain's avatar
lain committed
244
245
246
247
248
        additional:
          Map.take(data, [
            "cc",
            "id"
          ])
249
250
251
252
      }

      ActivityPub.create(params)
    else
lain's avatar
lain committed
253
      %Activity{} = activity -> {:ok, activity}
254
255
256
257
      _e -> :error
    end
  end

lain's avatar
lain committed
258
259
260
  def handle_incoming(
        %{"type" => "Follow", "object" => followed, "actor" => follower, "id" => id} = data
      ) do
261
    with %User{local: true} = followed <- User.get_cached_by_ap_id(followed),
262
263
         %User{} = follower <- User.get_or_fetch_by_ap_id(follower),
         {:ok, activity} <- ActivityPub.follow(follower, followed, id, false) do
264
      if not User.locked?(followed) do
kaniini's avatar
kaniini committed
265
266
267
268
269
270
271
        ActivityPub.accept(%{
          to: [follower.ap_id],
          actor: followed.ap_id,
          object: data,
          local: true
        })

272
273
        User.follow(follower, followed)
      end
lain's avatar
lain committed
274

275
276
277
278
279
280
      {:ok, activity}
    else
      _e -> :error
    end
  end

281
282
283
284
285
286
287
288
289
  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
290

291
  defp mastodon_follow_hack(_), do: {:error, nil}
292

293
294
295
296
297
298
299
300
  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
301

302
      _ ->
303
304
305
306
307
308
309
310
        {: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),
311
312
         {: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
313
314
315
316
317
318
319
320
         {:ok, activity} <-
           ActivityPub.accept(%{
             to: follow_activity.data["to"],
             type: "Accept",
             actor: followed.ap_id,
             object: follow_activity.data["id"],
             local: false
           }) do
321
      if not User.following?(follower, followed) do
322
        {:ok, follower} = User.follow(follower, followed)
323
      end
324

325
      {:ok, activity}
326
327
    else
      _e -> :error
328
329
330
331
332
333
334
    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),
335
336
         {: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
337
338
339
340
341
342
343
344
         {:ok, activity} <-
           ActivityPub.accept(%{
             to: follow_activity.data["to"],
             type: "Accept",
             actor: followed.ap_id,
             object: follow_activity.data["id"],
             local: false
           }) do
345
346
      User.unfollow(follower, followed)

347
      {:ok, activity}
348
349
    else
      _e -> :error
350
351
352
    end
  end

lain's avatar
lain committed
353
  def handle_incoming(
feld's avatar
feld committed
354
        %{"type" => "Like", "object" => object_id, "actor" => actor, "id" => id} = _data
lain's avatar
lain committed
355
      ) do
lain's avatar
lain committed
356
    with %User{} = actor <- User.get_or_fetch_by_ap_id(actor),
lain's avatar
lain committed
357
358
         {:ok, object} <-
           get_obj_helper(object_id) || ActivityPub.fetch_object_from_id(object_id),
feld's avatar
feld committed
359
         {:ok, activity, _object} <- ActivityPub.like(actor, object, id, false) do
lain's avatar
lain committed
360
361
362
363
364
365
      {:ok, activity}
    else
      _e -> :error
    end
  end

lain's avatar
lain committed
366
  def handle_incoming(
feld's avatar
feld committed
367
        %{"type" => "Announce", "object" => object_id, "actor" => actor, "id" => id} = _data
lain's avatar
lain committed
368
      ) do
lain's avatar
lain committed
369
    with %User{} = actor <- User.get_or_fetch_by_ap_id(actor),
lain's avatar
lain committed
370
371
         {:ok, object} <-
           get_obj_helper(object_id) || ActivityPub.fetch_object_from_id(object_id),
feld's avatar
feld committed
372
         {:ok, activity, _object} <- ActivityPub.announce(actor, object, id, false) do
lain's avatar
lain committed
373
374
375
376
377
378
      {:ok, activity}
    else
      _e -> :error
    end
  end

lain's avatar
lain committed
379
  def handle_incoming(
380
        %{"type" => "Update", "object" => %{"type" => object_type} = object, "actor" => actor_id} =
lain's avatar
lain committed
381
          data
382
383
      )
      when object_type in ["Person", "Application", "Service", "Organization"] do
lain's avatar
lain committed
384
385
386
387
    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"]
388
      locked = new_user_data[:info]["locked"] || false
lain's avatar
lain committed
389
390
391
392

      update_data =
        new_user_data
        |> Map.take([:name, :bio, :avatar])
393
        |> Map.put(:info, Map.merge(actor.info, %{"banner" => banner, "locked" => locked}))
lain's avatar
lain committed
394
395
396

      actor
      |> User.upgrade_changeset(update_data)
lain's avatar
lain committed
397
      |> User.update_and_set_cache()
lain's avatar
lain committed
398

lain's avatar
lain committed
399
400
401
402
403
404
405
      ActivityPub.update(%{
        local: false,
        to: data["to"] || [],
        cc: data["cc"] || [],
        object: object,
        actor: actor_id
      })
lain's avatar
lain committed
406
407
408
409
410
411
412
    else
      e ->
        Logger.error(e)
        :error
    end
  end

lain's avatar
lain committed
413
  # TODO: Make secure.
lain's avatar
lain committed
414
  def handle_incoming(
feld's avatar
feld committed
415
        %{"type" => "Delete", "object" => object_id, "actor" => actor, "id" => _id} = _data
lain's avatar
lain committed
416
      ) do
lain's avatar
lain committed
417
    object_id = Utils.get_ap_id(object_id)
lain's avatar
lain committed
418

feld's avatar
feld committed
419
    with %User{} = _actor <- User.get_or_fetch_by_ap_id(actor),
lain's avatar
lain committed
420
421
         {:ok, object} <-
           get_obj_helper(object_id) || ActivityPub.fetch_object_from_id(object_id),
lain's avatar
lain committed
422
423
424
         {:ok, activity} <- ActivityPub.delete(object, false) do
      {:ok, activity}
    else
feld's avatar
feld committed
425
      _e -> :error
lain's avatar
lain committed
426
427
428
    end
  end

429
  def handle_incoming(
430
431
        %{
          "type" => "Undo",
432
          "object" => %{"type" => "Announce", "object" => object_id},
433
434
          "actor" => actor,
          "id" => id
Thog's avatar
Thog committed
435
        } = _data
436
      ) do
437
438
439
    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),
440
         {:ok, activity, _} <- ActivityPub.unannounce(actor, object, id, false) do
441
442
      {:ok, activity}
    else
Thog's avatar
Thog committed
443
      _e -> :error
444
445
446
    end
  end

normandy's avatar
normandy committed
447
448
449
450
451
452
  def handle_incoming(
        %{
          "type" => "Undo",
          "object" => %{"type" => "Follow", "object" => followed},
          "actor" => follower,
          "id" => id
normandy's avatar
normandy committed
453
        } = _data
normandy's avatar
normandy committed
454
      ) do
normandy's avatar
normandy committed
455
456
    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
457
         {:ok, activity} <- ActivityPub.unfollow(follower, followed, id, false) do
normandy's avatar
normandy committed
458
459
460
461
462
463
464
      User.unfollow(follower, followed)
      {:ok, activity}
    else
      e -> :error
    end
  end

465
466
467
  @ap_config Application.get_env(:pleroma, :activitypub)
  @accept_blocks Keyword.get(@ap_config, :accept_blocks)

normandy's avatar
normandy committed
468
469
470
471
472
473
474
475
  def handle_incoming(
        %{
          "type" => "Undo",
          "object" => %{"type" => "Block", "object" => blocked},
          "actor" => blocker,
          "id" => id
        } = _data
      ) do
476
477
    with true <- @accept_blocks,
         %User{local: true} = blocked <- User.get_cached_by_ap_id(blocked),
normandy's avatar
normandy committed
478
479
         %User{} = blocker <- User.get_or_fetch_by_ap_id(blocker),
         {:ok, activity} <- ActivityPub.unblock(blocker, blocked, id, false) do
normandy's avatar
normandy committed
480
      User.unblock(blocker, blocked)
normandy's avatar
normandy committed
481
482
483
484
485
486
      {:ok, activity}
    else
      e -> :error
    end
  end

487
488
489
  def handle_incoming(
        %{"type" => "Block", "object" => blocked, "actor" => blocker, "id" => id} = data
      ) do
490
491
    with true <- @accept_blocks,
         %User{local: true} = blocked = User.get_cached_by_ap_id(blocked),
normandy's avatar
normandy committed
492
         %User{} = blocker = User.get_or_fetch_by_ap_id(blocker),
normandy's avatar
normandy committed
493
         {:ok, activity} <- ActivityPub.block(blocker, blocked, id, false) do
494
      User.unfollow(blocker, blocked)
495
      User.block(blocker, blocked)
normandy's avatar
normandy committed
496
497
498
499
500
      {:ok, activity}
    else
      e -> :error
    end
  end
501

Thog's avatar
Thog committed
502
503
504
505
506
507
  def handle_incoming(
        %{
          "type" => "Undo",
          "object" => %{"type" => "Like", "object" => object_id},
          "actor" => actor,
          "id" => id
Thog's avatar
Thog committed
508
        } = _data
Thog's avatar
Thog committed
509
510
511
512
513
514
515
      ) 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
516
      _e -> :error
Thog's avatar
Thog committed
517
518
519
    end
  end

520
521
  def handle_incoming(_), do: :error

522
  def get_obj_helper(id) do
523
    if object = Object.normalize(id), do: {:ok, object}, else: nil
524
525
  end

526
527
528
529
530
531
532
533
  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
534

535
536
537
  def set_reply_to_uri(obj), do: obj

  # Prepares the object of an outgoing create activity.
lain's avatar
lain committed
538
539
  def prepare_object(object) do
    object
lain's avatar
lain committed
540
    |> set_sensitive
lain's avatar
lain committed
541
    |> add_hashtags
lain's avatar
lain committed
542
    |> add_mention_tags
lain's avatar
lain committed
543
    |> add_emoji_tags
lain's avatar
lain committed
544
    |> add_attributed_to
lain's avatar
lain committed
545
    |> prepare_attachments
lain's avatar
lain committed
546
    |> set_conversation
547
    |> set_reply_to_uri
lain's avatar
lain committed
548
549
  end

feld's avatar
feld committed
550
551
552
553
  #  @doc
  #  """
  #  internal -> Mastodon
  #  """
lain's avatar
lain committed
554

lain's avatar
lain committed
555
  def prepare_outgoing(%{"type" => "Create", "object" => %{"type" => "Note"} = object} = data) do
lain's avatar
lain committed
556
557
558
559
560
561
562
563
    object =
      object
      |> prepare_object

    data =
      data
      |> Map.put("object", object)
      |> Map.put("@context", "https://www.w3.org/ns/activitystreams")
lain's avatar
lain committed
564
565
566
567

    {:ok, data}
  end

kaniini's avatar
kaniini committed
568
569
570
  # Mastodon Accept/Reject requires a non-normalized object containing the actor URIs,
  # because of course it does.
  def prepare_outgoing(%{"type" => "Accept"} = data) do
571
    with follow_activity <- Activity.normalize(data["object"]) do
kaniini's avatar
kaniini committed
572
573
574
575
576
577
578
579
580
581
      object = %{
        "actor" => follow_activity.actor,
        "object" => follow_activity.data["object"],
        "id" => follow_activity.data["id"],
        "type" => "Follow"
      }

      data =
        data
        |> Map.put("object", object)
582
        |> Map.put("@context", "https://www.w3.org/ns/activitystreams")
kaniini's avatar
kaniini committed
583
584
585
586
587

      {:ok, data}
    end
  end

588
  def prepare_outgoing(%{"type" => "Reject"} = data) do
589
    with follow_activity <- Activity.normalize(data["object"]) do
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
      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
606
  def prepare_outgoing(%{"type" => _type} = data) do
lain's avatar
lain committed
607
608
609
610
    data =
      data
      |> maybe_fix_object_url
      |> Map.put("@context", "https://www.w3.org/ns/activitystreams")
611
612
613
614

    {:ok, data}
  end

615
616
617
618
619
  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
620
            _data =
lain's avatar
lain committed
621
622
              data
              |> Map.put("object", relative_object.data["external_url"])
623
624
625
          else
            data
          end
lain's avatar
lain committed
626

627
628
629
630
631
632
633
634
635
        e ->
          Logger.error("Couldn't fetch #{data["object"]} #{inspect(e)}")
          data
      end
    else
      data
    end
  end

lain's avatar
lain committed
636
  def add_hashtags(object) do
lain's avatar
lain committed
637
638
639
640
641
642
643
644
645
    tags =
      (object["tag"] || [])
      |> Enum.map(fn tag ->
        %{
          "href" => Pleroma.Web.Endpoint.url() <> "/tags/#{tag}",
          "name" => "##{tag}",
          "type" => "Hashtag"
        }
      end)
lain's avatar
lain committed
646
647
648
649
650

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

lain's avatar
lain committed
651
  def add_mention_tags(object) do
lain's avatar
lain committed
652
    recipients = object["to"] ++ (object["cc"] || [])
lain's avatar
lain committed
653
654
655
656
657
658
659
660

    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
661

lain's avatar
lain committed
662
    tags = object["tag"] || []
lain's avatar
lain committed
663
664

    object
lain's avatar
lain committed
665
    |> Map.put("tag", tags ++ mentions)
lain's avatar
lain committed
666
667
  end

lain's avatar
lain committed
668
669
670
671
  # 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
672
673
674
675
676
677
678
679
680
681
682
683

    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
684
685
686
687
688

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

lain's avatar
lain committed
689
690
691
692
  def set_conversation(object) do
    Map.put(object, "conversation", object["context"])
  end

lain's avatar
lain committed
693
694
695
696
697
  def set_sensitive(object) do
    tags = object["tag"] || []
    Map.put(object, "sensitive", "nsfw" in tags)
  end

lain's avatar
lain committed
698
699
700
701
702
  def add_attributed_to(object) do
    attributedTo = object["attributedTo"] || object["actor"]

    object
    |> Map.put("attributedTo", attributedTo)
703
  end
lain's avatar
lain committed
704
705

  def prepare_attachments(object) do
lain's avatar
lain committed
706
707
708
709
710
711
    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
712
713
714
715

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

lain's avatar
lain committed
717
718
  defp user_upgrade_task(user) do
    old_follower_address = User.ap_followers(user)
lain's avatar
lain committed
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736

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

739
740
    maybe_retire_websub(user.ap_id)

lain's avatar
lain committed
741
    # Only do this for recent activties, don't go through the whole db.
lain's avatar
lain committed
742
743
    # Only look at the last 1000 activities.
    since = (Repo.aggregate(Activity, :max, :id) || 0) - 1_000
lain's avatar
lain committed
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762

    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
763
764
765
766
    Repo.update_all(q, [])
  end

  def upgrade_user_from_ap_id(ap_id, async \\ true) do
767
    with %User{local: false} = user <- User.get_by_ap_id(ap_id),
lain's avatar
lain committed
768
         {:ok, data} <- ActivityPub.fetch_and_prepare_user_from_ap_id(ap_id) do
lain's avatar
lain committed
769
770
771
      data =
        data
        |> Map.put(:info, Map.merge(user.info, data[:info]))
lain's avatar
lain committed
772

lain's avatar
lain committed
773
      already_ap = User.ap_enabled?(user)
lain's avatar
lain committed
774
775
776
777

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

lain's avatar
lain committed
779
780
781
782
783
784
785
      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
786
          user_upgrade_task(user)
lain's avatar
lain committed
787
        end
lain's avatar
lain committed
788
      end
lain's avatar
lain committed
789
790
791
792
793
794

      {:ok, user}
    else
      e -> e
    end
  end
795
796
797

  def maybe_retire_websub(ap_id) do
    # some sanity checks
lain's avatar
lain committed
798
799
800
801
802
803
804
    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}%")
        )

805
806
807
      Repo.delete_all(q)
    end
  end
808
809
810

  def maybe_fix_user_url(data) do
    if is_map(data["url"]) do
Thog's avatar
Thog committed
811
812
813
      Map.put(data, "url", data["url"]["href"])
    else
      data
814
815
816
817
818
819
820
    end
  end

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