transmogrifier.ex 28.5 KB
Newer Older
1
# Pleroma: A lightweight social networking server
kaniini's avatar
kaniini committed
2
# Copyright © 2017-2019 Pleroma Authors <https://pleroma.social/>
3
4
# SPDX-License-Identifier: AGPL-3.0-only

5
6
7
8
defmodule Pleroma.Web.ActivityPub.Transmogrifier do
  @moduledoc """
  A module to handle coding from internal to wire ActivityPub and back.
  """
9
  alias Pleroma.Activity
Haelwenn's avatar
Haelwenn committed
10
  alias Pleroma.Object
rinpatch's avatar
rinpatch committed
11
  alias Pleroma.Object.Containment
lain's avatar
lain committed
12
  alias Pleroma.Repo
13
  alias Pleroma.User
rinpatch's avatar
rinpatch committed
14
  alias Pleroma.User
15
  alias Pleroma.Web.ActivityPub.ActivityPub
16
  alias Pleroma.Web.ActivityPub.Utils
lain's avatar
lain committed
17
  alias Pleroma.Web.ActivityPub.Visibility
18

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

21
22
  require Logger

23
24
25
26
27
  @doc """
  Modifies an incoming AP object (mastodon format) to our internal format.
  """
  def fix_object(object) do
    object
28
    |> fix_actor
29
    |> fix_url
30
    |> fix_attachments
lain's avatar
lain committed
31
    |> fix_context
lain's avatar
lain committed
32
    |> fix_in_reply_to
lain's avatar
lain committed
33
    |> fix_emoji
34
    |> fix_tag
35
    |> fix_content_map
36
    |> fix_likes
37
    |> fix_addressing
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
    |> fix_summary
  end

  def fix_summary(%{"summary" => nil} = object) do
    object
    |> Map.put("summary", "")
  end

  def fix_summary(%{"summary" => _} = object) do
    # summary is present, nothing to do
    object
  end

  def fix_summary(object) do
    object
    |> Map.put("summary", "")
54
55
56
  end

  def fix_addressing_list(map, field) do
57
58
59
60
61
62
63
64
65
    cond do
      is_binary(map[field]) ->
        Map.put(map, field, [map[field]])

      is_nil(map[field]) ->
        Map.put(map, field, [])

      true ->
        map
66
67
68
    end
  end

69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
  def fix_explicit_addressing(%{"to" => to, "cc" => cc} = object, explicit_mentions) do
    explicit_to =
      to
      |> Enum.filter(fn x -> x in explicit_mentions end)

    explicit_cc =
      to
      |> Enum.filter(fn x -> x not in explicit_mentions end)

    final_cc =
      (cc ++ explicit_cc)
      |> Enum.uniq()

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

  def fix_explicit_addressing(object, _explicit_mentions), do: object

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

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

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

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

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

    if followers_collection not in recipients do
      cond do
        "https://www.w3.org/ns/activitystreams#Public" in cc ->
          to = to ++ [followers_collection]
          Map.put(object, "to", to)

        "https://www.w3.org/ns/activitystreams#Public" in to ->
          cc = cc ++ [followers_collection]
          Map.put(object, "cc", cc)

        true ->
          object
      end
121
    else
122
      object
123
124
125
    end
  end

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

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

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

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

146
147
148
149
150
  # Check for standardisation
  # This is what Peertube does
  # curl -H 'Accept: application/activity+json' $likes | jq .totalItems
  # Prismo returns only an integer (count) as "likes"
  def fix_likes(%{"likes" => likes} = object) when not is_map(likes) do
151
152
153
154
155
156
157
158
159
    object
    |> Map.put("likes", [])
    |> Map.put("like_count", 0)
  end

  def fix_likes(object) do
    object
  end

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

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

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

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

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

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

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

209
  def fix_attachments(%{"attachment" => attachment} = object) when is_list(attachment) do
lain's avatar
lain committed
210
    attachments =
211
      attachment
lain's avatar
lain committed
212
      |> Enum.map(fn data ->
213
214
215
216
217
218
219
220
        media_type = data["mediaType"] || data["mimeType"]
        href = data["url"] || data["href"]

        url = [%{"type" => "Link", "mediaType" => media_type, "href" => href}]

        data
        |> Map.put("mediaType", media_type)
        |> Map.put("url", url)
lain's avatar
lain committed
221
      end)
lain's avatar
lain committed
222
223
224

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

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

232
  def fix_attachments(object), do: object
233

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

239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
  def fix_url(%{"type" => "Video", "url" => url} = object) when is_list(url) do
    first_element = Enum.at(url, 0)

    link_element =
      url
      |> Enum.filter(fn x -> is_map(x) end)
      |> Enum.filter(fn x -> x["mimeType"] == "text/html" end)
      |> Enum.at(0)

    object
    |> Map.put("attachment", [first_element])
    |> Map.put("url", link_element["href"])
  end

  def fix_url(%{"type" => object_type, "url" => url} = object)
      when object_type != "Video" and is_list(url) do
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
    first_element = Enum.at(url, 0)

    url_string =
      cond do
        is_bitstring(first_element) -> first_element
        is_map(first_element) -> first_element["href"] || ""
        true -> ""
      end

    object
    |> Map.put("url", url_string)
  end

  def fix_url(object), do: object

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

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

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

    # 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

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

296
  def fix_emoji(object), do: object
297

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

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

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

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

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

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

319
  def fix_tag(object), do: object
320

321
322
323
324
325
326
327
328
329
330
331
  # content map usually only has one language so this will do for now.
  def fix_content_map(%{"contentMap" => content_map} = object) do
    content_groups = Map.to_list(content_map)
    {_, content} = Enum.at(content_groups, 0)

    object
    |> Map.put("content", content)
  end

  def fix_content_map(object), do: object

Maksim's avatar
Maksim committed
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
  defp mastodon_follow_hack(%{"id" => id, "actor" => follower_id}, followed) do
    with true <- id =~ "follows",
         %User{local: true} = follower <- User.get_cached_by_ap_id(follower_id),
         %Activity{} = activity <- Utils.fetch_latest_follow(follower, followed) do
      {:ok, activity}
    else
      _ -> {:error, nil}
    end
  end

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

  defp get_follow_activity(follow_object, followed) do
    with object_id when not is_nil(object_id) <- Utils.get_ap_id(follow_object),
         {_, %Activity{} = activity} <- {:activity, Activity.get_by_ap_id(object_id)} do
      {:ok, activity}
    else
      # Can't find the activity. This might a Mastodon 2.3 "Accept"
      {:activity, nil} ->
        mastodon_follow_hack(follow_object, followed)

      _ ->
        {:error, nil}
    end
  end

358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
  # Flag objects are placed ahead of the ID check because Mastodon 2.8 and earlier send them
  # with nil ID.
  def handle_incoming(%{"type" => "Flag", "object" => objects, "actor" => actor} = data) do
    with context <- data["context"] || Utils.generate_context_id(),
         content <- data["content"] || "",
         %User{} = actor <- User.get_cached_by_ap_id(actor),

         # Reduce the object list to find the reported user.
         %User{} = account <-
           Enum.reduce_while(objects, nil, fn ap_id, _ ->
             with %User{} = user <- User.get_cached_by_ap_id(ap_id) do
               {:halt, user}
             else
               _ -> {:cont, nil}
             end
           end),

         # Remove the reported user from the object list.
         statuses <- Enum.filter(objects, fn ap_id -> ap_id != account.ap_id end) do
      params = %{
        actor: actor,
        context: context,
        account: account,
        statuses: statuses,
        content: content,
        additional: %{
          "cc" => [account.ap_id]
        }
      }

      ActivityPub.flag(params)
    end
  end

392
393
394
395
396
397
  # 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

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

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

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

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

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

lain's avatar
lain committed
435
436
437
  def handle_incoming(
        %{"type" => "Follow", "object" => followed, "actor" => follower, "id" => id} = data
      ) do
438
    with %User{local: true} = followed <- User.get_cached_by_ap_id(followed),
439
440
         %User{} = follower <- User.get_or_fetch_by_ap_id(follower),
         {:ok, activity} <- ActivityPub.follow(follower, followed, id, false) do
441
442
443
444
445
      with deny_follow_blocked <- Pleroma.Config.get([:user, :deny_follow_blocked]),
           {:user_blocked, false} <-
             {:user_blocked, User.blocks?(followed, follower) && deny_follow_blocked},
           {:user_locked, false} <- {:user_locked, User.locked?(followed)},
           {:follow, {:ok, follower}} <- {:follow, User.follow(follower, followed)} do
kaniini's avatar
kaniini committed
446
447
        ActivityPub.accept(%{
          to: [follower.ap_id],
448
          actor: followed,
kaniini's avatar
kaniini committed
449
450
451
          object: data,
          local: true
        })
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
      else
        {:user_blocked, true} ->
          {:ok, _} = Utils.update_follow_state(activity, "reject")

          ActivityPub.reject(%{
            to: [follower.ap_id],
            actor: followed,
            object: data,
            local: true
          })

        {:follow, {:error, _}} ->
          {:ok, _} = Utils.update_follow_state(activity, "reject")

          ActivityPub.reject(%{
            to: [follower.ap_id],
            actor: followed,
            object: data,
            local: true
          })

        {:user_locked, true} ->
          :noop
475
      end
lain's avatar
lain committed
476

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

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

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

  def handle_incoming(
Maksim's avatar
Maksim committed
511
        %{"type" => "Reject", "object" => follow_object, "actor" => _actor, "id" => _id} = data
512
      ) do
513
    with actor <- Containment.get_actor(data),
514
         %User{} = followed <- User.get_or_fetch_by_ap_id(actor),
515
         {:ok, follow_activity} <- get_follow_activity(follow_object, followed),
516
         {:ok, follow_activity} <- Utils.update_follow_state(follow_activity, "reject"),
517
         %User{local: true} = follower <- User.get_cached_by_ap_id(follow_activity.data["actor"]),
lain's avatar
lain committed
518
         {:ok, activity} <-
519
           ActivityPub.reject(%{
lain's avatar
lain committed
520
             to: follow_activity.data["to"],
521
             type: "Reject",
522
             actor: followed,
lain's avatar
lain committed
523
524
525
             object: follow_activity.data["id"],
             local: false
           }) do
526
527
      User.unfollow(follower, followed)

528
      {:ok, activity}
529
530
    else
      _e -> :error
531
532
533
    end
  end

lain's avatar
lain committed
534
  def handle_incoming(
Maksim's avatar
Maksim committed
535
        %{"type" => "Like", "object" => object_id, "actor" => _actor, "id" => id} = data
lain's avatar
lain committed
536
      ) do
537
    with actor <- Containment.get_actor(data),
538
         %User{} = actor <- User.get_or_fetch_by_ap_id(actor),
539
         {:ok, object} <- get_obj_helper(object_id),
feld's avatar
feld committed
540
         {:ok, activity, _object} <- ActivityPub.like(actor, object, id, false) do
lain's avatar
lain committed
541
542
543
544
545
546
      {:ok, activity}
    else
      _e -> :error
    end
  end

lain's avatar
lain committed
547
  def handle_incoming(
Maksim's avatar
Maksim committed
548
        %{"type" => "Announce", "object" => object_id, "actor" => _actor, "id" => id} = data
lain's avatar
lain committed
549
      ) do
550
    with actor <- Containment.get_actor(data),
551
         %User{} = actor <- User.get_or_fetch_by_ap_id(actor),
552
         {:ok, object} <- get_obj_helper(object_id),
lain's avatar
lain committed
553
         public <- Visibility.is_public?(data),
554
         {:ok, activity, _object} <- ActivityPub.announce(actor, object, id, false, public) do
lain's avatar
lain committed
555
556
557
558
559
560
      {:ok, activity}
    else
      _e -> :error
    end
  end

lain's avatar
lain committed
561
  def handle_incoming(
562
        %{"type" => "Update", "object" => %{"type" => object_type} = object, "actor" => actor_id} =
lain's avatar
lain committed
563
          data
564
565
      )
      when object_type in ["Person", "Application", "Service", "Organization"] do
minibikini's avatar
minibikini committed
566
    with %User{ap_id: ^actor_id} = actor <- User.get_cached_by_ap_id(object["id"]) do
lain's avatar
lain committed
567
568
569
      {:ok, new_user_data} = ActivityPub.user_data_from_user_object(object)

      banner = new_user_data[:info]["banner"]
570
      locked = new_user_data[:info]["locked"] || false
lain's avatar
lain committed
571
572
573
574

      update_data =
        new_user_data
        |> Map.take([:name, :bio, :avatar])
lain's avatar
lain committed
575
        |> Map.put(:info, %{"banner" => banner, "locked" => locked})
lain's avatar
lain committed
576
577
578

      actor
      |> User.upgrade_changeset(update_data)
lain's avatar
lain committed
579
      |> User.update_and_set_cache()
lain's avatar
lain committed
580

lain's avatar
lain committed
581
582
583
584
585
586
587
      ActivityPub.update(%{
        local: false,
        to: data["to"] || [],
        cc: data["cc"] || [],
        object: object,
        actor: actor_id
      })
lain's avatar
lain committed
588
589
590
591
592
593
594
    else
      e ->
        Logger.error(e)
        :error
    end
  end

595
596
597
598
599
  # TODO: We presently assume that any actor on the same origin domain as the object being
  # deleted has the rights to delete that object.  A better way to validate whether or not
  # the object should be deleted is to refetch the object URI, which should return either
  # an error or a tombstone.  This would allow us to verify that a deletion actually took
  # place.
lain's avatar
lain committed
600
  def handle_incoming(
601
        %{"type" => "Delete", "object" => object_id, "actor" => _actor, "id" => _id} = data
lain's avatar
lain committed
602
      ) do
lain's avatar
lain committed
603
    object_id = Utils.get_ap_id(object_id)
lain's avatar
lain committed
604

605
    with actor <- Containment.get_actor(data),
606
         %User{} = actor <- User.get_or_fetch_by_ap_id(actor),
607
         {:ok, object} <- get_obj_helper(object_id),
608
         :ok <- Containment.contain_origin(actor.ap_id, object.data),
lain's avatar
lain committed
609
610
611
         {:ok, activity} <- ActivityPub.delete(object, false) do
      {:ok, activity}
    else
feld's avatar
feld committed
612
      _e -> :error
lain's avatar
lain committed
613
614
615
    end
  end

616
  def handle_incoming(
617
618
        %{
          "type" => "Undo",
619
          "object" => %{"type" => "Announce", "object" => object_id},
Maksim's avatar
Maksim committed
620
          "actor" => _actor,
621
          "id" => id
622
        } = data
623
      ) do
624
    with actor <- Containment.get_actor(data),
625
         %User{} = actor <- User.get_or_fetch_by_ap_id(actor),
626
         {:ok, object} <- get_obj_helper(object_id),
627
         {:ok, activity, _} <- ActivityPub.unannounce(actor, object, id, false) do
628
629
      {:ok, activity}
    else
Thog's avatar
Thog committed
630
      _e -> :error
631
632
633
    end
  end

normandy's avatar
normandy committed
634
635
636
637
638
639
  def handle_incoming(
        %{
          "type" => "Undo",
          "object" => %{"type" => "Follow", "object" => followed},
          "actor" => follower,
          "id" => id
normandy's avatar
normandy committed
640
        } = _data
normandy's avatar
normandy committed
641
      ) do
normandy's avatar
normandy committed
642
643
    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
644
         {:ok, activity} <- ActivityPub.unfollow(follower, followed, id, false) do
normandy's avatar
normandy committed
645
646
647
      User.unfollow(follower, followed)
      {:ok, activity}
    else
Maksim's avatar
Maksim committed
648
      _e -> :error
normandy's avatar
normandy committed
649
650
651
    end
  end

normandy's avatar
normandy committed
652
653
654
655
656
657
658
659
  def handle_incoming(
        %{
          "type" => "Undo",
          "object" => %{"type" => "Block", "object" => blocked},
          "actor" => blocker,
          "id" => id
        } = _data
      ) do
href's avatar
href committed
660
    with true <- Pleroma.Config.get([:activitypub, :accept_blocks]),
661
         %User{local: true} = blocked <- User.get_cached_by_ap_id(blocked),
normandy's avatar
normandy committed
662
663
         %User{} = blocker <- User.get_or_fetch_by_ap_id(blocker),
         {:ok, activity} <- ActivityPub.unblock(blocker, blocked, id, false) do
normandy's avatar
normandy committed
664
      User.unblock(blocker, blocked)
normandy's avatar
normandy committed
665
666
      {:ok, activity}
    else
Maksim's avatar
Maksim committed
667
      _e -> :error
normandy's avatar
normandy committed
668
669
670
    end
  end

671
  def handle_incoming(
Maksim's avatar
Maksim committed
672
        %{"type" => "Block", "object" => blocked, "actor" => blocker, "id" => id} = _data
673
      ) do
href's avatar
href committed
674
    with true <- Pleroma.Config.get([:activitypub, :accept_blocks]),
675
         %User{local: true} = blocked = User.get_cached_by_ap_id(blocked),
normandy's avatar
normandy committed
676
         %User{} = blocker = User.get_or_fetch_by_ap_id(blocker),
normandy's avatar
normandy committed
677
         {:ok, activity} <- ActivityPub.block(blocker, blocked, id, false) do
678
      User.unfollow(blocker, blocked)
679
      User.block(blocker, blocked)
normandy's avatar
normandy committed
680
681
      {:ok, activity}
    else
Maksim's avatar
Maksim committed
682
      _e -> :error
normandy's avatar
normandy committed
683
684
    end
  end
685

Thog's avatar
Thog committed
686
687
688
689
  def handle_incoming(
        %{
          "type" => "Undo",
          "object" => %{"type" => "Like", "object" => object_id},
Maksim's avatar
Maksim committed
690
          "actor" => _actor,
Thog's avatar
Thog committed
691
          "id" => id
692
        } = data
Thog's avatar
Thog committed
693
      ) do
694
    with actor <- Containment.get_actor(data),
695
         %User{} = actor <- User.get_or_fetch_by_ap_id(actor),
696
         {:ok, object} <- get_obj_helper(object_id),
Thog's avatar
Thog committed
697
698
699
         {:ok, activity, _, _} <- ActivityPub.unlike(actor, object, id, false) do
      {:ok, activity}
    else
Thog's avatar
Thog committed
700
      _e -> :error
Thog's avatar
Thog committed
701
702
703
    end
  end

704
705
  def handle_incoming(_), do: :error

706
  def get_obj_helper(id) do
707
    if object = Object.normalize(id), do: {:ok, object}, else: nil
708
709
  end

710
711
712
713
  def set_reply_to_uri(%{"inReplyTo" => in_reply_to} = object) when is_binary(in_reply_to) do
    with false <- String.starts_with?(in_reply_to, "http"),
         {:ok, %{data: replied_to_object}} <- get_obj_helper(in_reply_to) do
      Map.put(object, "inReplyTo", replied_to_object["external_url"] || in_reply_to)
714
715
716
717
    else
      _e -> object
    end
  end
lain's avatar
lain committed
718

719
720
721
  def set_reply_to_uri(obj), do: obj

  # Prepares the object of an outgoing create activity.
lain's avatar
lain committed
722
723
  def prepare_object(object) do
    object
lain's avatar
lain committed
724
    |> set_sensitive
lain's avatar
lain committed
725
    |> add_hashtags
lain's avatar
lain committed
726
    |> add_mention_tags
lain's avatar
lain committed
727
    |> add_emoji_tags
lain's avatar
lain committed
728
    |> add_attributed_to
729
    |> add_likes
lain's avatar
lain committed
730
    |> prepare_attachments
lain's avatar
lain committed
731
    |> set_conversation
732
    |> set_reply_to_uri
733
734
    |> strip_internal_fields
    |> strip_internal_tags
lain's avatar
lain committed
735
736
  end

feld's avatar
feld committed
737
738
739
740
  #  @doc
  #  """
  #  internal -> Mastodon
  #  """
lain's avatar
lain committed
741

742
  def prepare_outgoing(%{"type" => "Create", "object" => object_id} = data) do
lain's avatar
lain committed
743
    object =
744
      Object.normalize(object_id).data
lain's avatar
lain committed
745
746
747
748
749
      |> prepare_object

    data =
      data
      |> Map.put("object", object)
lain's avatar
lain committed
750
      |> Map.merge(Utils.make_json_ld_header())
lain's avatar
lain committed
751
752
753
754

    {:ok, data}
  end

kaniini's avatar
kaniini committed
755
756
757
  # Mastodon Accept/Reject requires a non-normalized object containing the actor URIs,
  # because of course it does.
  def prepare_outgoing(%{"type" => "Accept"} = data) do
758
    with follow_activity <- Activity.normalize(data["object"]) do
kaniini's avatar
kaniini committed
759
760
761
762
763
764
765
766
767
768
      object = %{
        "actor" => follow_activity.actor,
        "object" => follow_activity.data["object"],
        "id" => follow_activity.data["id"],
        "type" => "Follow"
      }

      data =
        data
        |> Map.put("object", object)
lain's avatar
lain committed
769
        |> Map.merge(Utils.make_json_ld_header())
kaniini's avatar
kaniini committed
770
771
772
773
774

      {:ok, data}
    end
  end

775
  def prepare_outgoing(%{"type" => "Reject"} = data) do
776
    with follow_activity <- Activity.normalize(data["object"]) do
777
778
779
780
781
782
783
784
785
786
      object = %{
        "actor" => follow_activity.actor,
        "object" => follow_activity.data["object"],
        "id" => follow_activity.data["id"],
        "type" => "Follow"
      }

      data =
        data
        |> Map.put("object", object)
lain's avatar
lain committed
787
        |> Map.merge(Utils.make_json_ld_header())
788
789
790
791
792

      {:ok, data}
    end
  end

feld's avatar
feld committed
793
  def prepare_outgoing(%{"type" => _type} = data) do
lain's avatar
lain committed
794
795
    data =
      data
796
      |> strip_internal_fields
lain's avatar
lain committed
797
      |> maybe_fix_object_url
lain's avatar
lain committed
798
      |> Map.merge(Utils.make_json_ld_header())
799
800
801
802

    {:ok, data}
  end

803
804
  def maybe_fix_object_url(data) do
    if is_binary(data["object"]) and not String.starts_with?(data["object"], "http") do
805
      case get_obj_helper(data["object"]) do
806
807
        {:ok, relative_object} ->
          if relative_object.data["external_url"] do
feld's avatar
feld committed
808
            _data =
lain's avatar
lain committed
809
810
              data
              |> Map.put("object", relative_object.data["external_url"])
811
812
813
          else
            data
          end
lain's avatar
lain committed
814

815
816
817
818
819
820
821
822
823
        e ->
          Logger.error("Couldn't fetch #{data["object"]} #{inspect(e)}")
          data
      end
    else
      data
    end
  end

lain's avatar
lain committed
824
  def add_hashtags(object) do
lain's avatar
lain committed
825
826
    tags =
      (object["tag"] || [])
827
828
829
830
831
832
833
834
835
836
837
838
      |> Enum.map(fn
        # Expand internal representation tags into AS2 tags.
        tag when is_binary(tag) ->
          %{
            "href" => Pleroma.Web.Endpoint.url() <> "/tags/#{tag}",
            "name" => "##{tag}",
            "type" => "Hashtag"
          }

        # Do not process tags which are already AS2 tag objects.
        tag when is_map(tag) ->
          tag
lain's avatar
lain committed
839
      end)
lain's avatar
lain committed
840
841
842
843
844

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

lain's avatar
lain committed
845
  def add_mention_tags(object) do
lain's avatar
lain committed
846
    mentions =
847
848
      object
      |> Utils.get_notified_from_object()
lain's avatar
lain committed
849
850
851
      |> Enum.map(fn user ->
        %{"type" => "Mention", "href" => user.ap_id, "name" => "@#{user.nickname}"}
      end)
lain's avatar
lain committed
852

lain's avatar
lain committed
853
    tags = object["tag"] || []
lain's avatar
lain committed
854
855

    object
lain's avatar
lain committed
856
    |> Map.put("tag", tags ++ mentions)
lain's avatar
lain committed
857
858
  end

lain's avatar
lain committed
859
860
861
862
  # 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
863
864
865
866
867
868
869
870
871
872
873
874

    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
875
876
877
878
879

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

lain's avatar
lain committed
880
881
882
883
  def set_conversation(object) do
    Map.put(object, "conversation", object["context"])
  end

lain's avatar
lain committed
884
885
886
887
888
  def set_sensitive(object) do
    tags = object["tag"] || []
    Map.put(object, "sensitive", "nsfw" in tags)
  end

lain's avatar
lain committed
889
  def add_attributed_to(object) do
890
    attributed_to = object["attributedTo"] || object["actor"]
lain's avatar
lain committed
891
892

    object
893
    |> Map.put("attributedTo", attributed_to)
894
  end
lain's avatar
lain committed
895

896
897
898
899
900
901
902
903
904
905
906
  def add_likes(%{"id" => id, "like_count" => likes} = object) do
    likes = %{
      "id" => "#{id}/likes",
      "first" => "#{id}/likes?page=1",
      "type" => "OrderedCollection",
      "totalItems" => likes
    }

    object
    |> Map.put("likes", likes)
  end
lain's avatar
lain committed
907

908
  def add_likes(object) do
lain's avatar
lain committed
909
    object
910
  end
lain's avatar
lain committed
911
912

  def prepare_attachments(object) do
lain's avatar
lain committed
913
914
915
916
917
918
    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
919
920
921
922

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

924
925
926
927
928
929
930
  defp strip_internal_fields(object) do
    object
    |> Map.drop([
      "like_count",
      "announcements",
      "announcement_count",
      "emoji",
931
932
      "context_id",
      "deleted_activity_id"
933
934
935
936
937
938
939
940
941
942
943
944
945
946
    ])
  end

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

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

  defp strip_internal_tags(object), do: object

947
  def perform(:user_upgrade, user) do
948
949
    # we pass a fake user so that the followers collection is stripped away
    old_follower_address = User.ap_followers(%User{nickname: user.nickname})
lain's avatar
lain committed
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967

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

970
971
    maybe_retire_websub(user.ap_id)

lain's avatar
lain committed
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
    q =
      from(
        a in Activity,
        where: ^old_follower_address in a.recipients,
        update: [
          set: [
            recipients:
              fragment(
                "array_replace(?,?,?)",
                a.recipients,
                ^old_follower_address,
                ^user.follower_address
              )
          ]
        ]
      )

lain's avatar
lain committed
989
990
991
    Repo.update_all(q, [])
  end

992
  def upgrade_user_from_ap_id(ap_id) do
minibikini's avatar
minibikini committed
993
    with %User{local: false} = user <- User.get_cached_by_ap_id(ap_id),
994
995
996
997
998
         {:ok, data} <- ActivityPub.fetch_and_prepare_user_from_ap_id(ap_id),
         already_ap <- User.ap_enabled?(user),
         {:ok, user} <- user |> User.upgrade_changeset(data) |> User.update_and_set_cache() do
      unless already_ap do
        PleromaJobQueue.enqueue(:transmogrifier, __MODULE__, [:user_upgrade, user])
lain's avatar
lain committed
999
      end
lain's avatar
lain committed
1000

For faster browsing, not all history is shown. View entire blame