utils.ex 12.7 KB
Newer Older
lain's avatar
lain committed
1
2
3
4
5
6
defmodule Pleroma.Web.ActivityPub.Utils do
  alias Pleroma.{Repo, Web, Object, Activity, User}
  alias Pleroma.Web.Router.Helpers
  alias Pleroma.Web.Endpoint
  alias Ecto.{Changeset, UUID}
  import Ecto.Query
kaniini's avatar
kaniini committed
7
  require Logger
lain's avatar
lain committed
8

9
10
  # Some implementations send the actor URI as the actor field, others send the entire actor object,
  # so figure out what the actor's URI is based on what we have.
lain's avatar
lain committed
11
12
13
14
  def get_ap_id(object) do
    case object do
      %{"id" => id} -> id
      id -> id
15
16
17
18
    end
  end

  def normalize_params(params) do
lain's avatar
lain committed
19
    Map.put(params, "actor", get_ap_id(params["actor"]))
20
21
  end

22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
  def make_json_ld_header do
    %{
      "@context" => [
        "https://www.w3.org/ns/activitystreams",
        "https://w3id.org/security/v1",
        %{
          "manuallyApprovesFollowers" => "as:manuallyApprovesFollowers",
          "sensitive" => "as:sensitive",
          "Hashtag" => "as:Hashtag",
          "ostatus" => "http://ostatus.org#",
          "atomUri" => "ostatus:atomUri",
          "inReplyToAtomUri" => "ostatus:inReplyToAtomUri",
          "conversation" => "ostatus:conversation",
          "toot" => "http://joinmastodon.org/ns#",
          "Emoji" => "toot:Emoji"
        }
      ]
    }
  end

lain's avatar
lain committed
42
  def make_date do
lain's avatar
lain committed
43
    DateTime.utc_now() |> DateTime.to_iso8601()
lain's avatar
lain committed
44
45
46
47
48
49
50
51
52
53
54
  end

  def generate_activity_id do
    generate_id("activities")
  end

  def generate_context_id do
    generate_id("contexts")
  end

  def generate_object_id do
lain's avatar
lain committed
55
    Helpers.o_status_url(Endpoint, :object, UUID.generate())
lain's avatar
lain committed
56
57
58
  end

  def generate_id(type) do
lain's avatar
lain committed
59
    "#{Web.base_url()}/#{type}/#{UUID.generate()}"
lain's avatar
lain committed
60
61
  end

62
63
64
65
66
  def create_context(context) do
    context = context || generate_id("contexts")
    changeset = Object.context_mapping(context)

    case Repo.insert(changeset) do
lain's avatar
lain committed
67
68
69
      {:ok, object} ->
        object

70
71
      # This should be solved by an upsert, but it seems ecto
      # has problems accessing the constraint inside the jsonb.
lain's avatar
lain committed
72
73
      {:error, _} ->
        Object.get_cached_by_ap_id(context)
74
75
76
    end
  end

lain's avatar
lain committed
77
78
79
80
  @doc """
  Enqueues an activity for federation if it's local
  """
  def maybe_federate(%Activity{local: true} = activity) do
lain's avatar
lain committed
81
82
83
84
85
86
87
    priority =
      case activity.data["type"] do
        "Delete" -> 10
        "Create" -> 1
        _ -> 5
      end

lain's avatar
lain committed
88
    Pleroma.Web.Federator.enqueue(:publish, activity, priority)
lain's avatar
lain committed
89
90
    :ok
  end
lain's avatar
lain committed
91

lain's avatar
lain committed
92
93
94
95
96
97
98
  def maybe_federate(_), do: :ok

  @doc """
  Adds an id and a published data if they aren't there,
  also adds it to an included object
  """
  def lazy_put_activity_defaults(map) do
99
100
    %{data: %{"id" => context}, id: context_id} = create_context(map["context"])

lain's avatar
lain committed
101
102
103
104
    map =
      map
      |> Map.put_new_lazy("id", &generate_activity_id/0)
      |> Map.put_new_lazy("published", &make_date/0)
105
106
      |> Map.put_new("context", context)
      |> Map.put_new("context_id", context_id)
lain's avatar
lain committed
107
108

    if is_map(map["object"]) do
109
      object = lazy_put_object_defaults(map["object"], map)
lain's avatar
lain committed
110
111
112
113
114
115
116
117
118
      %{map | "object" => object}
    else
      map
    end
  end

  @doc """
  Adds an id and published date if they aren't there.
  """
119
  def lazy_put_object_defaults(map, activity \\ %{}) do
lain's avatar
lain committed
120
121
122
    map
    |> Map.put_new_lazy("id", &generate_object_id/0)
    |> Map.put_new_lazy("published", &make_date/0)
123
124
    |> Map.put_new("context", activity["context"])
    |> Map.put_new("context_id", activity["context_id"])
lain's avatar
lain committed
125
126
127
128
129
  end

  @doc """
  Inserts a full object if it is contained in an activity.
  """
lain's avatar
lain committed
130
  def insert_full_object(%{"object" => %{"type" => type} = object_data})
131
      when is_map(object_data) and type in ["Article", "Note"] do
Thog's avatar
Thog committed
132
    with {:ok, _} <- Object.create(object_data) do
lain's avatar
lain committed
133
134
135
      :ok
    end
  end
lain's avatar
lain committed
136

lain's avatar
lain committed
137
138
139
140
141
142
143
144
  def insert_full_object(_), do: :ok

  def update_object_in_activities(%{data: %{"id" => id}} = object) do
    # TODO
    # Update activities that already had this. Could be done in a seperate process.
    # Alternatively, just don't do this and fetch the current object each time. Most
    # could probably be taken from cache.
    relevant_activities = Activity.all_by_object_ap_id(id)
lain's avatar
lain committed
145
146

    Enum.map(relevant_activities, fn activity ->
lain's avatar
lain committed
147
148
149
150
151
152
153
154
155
156
157
      new_activity_data = activity.data |> Map.put("object", object.data)
      changeset = Changeset.change(activity, data: new_activity_data)
      Repo.update(changeset)
    end)
  end

  #### Like-related helpers

  @doc """
  Returns an existing like if a user already liked an object
  """
Thog's avatar
Thog committed
158
  def get_existing_like(actor, %{data: %{"id" => id}}) do
lain's avatar
lain committed
159
160
161
162
163
164
165
166
167
168
169
170
171
172
    query =
      from(
        activity in Activity,
        where: fragment("(?)->>'actor' = ?", activity.data, ^actor),
        # this is to use the index
        where:
          fragment(
            "coalesce((?)->'object'->>'id', (?)->>'object') = ?",
            activity.data,
            activity.data,
            ^id
          ),
        where: fragment("(?)->>'type' = 'Like'", activity.data)
      )
173

lain's avatar
lain committed
174
175
176
177
178
179
180
181
    Repo.one(query)
  end

  def make_like_data(%User{ap_id: ap_id} = actor, %{data: %{"id" => id}} = object, activity_id) do
    data = %{
      "type" => "Like",
      "actor" => ap_id,
      "object" => id,
lain's avatar
lain committed
182
      "to" => [actor.follower_address, object.data["actor"]],
lain's avatar
lain committed
183
      "cc" => ["https://www.w3.org/ns/activitystreams#Public"],
lain's avatar
lain committed
184
185
186
187
188
189
190
      "context" => object.data["context"]
    }

    if activity_id, do: Map.put(data, "id", activity_id), else: data
  end

  def update_element_in_object(property, element, object) do
lain's avatar
lain committed
191
    with new_data <-
lain's avatar
lain committed
192
193
           object.data
           |> Map.put("#{property}_count", length(element))
lain's avatar
lain committed
194
           |> Map.put("#{property}s", element),
lain's avatar
lain committed
195
196
         changeset <- Changeset.change(object, data: new_data),
         {:ok, object} <- Repo.update(changeset),
lain's avatar
lain committed
197
         _ <- update_object_in_activities(object) do
lain's avatar
lain committed
198
199
200
201
202
203
204
205
206
      {:ok, object}
    end
  end

  def update_likes_in_object(likes, object) do
    update_element_in_object("like", likes, object)
  end

  def add_like_to_object(%Activity{data: %{"actor" => actor}}, object) do
lain's avatar
lain committed
207
    with likes <- [actor | object.data["likes"] || []] |> Enum.uniq() do
lain's avatar
lain committed
208
209
210
211
212
213
214
215
216
217
218
219
      update_likes_in_object(likes, object)
    end
  end

  def remove_like_from_object(%Activity{data: %{"actor" => actor}}, object) do
    with likes <- (object.data["likes"] || []) |> List.delete(actor) do
      update_likes_in_object(likes, object)
    end
  end

  #### Follow-related helpers

kaniini's avatar
kaniini committed
220
221
222
223
224
225
226
227
228
229
230
231
232
  @doc """
  Updates a follow activity's state (for locked accounts).
  """
  def update_follow_state(%Activity{} = activity, state) do
    with new_data <-
           activity.data
           |> Map.put("state", state),
         changeset <- Changeset.change(activity, data: new_data),
         {:ok, activity} <- Repo.update(changeset) do
      {:ok, activity}
    end
  end

lain's avatar
lain committed
233
234
235
  @doc """
  Makes a follow activity data for the given follower and followed
  """
kaniini's avatar
kaniini committed
236
237
238
239
240
  def make_follow_data(
        %User{ap_id: follower_id},
        %User{ap_id: followed_id} = followed,
        activity_id
      ) do
lain's avatar
lain committed
241
242
243
244
    data = %{
      "type" => "Follow",
      "actor" => follower_id,
      "to" => [followed_id],
lain's avatar
lain committed
245
      "cc" => ["https://www.w3.org/ns/activitystreams#Public"],
lain's avatar
lain committed
246
247
248
      "object" => followed_id
    }

kaniini's avatar
kaniini committed
249
250
251
252
    data = if activity_id, do: Map.put(data, "id", activity_id), else: data
    data = if User.locked?(followed), do: Map.put(data, "state", "pending"), else: data

    data
lain's avatar
lain committed
253
254
  end

lain's avatar
lain committed
255
256
257
258
  def fetch_latest_follow(%User{ap_id: follower_id}, %User{ap_id: followed_id}) do
    query =
      from(
        activity in Activity,
259
260
261
262
263
264
        where:
          fragment(
            "? ->> 'type' = 'Follow'",
            activity.data
          ),
        where: activity.actor == ^follower_id,
lain's avatar
lain committed
265
266
267
268
        where:
          fragment(
            "? @> ?",
            activity.data,
269
            ^%{object: followed_id}
lain's avatar
lain committed
270
271
272
273
274
          ),
        order_by: [desc: :id],
        limit: 1
      )

lain's avatar
lain committed
275
276
277
278
279
280
    Repo.one(query)
  end

  #### Announce-related helpers

  @doc """
281
  Retruns an existing announce activity if the notice has already been announced
lain's avatar
lain committed
282
  """
normandy's avatar
normandy committed
283
284
285
286
  def get_existing_announce(actor, %{data: %{"id" => id}}) do
    query =
      from(
        activity in Activity,
lain's avatar
lain committed
287
        where: activity.actor == ^actor,
normandy's avatar
normandy committed
288
289
290
291
292
293
294
295
296
297
298
299
300
301
        # this is to use the index
        where:
          fragment(
            "coalesce((?)->'object'->>'id', (?)->>'object') = ?",
            activity.data,
            activity.data,
            ^id
          ),
        where: fragment("(?)->>'type' = 'Announce'", activity.data)
      )

    Repo.one(query)
  end

normandy's avatar
normandy committed
302
303
304
  @doc """
  Make announce activity data for the given actor and object
  """
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
  # for relayed messages, we only want to send to subscribers
  def make_announce_data(
        %User{ap_id: ap_id, nickname: nil} = user,
        %Object{data: %{"id" => id}} = object,
        activity_id
      ) do
    data = %{
      "type" => "Announce",
      "actor" => ap_id,
      "object" => id,
      "to" => [user.follower_address],
      "cc" => [],
      "context" => object.data["context"]
    }

    if activity_id, do: Map.put(data, "id", activity_id), else: data
  end

lain's avatar
lain committed
323
324
325
326
327
  def make_announce_data(
        %User{ap_id: ap_id} = user,
        %Object{data: %{"id" => id}} = object,
        activity_id
      ) do
lain's avatar
lain committed
328
329
330
331
    data = %{
      "type" => "Announce",
      "actor" => ap_id,
      "object" => id,
lain's avatar
lain committed
332
      "to" => [user.follower_address, object.data["actor"]],
lain's avatar
lain committed
333
      "cc" => ["https://www.w3.org/ns/activitystreams#Public"],
lain's avatar
lain committed
334
335
336
337
338
339
      "context" => object.data["context"]
    }

    if activity_id, do: Map.put(data, "id", activity_id), else: data
  end

340
341
342
343
344
  @doc """
  Make unannounce activity data for the given actor and object
  """
  def make_unannounce_data(
        %User{ap_id: ap_id} = user,
345
346
        %Activity{data: %{"context" => context}} = activity,
        activity_id
347
      ) do
348
    data = %{
349
350
      "type" => "Undo",
      "actor" => ap_id,
351
      "object" => activity.data,
normandy's avatar
normandy committed
352
      "to" => [user.follower_address, activity.data["actor"]],
353
      "cc" => ["https://www.w3.org/ns/activitystreams#Public"],
normandy's avatar
normandy committed
354
      "context" => context
355
    }
356
357

    if activity_id, do: Map.put(data, "id", activity_id), else: data
358
359
  end

Thog's avatar
Thog committed
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
  def make_unlike_data(
        %User{ap_id: ap_id} = user,
        %Activity{data: %{"context" => context}} = activity,
        activity_id
      ) do
    data = %{
      "type" => "Undo",
      "actor" => ap_id,
      "object" => activity.data,
      "to" => [user.follower_address, activity.data["actor"]],
      "cc" => ["https://www.w3.org/ns/activitystreams#Public"],
      "context" => context
    }

    if activity_id, do: Map.put(data, "id", activity_id), else: data
  end

377
378
379
380
381
382
  def add_announce_to_object(
        %Activity{
          data: %{"actor" => actor, "cc" => ["https://www.w3.org/ns/activitystreams#Public"]}
        },
        object
      ) do
lain's avatar
lain committed
383
    with announcements <- [actor | object.data["announcements"] || []] |> Enum.uniq() do
lain's avatar
lain committed
384
385
386
387
      update_element_in_object("announcement", announcements, object)
    end
  end

388
389
  def add_announce_to_object(_, object), do: {:ok, object}

normandy's avatar
normandy committed
390
391
392
393
394
395
  def remove_announce_from_object(%Activity{data: %{"actor" => actor}}, object) do
    with announcements <- (object.data["announcements"] || []) |> List.delete(actor) do
      update_element_in_object("announcement", announcements, object)
    end
  end

lain's avatar
lain committed
396
397
  #### Unfollow-related helpers

normandy's avatar
normandy committed
398
399
  def make_unfollow_data(follower, followed, follow_activity, activity_id) do
    data = %{
lain's avatar
lain committed
400
401
402
      "type" => "Undo",
      "actor" => follower.ap_id,
      "to" => [followed.ap_id],
normandy's avatar
normandy committed
403
      "object" => follow_activity.data
lain's avatar
lain committed
404
    }
normandy's avatar
Format    
normandy committed
405

normandy's avatar
normandy committed
406
    if activity_id, do: Map.put(data, "id", activity_id), else: data
lain's avatar
lain committed
407
408
  end

normandy's avatar
normandy committed
409
410
411
412
413
  #### Block-related helpers
  def fetch_latest_block(%User{ap_id: blocker_id}, %User{ap_id: blocked_id}) do
    query =
      from(
        activity in Activity,
414
415
416
417
418
419
        where:
          fragment(
            "? ->> 'type' = 'Block'",
            activity.data
          ),
        where: activity.actor == ^blocker_id,
normandy's avatar
normandy committed
420
421
422
423
        where:
          fragment(
            "? @> ?",
            activity.data,
424
            ^%{object: blocked_id}
normandy's avatar
normandy committed
425
426
427
428
429
430
431
432
          ),
        order_by: [desc: :id],
        limit: 1
      )

    Repo.one(query)
  end

normandy's avatar
normandy committed
433
434
  def make_block_data(blocker, blocked, activity_id) do
    data = %{
normandy's avatar
normandy committed
435
436
437
438
439
      "type" => "Block",
      "actor" => blocker.ap_id,
      "to" => [blocked.ap_id],
      "object" => blocked.ap_id
    }
normandy's avatar
Format    
normandy committed
440

normandy's avatar
normandy committed
441
    if activity_id, do: Map.put(data, "id", activity_id), else: data
normandy's avatar
normandy committed
442
443
  end

normandy's avatar
normandy committed
444
445
  def make_unblock_data(blocker, blocked, block_activity, activity_id) do
    data = %{
normandy's avatar
normandy committed
446
447
448
449
      "type" => "Undo",
      "actor" => blocker.ap_id,
      "to" => [blocked.ap_id],
      "object" => block_activity.data
lain's avatar
lain committed
450
    }
normandy's avatar
Format    
normandy committed
451

normandy's avatar
normandy committed
452
    if activity_id, do: Map.put(data, "id", activity_id), else: data
lain's avatar
lain committed
453
454
455
456
457
458
  end

  #### Create-related helpers

  def make_create_data(params, additional) do
    published = params.published || make_date()
lain's avatar
lain committed
459

Thog's avatar
Thog committed
460
    %{
lain's avatar
lain committed
461
      "type" => "Create",
lain's avatar
lain committed
462
      "to" => params.to |> Enum.uniq(),
lain's avatar
lain committed
463
464
465
466
467
468
469
470
      "actor" => params.actor.ap_id,
      "object" => params.object,
      "published" => published,
      "context" => params.context
    }
    |> Map.merge(additional)
  end
end