transmogrifier.ex 23.1 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
    if is_binary(Enum.at(actor, 0)) do
      Enum.at(actor, 0)
    else
24
      Enum.find(actor, fn %{"type" => type} -> type in ["Person", "Service", "Application"] end)
25
26
      |> Map.get("id")
    end
27
28
  end

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

33
34
35
36
  def get_actor(%{"actor" => nil, "attributedTo" => actor}) when not is_nil(actor) do
    get_actor(%{"actor" => actor})
  end

37
38
39
  @doc """
  Checks that an imported AP object's actor matches the domain it came from.
  """
40
41
  def contain_origin(id, %{"actor" => nil}), do: :error

42
  def contain_origin(id, %{"actor" => actor} = params) do
43
    id_uri = URI.parse(id)
44
    actor_uri = URI.parse(get_actor(params))
45
46
47
48
49
50
51
52

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

53
54
55
56
57
  @doc """
  Modifies an incoming AP object (mastodon format) to our internal format.
  """
  def fix_object(object) do
    object
58
    |> fix_actor
lain's avatar
lain committed
59
    |> fix_attachments
lain's avatar
lain committed
60
    |> fix_context
lain's avatar
lain committed
61
    |> fix_in_reply_to
lain's avatar
lain committed
62
    |> fix_emoji
63
    |> fix_tag
64
    |> fix_content_map
65
    |> fix_likes
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
    |> 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
84
85
  end

86
87
  def fix_actor(%{"attributedTo" => actor} = object) do
    object
88
    |> Map.put("actor", get_actor(%{"actor" => actor}))
89
90
  end

91
92
93
94
95
96
97
98
99
100
101
102
103
104
  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

105
106
107
  def fix_in_reply_to(%{"inReplyTo" => in_reply_to} = object)
      when not is_nil(in_reply_to) do
    in_reply_to_id =
108
      cond do
109
110
111
112
113
114
115
116
117
        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)

118
        # Maybe I should output an error too?
119
120
        true ->
          ""
121
122
      end

123
    case fetch_obj_helper(in_reply_to_id) do
lain's avatar
lain committed
124
      {:ok, replied_object} ->
125
126
127
128
129
130
131
132
133
134
        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 ->
135
            Logger.error("Couldn't fetch \"#{inspect(in_reply_to_id)}\", error: #{inspect(e)}")
136
137
            object
        end
lain's avatar
lain committed
138

lain's avatar
lain committed
139
      e ->
140
        Logger.error("Couldn't fetch \"#{inspect(in_reply_to_id)}\", error: #{inspect(e)}")
lain's avatar
lain committed
141
142
143
        object
    end
  end
lain's avatar
lain committed
144

lain's avatar
lain committed
145
146
  def fix_in_reply_to(object), do: object

lain's avatar
lain committed
147
  def fix_context(object) do
Haelwenn's avatar
Haelwenn committed
148
149
    context = object["context"] || object["conversation"] || Utils.generate_context_id()

lain's avatar
lain committed
150
    object
Haelwenn's avatar
Haelwenn committed
151
152
    |> Map.put("context", context)
    |> Map.put("conversation", context)
lain's avatar
lain committed
153
154
  end

155
  def fix_attachments(%{"attachment" => attachment} = object) when is_list(attachment) do
lain's avatar
lain committed
156
    attachments =
157
      attachment
lain's avatar
lain committed
158
159
160
161
      |> Enum.map(fn data ->
        url = [%{"type" => "Link", "mediaType" => data["mediaType"], "href" => data["url"]}]
        Map.put(data, "url", url)
      end)
lain's avatar
lain committed
162
163
164

    object
    |> Map.put("attachment", attachments)
165
166
  end

167
  def fix_attachments(%{"attachment" => attachment} = object) when is_map(attachment) do
168
169
    Map.put(object, "attachment", [attachment])
    |> fix_attachments()
170
171
  end

172
  def fix_attachments(object), do: object
173

174
  def fix_emoji(%{"tag" => tags} = object) when is_list(tags) do
lain's avatar
lain committed
175
176
177
178
179
    emoji = tags |> Enum.filter(fn data -> data["type"] == "Emoji" and data["icon"] end)

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

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

    # 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

192
193
194
195
196
197
198
199
  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

200
  def fix_emoji(object), do: object
201

202
  def fix_tag(%{"tag" => tag} = object) when is_list(tag) do
lain's avatar
lain committed
203
    tags =
204
      tag
lain's avatar
lain committed
205
206
      |> Enum.filter(fn data -> data["type"] == "Hashtag" and data["name"] end)
      |> Enum.map(fn data -> String.slice(data["name"], 1..-1) end)
207

208
    combined = tag ++ tags
209
210
211
212
213

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

214
215
  def fix_tag(%{"tag" => %{"type" => "Hashtag", "name" => hashtag} = tag} = object) do
    combined = [tag, String.slice(hashtag, 1..-1)]
216
217
218
219
220

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

221
  def fix_tag(object), do: object
222

223
224
225
226
227
228
229
230
231
232
233
  # 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

234
235
236
237
238
239
  # 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

240
241
242
  # TODO: validate those with a Ecto scheme
  # - tags
  # - emoji
kaniini's avatar
kaniini committed
243
  def handle_incoming(%{"type" => "Create", "object" => %{"type" => objtype} = object} = data)
Haelwenn's avatar
Haelwenn committed
244
      when objtype in ["Article", "Note", "Video"] do
245
    actor = get_actor(data)
246
247
248
249

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

lain's avatar
lain committed
251
252
    with nil <- Activity.get_create_activity_by_object_ap_id(object["id"]),
         %User{} = user <- User.get_or_fetch_by_ap_id(data["actor"]) do
253
      object = fix_object(data["object"])
254

255
256
257
258
      params = %{
        to: data["to"],
        object: object,
        actor: user,
lain's avatar
lain committed
259
        context: object["conversation"],
260
261
        local: false,
        published: data["published"],
lain's avatar
lain committed
262
263
264
265
266
        additional:
          Map.take(data, [
            "cc",
            "id"
          ])
267
268
269
270
      }

      ActivityPub.create(params)
    else
lain's avatar
lain committed
271
      %Activity{} = activity -> {:ok, activity}
272
273
274
275
      _e -> :error
    end
  end

lain's avatar
lain committed
276
277
278
  def handle_incoming(
        %{"type" => "Follow", "object" => followed, "actor" => follower, "id" => id} = data
      ) do
279
    with %User{local: true} = followed <- User.get_cached_by_ap_id(followed),
280
281
         %User{} = follower <- User.get_or_fetch_by_ap_id(follower),
         {:ok, activity} <- ActivityPub.follow(follower, followed, id, false) do
282
      if not User.locked?(followed) do
kaniini's avatar
kaniini committed
283
284
285
286
287
288
289
        ActivityPub.accept(%{
          to: [follower.ap_id],
          actor: followed.ap_id,
          object: data,
          local: true
        })

290
291
        User.follow(follower, followed)
      end
lain's avatar
lain committed
292

293
294
295
296
297
298
      {:ok, activity}
    else
      _e -> :error
    end
  end

299
300
301
302
303
304
305
306
307
  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
308

309
  defp mastodon_follow_hack(_), do: {:error, nil}
310

311
312
313
314
315
316
317
318
  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
319

320
      _ ->
321
322
323
324
325
326
327
        {:error, nil}
    end
  end

  def handle_incoming(
        %{"type" => "Accept", "object" => follow_object, "actor" => actor, "id" => id} = data
      ) do
328
329
    with actor <- get_actor(data),
         %User{} = followed <- User.get_or_fetch_by_ap_id(actor),
330
         {:ok, follow_activity} <- get_follow_activity(follow_object, followed),
331
         {:ok, follow_activity} <- Utils.update_follow_state(follow_activity, "accept"),
332
         %User{local: true} = follower <- User.get_cached_by_ap_id(follow_activity.data["actor"]),
lain's avatar
lain committed
333
334
335
336
337
338
339
340
         {:ok, activity} <-
           ActivityPub.accept(%{
             to: follow_activity.data["to"],
             type: "Accept",
             actor: followed.ap_id,
             object: follow_activity.data["id"],
             local: false
           }) do
341
      if not User.following?(follower, followed) do
342
        {:ok, follower} = User.follow(follower, followed)
343
      end
344

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

  def handle_incoming(
        %{"type" => "Reject", "object" => follow_object, "actor" => actor, "id" => id} = data
      ) do
354
355
    with actor <- get_actor(data),
         %User{} = followed <- User.get_or_fetch_by_ap_id(actor),
356
         {:ok, follow_activity} <- get_follow_activity(follow_object, followed),
357
         {:ok, follow_activity} <- Utils.update_follow_state(follow_activity, "reject"),
358
         %User{local: true} = follower <- User.get_cached_by_ap_id(follow_activity.data["actor"]),
lain's avatar
lain committed
359
360
361
362
363
364
365
366
         {:ok, activity} <-
           ActivityPub.accept(%{
             to: follow_activity.data["to"],
             type: "Accept",
             actor: followed.ap_id,
             object: follow_activity.data["id"],
             local: false
           }) do
367
368
      User.unfollow(follower, followed)

369
      {:ok, activity}
370
371
    else
      _e -> :error
372
373
374
    end
  end

lain's avatar
lain committed
375
  def handle_incoming(
376
        %{"type" => "Like", "object" => object_id, "actor" => actor, "id" => id} = data
lain's avatar
lain committed
377
      ) do
378
379
380
    with actor <- get_actor(data),
         %User{} = actor <- User.get_or_fetch_by_ap_id(actor),
         {:ok, object} <- get_obj_helper(object_id) || fetch_obj_helper(object_id),
feld's avatar
feld committed
381
         {:ok, activity, _object} <- ActivityPub.like(actor, object, id, false) do
lain's avatar
lain committed
382
383
384
385
386
387
      {:ok, activity}
    else
      _e -> :error
    end
  end

lain's avatar
lain committed
388
  def handle_incoming(
389
        %{"type" => "Announce", "object" => object_id, "actor" => actor, "id" => id} = data
lain's avatar
lain committed
390
      ) do
391
392
393
    with actor <- get_actor(data),
         %User{} = actor <- User.get_or_fetch_by_ap_id(actor),
         {:ok, object} <- get_obj_helper(object_id) || fetch_obj_helper(object_id),
feld's avatar
feld committed
394
         {:ok, activity, _object} <- ActivityPub.announce(actor, object, id, false) do
lain's avatar
lain committed
395
396
397
398
399
400
      {:ok, activity}
    else
      _e -> :error
    end
  end

lain's avatar
lain committed
401
  def handle_incoming(
402
        %{"type" => "Update", "object" => %{"type" => object_type} = object, "actor" => actor_id} =
lain's avatar
lain committed
403
          data
404
405
      )
      when object_type in ["Person", "Application", "Service", "Organization"] do
lain's avatar
lain committed
406
407
408
409
    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"]
410
      locked = new_user_data[:info]["locked"] || false
lain's avatar
lain committed
411
412
413
414

      update_data =
        new_user_data
        |> Map.take([:name, :bio, :avatar])
415
        |> Map.put(:info, Map.merge(actor.info, %{"banner" => banner, "locked" => locked}))
lain's avatar
lain committed
416
417
418

      actor
      |> User.upgrade_changeset(update_data)
lain's avatar
lain committed
419
      |> User.update_and_set_cache()
lain's avatar
lain committed
420

lain's avatar
lain committed
421
422
423
424
425
426
427
      ActivityPub.update(%{
        local: false,
        to: data["to"] || [],
        cc: data["cc"] || [],
        object: object,
        actor: actor_id
      })
lain's avatar
lain committed
428
429
430
431
432
433
434
    else
      e ->
        Logger.error(e)
        :error
    end
  end

lain's avatar
lain committed
435
  # TODO: Make secure.
lain's avatar
lain committed
436
  def handle_incoming(
437
        %{"type" => "Delete", "object" => object_id, "actor" => actor, "id" => _id} = data
lain's avatar
lain committed
438
      ) do
lain's avatar
lain committed
439
    object_id = Utils.get_ap_id(object_id)
lain's avatar
lain committed
440

441
442
443
    with actor <- get_actor(data),
         %User{} = _actor <- User.get_or_fetch_by_ap_id(actor),
         {:ok, object} <- get_obj_helper(object_id) || fetch_obj_helper(object_id),
lain's avatar
lain committed
444
445
446
         {:ok, activity} <- ActivityPub.delete(object, false) do
      {:ok, activity}
    else
feld's avatar
feld committed
447
      _e -> :error
lain's avatar
lain committed
448
449
450
    end
  end

451
  def handle_incoming(
452
453
        %{
          "type" => "Undo",
454
          "object" => %{"type" => "Announce", "object" => object_id},
455
456
          "actor" => actor,
          "id" => id
457
        } = data
458
      ) do
459
460
461
    with actor <- get_actor(data),
         %User{} = actor <- User.get_or_fetch_by_ap_id(actor),
         {:ok, object} <- get_obj_helper(object_id) || fetch_obj_helper(object_id),
462
         {:ok, activity, _} <- ActivityPub.unannounce(actor, object, id, false) do
463
464
      {:ok, activity}
    else
Thog's avatar
Thog committed
465
      _e -> :error
466
467
468
    end
  end

normandy's avatar
normandy committed
469
470
471
472
473
474
  def handle_incoming(
        %{
          "type" => "Undo",
          "object" => %{"type" => "Follow", "object" => followed},
          "actor" => follower,
          "id" => id
normandy's avatar
normandy committed
475
        } = _data
normandy's avatar
normandy committed
476
      ) do
normandy's avatar
normandy committed
477
478
    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
479
         {:ok, activity} <- ActivityPub.unfollow(follower, followed, id, false) do
normandy's avatar
normandy committed
480
481
482
483
484
485
486
      User.unfollow(follower, followed)
      {:ok, activity}
    else
      e -> :error
    end
  end

487
488
489
  @ap_config Application.get_env(:pleroma, :activitypub)
  @accept_blocks Keyword.get(@ap_config, :accept_blocks)

normandy's avatar
normandy committed
490
491
492
493
494
495
496
497
  def handle_incoming(
        %{
          "type" => "Undo",
          "object" => %{"type" => "Block", "object" => blocked},
          "actor" => blocker,
          "id" => id
        } = _data
      ) do
498
499
    with true <- @accept_blocks,
         %User{local: true} = blocked <- User.get_cached_by_ap_id(blocked),
normandy's avatar
normandy committed
500
501
         %User{} = blocker <- User.get_or_fetch_by_ap_id(blocker),
         {:ok, activity} <- ActivityPub.unblock(blocker, blocked, id, false) do
normandy's avatar
normandy committed
502
      User.unblock(blocker, blocked)
normandy's avatar
normandy committed
503
504
505
506
507
508
      {:ok, activity}
    else
      e -> :error
    end
  end

509
510
511
  def handle_incoming(
        %{"type" => "Block", "object" => blocked, "actor" => blocker, "id" => id} = data
      ) do
512
513
    with true <- @accept_blocks,
         %User{local: true} = blocked = User.get_cached_by_ap_id(blocked),
normandy's avatar
normandy committed
514
         %User{} = blocker = User.get_or_fetch_by_ap_id(blocker),
normandy's avatar
normandy committed
515
         {:ok, activity} <- ActivityPub.block(blocker, blocked, id, false) do
516
      User.unfollow(blocker, blocked)
517
      User.block(blocker, blocked)
normandy's avatar
normandy committed
518
519
520
521
522
      {:ok, activity}
    else
      e -> :error
    end
  end
523

Thog's avatar
Thog committed
524
525
526
527
528
529
  def handle_incoming(
        %{
          "type" => "Undo",
          "object" => %{"type" => "Like", "object" => object_id},
          "actor" => actor,
          "id" => id
530
        } = data
Thog's avatar
Thog committed
531
      ) do
532
533
534
    with actor <- get_actor(data),
         %User{} = actor <- User.get_or_fetch_by_ap_id(actor),
         {:ok, object} <- get_obj_helper(object_id) || fetch_obj_helper(object_id),
Thog's avatar
Thog committed
535
536
537
         {:ok, activity, _, _} <- ActivityPub.unlike(actor, object, id, false) do
      {:ok, activity}
    else
Thog's avatar
Thog committed
538
      _e -> :error
Thog's avatar
Thog committed
539
540
541
    end
  end

542
543
  def handle_incoming(_), do: :error

544
545
546
  def fetch_obj_helper(id) when is_bitstring(id), do: ActivityPub.fetch_object_from_id(id)
  def fetch_obj_helper(obj) when is_map(obj), do: ActivityPub.fetch_object_from_id(obj["id"])

547
  def get_obj_helper(id) do
548
    if object = Object.normalize(id), do: {:ok, object}, else: nil
549
550
  end

551
552
553
554
555
556
557
558
  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
559

560
561
562
  def set_reply_to_uri(obj), do: obj

  # Prepares the object of an outgoing create activity.
lain's avatar
lain committed
563
564
  def prepare_object(object) do
    object
lain's avatar
lain committed
565
    |> set_sensitive
lain's avatar
lain committed
566
    |> add_hashtags
lain's avatar
lain committed
567
    |> add_mention_tags
lain's avatar
lain committed
568
    |> add_emoji_tags
lain's avatar
lain committed
569
    |> add_attributed_to
lain's avatar
lain committed
570
    |> prepare_attachments
lain's avatar
lain committed
571
    |> set_conversation
572
    |> set_reply_to_uri
lain's avatar
lain committed
573
574
  end

feld's avatar
feld committed
575
576
577
578
  #  @doc
  #  """
  #  internal -> Mastodon
  #  """
lain's avatar
lain committed
579

lain's avatar
lain committed
580
  def prepare_outgoing(%{"type" => "Create", "object" => %{"type" => "Note"} = object} = data) do
lain's avatar
lain committed
581
582
583
584
585
586
587
588
    object =
      object
      |> prepare_object

    data =
      data
      |> Map.put("object", object)
      |> Map.put("@context", "https://www.w3.org/ns/activitystreams")
lain's avatar
lain committed
589
590
591
592

    {:ok, data}
  end

kaniini's avatar
kaniini committed
593
594
595
  # Mastodon Accept/Reject requires a non-normalized object containing the actor URIs,
  # because of course it does.
  def prepare_outgoing(%{"type" => "Accept"} = data) do
596
    with follow_activity <- Activity.normalize(data["object"]) do
kaniini's avatar
kaniini committed
597
598
599
600
601
602
603
604
605
606
      object = %{
        "actor" => follow_activity.actor,
        "object" => follow_activity.data["object"],
        "id" => follow_activity.data["id"],
        "type" => "Follow"
      }

      data =
        data
        |> Map.put("object", object)
607
        |> Map.put("@context", "https://www.w3.org/ns/activitystreams")
kaniini's avatar
kaniini committed
608
609
610
611
612

      {:ok, data}
    end
  end

613
  def prepare_outgoing(%{"type" => "Reject"} = data) do
614
    with follow_activity <- Activity.normalize(data["object"]) do
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
      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
631
  def prepare_outgoing(%{"type" => _type} = data) do
lain's avatar
lain committed
632
633
634
635
    data =
      data
      |> maybe_fix_object_url
      |> Map.put("@context", "https://www.w3.org/ns/activitystreams")
636
637
638
639

    {:ok, data}
  end

640
641
  def maybe_fix_object_url(data) do
    if is_binary(data["object"]) and not String.starts_with?(data["object"], "http") do
642
      case fetch_obj_helper(data["object"]) do
643
644
        {:ok, relative_object} ->
          if relative_object.data["external_url"] do
feld's avatar
feld committed
645
            _data =
lain's avatar
lain committed
646
647
              data
              |> Map.put("object", relative_object.data["external_url"])
648
649
650
          else
            data
          end
lain's avatar
lain committed
651

652
653
654
655
656
657
658
659
660
        e ->
          Logger.error("Couldn't fetch #{data["object"]} #{inspect(e)}")
          data
      end
    else
      data
    end
  end

lain's avatar
lain committed
661
  def add_hashtags(object) do
lain's avatar
lain committed
662
663
664
665
666
667
668
669
670
    tags =
      (object["tag"] || [])
      |> Enum.map(fn tag ->
        %{
          "href" => Pleroma.Web.Endpoint.url() <> "/tags/#{tag}",
          "name" => "##{tag}",
          "type" => "Hashtag"
        }
      end)
lain's avatar
lain committed
671
672
673
674
675

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

lain's avatar
lain committed
676
  def add_mention_tags(object) do
lain's avatar
lain committed
677
    recipients = object["to"] ++ (object["cc"] || [])
lain's avatar
lain committed
678
679
680
681
682
683
684
685

    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
686

lain's avatar
lain committed
687
    tags = object["tag"] || []
lain's avatar
lain committed
688
689

    object
lain's avatar
lain committed
690
    |> Map.put("tag", tags ++ mentions)
lain's avatar
lain committed
691
692
  end

lain's avatar
lain committed
693
694
695
696
  # 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
697
698
699
700
701
702
703
704
705
706
707
708

    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
709
710
711
712
713

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

lain's avatar
lain committed
714
715
716
717
  def set_conversation(object) do
    Map.put(object, "conversation", object["context"])
  end

lain's avatar
lain committed
718
719
720
721
722
  def set_sensitive(object) do
    tags = object["tag"] || []
    Map.put(object, "sensitive", "nsfw" in tags)
  end

lain's avatar
lain committed
723
724
725
726
727
  def add_attributed_to(object) do
    attributedTo = object["attributedTo"] || object["actor"]

    object
    |> Map.put("attributedTo", attributedTo)
728
  end
lain's avatar
lain committed
729
730

  def prepare_attachments(object) do
lain's avatar
lain committed
731
732
733
734
735
736
    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
737
738
739
740

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

lain's avatar
lain committed
742
743
  defp user_upgrade_task(user) do
    old_follower_address = User.ap_followers(user)
lain's avatar
lain committed
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761

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

764
765
    maybe_retire_websub(user.ap_id)

lain's avatar
lain committed
766
    # Only do this for recent activties, don't go through the whole db.
lain's avatar
lain committed
767
768
    # Only look at the last 1000 activities.
    since = (Repo.aggregate(Activity, :max, :id) || 0) - 1_000
lain's avatar
lain committed
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787

    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
788
789
790
791
    Repo.update_all(q, [])
  end

  def upgrade_user_from_ap_id(ap_id, async \\ true) do
792
    with %User{local: false} = user <- User.get_by_ap_id(ap_id),
lain's avatar
lain committed
793
         {:ok, data} <- ActivityPub.fetch_and_prepare_user_from_ap_id(ap_id) do
lain's avatar
lain committed
794
795
796
      data =
        data
        |> Map.put(:info, Map.merge(user.info, data[:info]))
lain's avatar
lain committed
797

lain's avatar
lain committed
798
      already_ap = User.ap_enabled?(user)
lain's avatar
lain committed
799
800
801
802

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

lain's avatar
lain committed
804
805
806
807
808
809
810
      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
811
          user_upgrade_task(user)
lain's avatar
lain committed
812
        end
lain's avatar
lain committed
813
      end
lain's avatar
lain committed
814
815
816
817
818
819

      {:ok, user}
    else
      e -> e
    end
  end
820
821
822

  def maybe_retire_websub(ap_id) do
    # some sanity checks
lain's avatar
lain committed
823
824
825
826
827
828
829
    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}%")
        )

830
831
832
      Repo.delete_all(q)
    end
  end
833
834
835

  def maybe_fix_user_url(data) do
    if is_map(data["url"]) do
Thog's avatar
Thog committed
836
837
838
      Map.put(data, "url", data["url"]["href"])
    else
      data
839
840
841
842
843
844
845
    end
  end

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