activitypub utils: optimize block and follow activity lookup
[akkoma] / lib / pleroma / web / activity_pub / utils.ex
1 defmodule Pleroma.Web.ActivityPub.Utils do
2 alias Pleroma.{Repo, Web, Object, Activity, User}
3 alias Pleroma.Web.Router.Helpers
4 alias Pleroma.Web.Endpoint
5 alias Ecto.{Changeset, UUID}
6 import Ecto.Query
7
8 # Some implementations send the actor URI as the actor field, others send the entire actor object,
9 # so figure out what the actor's URI is based on what we have.
10 def normalize_actor(actor) do
11 cond do
12 is_binary(actor) ->
13 actor
14
15 is_map(actor) ->
16 actor["id"]
17 end
18 end
19
20 def normalize_params(params) do
21 Map.put(params, "actor", normalize_actor(params["actor"]))
22 end
23
24 def make_json_ld_header do
25 %{
26 "@context" => [
27 "https://www.w3.org/ns/activitystreams",
28 "https://w3id.org/security/v1",
29 %{
30 "manuallyApprovesFollowers" => "as:manuallyApprovesFollowers",
31 "sensitive" => "as:sensitive",
32 "Hashtag" => "as:Hashtag",
33 "ostatus" => "http://ostatus.org#",
34 "atomUri" => "ostatus:atomUri",
35 "inReplyToAtomUri" => "ostatus:inReplyToAtomUri",
36 "conversation" => "ostatus:conversation",
37 "toot" => "http://joinmastodon.org/ns#",
38 "Emoji" => "toot:Emoji"
39 }
40 ]
41 }
42 end
43
44 def make_date do
45 DateTime.utc_now() |> DateTime.to_iso8601()
46 end
47
48 def generate_activity_id do
49 generate_id("activities")
50 end
51
52 def generate_context_id do
53 generate_id("contexts")
54 end
55
56 def generate_object_id do
57 Helpers.o_status_url(Endpoint, :object, UUID.generate())
58 end
59
60 def generate_id(type) do
61 "#{Web.base_url()}/#{type}/#{UUID.generate()}"
62 end
63
64 def create_context(context) do
65 context = context || generate_id("contexts")
66 changeset = Object.context_mapping(context)
67
68 case Repo.insert(changeset) do
69 {:ok, object} ->
70 object
71
72 # This should be solved by an upsert, but it seems ecto
73 # has problems accessing the constraint inside the jsonb.
74 {:error, _} ->
75 Object.get_cached_by_ap_id(context)
76 end
77 end
78
79 @doc """
80 Enqueues an activity for federation if it's local
81 """
82 def maybe_federate(%Activity{local: true} = activity) do
83 priority =
84 case activity.data["type"] do
85 "Delete" -> 10
86 "Create" -> 1
87 _ -> 5
88 end
89
90 Pleroma.Web.Federator.enqueue(:publish, activity, priority)
91 :ok
92 end
93
94 def maybe_federate(_), do: :ok
95
96 @doc """
97 Adds an id and a published data if they aren't there,
98 also adds it to an included object
99 """
100 def lazy_put_activity_defaults(map) do
101 %{data: %{"id" => context}, id: context_id} = create_context(map["context"])
102
103 map =
104 map
105 |> Map.put_new_lazy("id", &generate_activity_id/0)
106 |> Map.put_new_lazy("published", &make_date/0)
107 |> Map.put_new("context", context)
108 |> Map.put_new("context_id", context_id)
109
110 if is_map(map["object"]) do
111 object = lazy_put_object_defaults(map["object"], map)
112 %{map | "object" => object}
113 else
114 map
115 end
116 end
117
118 @doc """
119 Adds an id and published date if they aren't there.
120 """
121 def lazy_put_object_defaults(map, activity \\ %{}) do
122 map
123 |> Map.put_new_lazy("id", &generate_object_id/0)
124 |> Map.put_new_lazy("published", &make_date/0)
125 |> Map.put_new("context", activity["context"])
126 |> Map.put_new("context_id", activity["context_id"])
127 end
128
129 @doc """
130 Inserts a full object if it is contained in an activity.
131 """
132 def insert_full_object(%{"object" => %{"type" => type} = object_data})
133 when is_map(object_data) and type in ["Note"] do
134 with {:ok, _} <- Object.create(object_data) do
135 :ok
136 end
137 end
138
139 def insert_full_object(_), do: :ok
140
141 def update_object_in_activities(%{data: %{"id" => id}} = object) do
142 # TODO
143 # Update activities that already had this. Could be done in a seperate process.
144 # Alternatively, just don't do this and fetch the current object each time. Most
145 # could probably be taken from cache.
146 relevant_activities = Activity.all_by_object_ap_id(id)
147
148 Enum.map(relevant_activities, fn activity ->
149 new_activity_data = activity.data |> Map.put("object", object.data)
150 changeset = Changeset.change(activity, data: new_activity_data)
151 Repo.update(changeset)
152 end)
153 end
154
155 #### Like-related helpers
156
157 @doc """
158 Returns an existing like if a user already liked an object
159 """
160 def get_existing_like(actor, %{data: %{"id" => id}}) do
161 query =
162 from(
163 activity in Activity,
164 where: fragment("(?)->>'actor' = ?", activity.data, ^actor),
165 # this is to use the index
166 where:
167 fragment(
168 "coalesce((?)->'object'->>'id', (?)->>'object') = ?",
169 activity.data,
170 activity.data,
171 ^id
172 ),
173 where: fragment("(?)->>'type' = 'Like'", activity.data)
174 )
175
176 Repo.one(query)
177 end
178
179 def make_like_data(%User{ap_id: ap_id} = actor, %{data: %{"id" => id}} = object, activity_id) do
180 data = %{
181 "type" => "Like",
182 "actor" => ap_id,
183 "object" => id,
184 "to" => [actor.follower_address, object.data["actor"]],
185 "cc" => ["https://www.w3.org/ns/activitystreams#Public"],
186 "context" => object.data["context"]
187 }
188
189 if activity_id, do: Map.put(data, "id", activity_id), else: data
190 end
191
192 def update_element_in_object(property, element, object) do
193 with new_data <-
194 object.data
195 |> Map.put("#{property}_count", length(element))
196 |> Map.put("#{property}s", element),
197 changeset <- Changeset.change(object, data: new_data),
198 {:ok, object} <- Repo.update(changeset),
199 _ <- update_object_in_activities(object) do
200 {:ok, object}
201 end
202 end
203
204 def update_likes_in_object(likes, object) do
205 update_element_in_object("like", likes, object)
206 end
207
208 def add_like_to_object(%Activity{data: %{"actor" => actor}}, object) do
209 with likes <- [actor | object.data["likes"] || []] |> Enum.uniq() do
210 update_likes_in_object(likes, object)
211 end
212 end
213
214 def remove_like_from_object(%Activity{data: %{"actor" => actor}}, object) do
215 with likes <- (object.data["likes"] || []) |> List.delete(actor) do
216 update_likes_in_object(likes, object)
217 end
218 end
219
220 #### Follow-related helpers
221
222 @doc """
223 Makes a follow activity data for the given follower and followed
224 """
225 def make_follow_data(%User{ap_id: follower_id}, %User{ap_id: followed_id}, activity_id) do
226 data = %{
227 "type" => "Follow",
228 "actor" => follower_id,
229 "to" => [followed_id],
230 "cc" => ["https://www.w3.org/ns/activitystreams#Public"],
231 "object" => followed_id
232 }
233
234 if activity_id, do: Map.put(data, "id", activity_id), else: data
235 end
236
237 def fetch_latest_follow(%User{ap_id: follower_id}, %User{ap_id: followed_id}) do
238 query =
239 from(
240 activity in Activity,
241 where:
242 fragment(
243 "? ->> 'type' = 'Follow'",
244 activity.data
245 ),
246 where: activity.actor == ^follower_id,
247 where:
248 fragment(
249 "? @> ?",
250 activity.data,
251 ^%{object: followed_id}
252 ),
253 order_by: [desc: :id],
254 limit: 1
255 )
256
257 Repo.one(query)
258 end
259
260 #### Announce-related helpers
261
262 @doc """
263 Retruns an existing announce activity if the notice has already been announced
264 """
265 def get_existing_announce(actor, %{data: %{"id" => id}}) do
266 query =
267 from(
268 activity in Activity,
269 where: activity.actor == ^actor,
270 # this is to use the index
271 where:
272 fragment(
273 "coalesce((?)->'object'->>'id', (?)->>'object') = ?",
274 activity.data,
275 activity.data,
276 ^id
277 ),
278 where: fragment("(?)->>'type' = 'Announce'", activity.data)
279 )
280
281 Repo.one(query)
282 end
283
284 @doc """
285 Make announce activity data for the given actor and object
286 """
287 def make_announce_data(
288 %User{ap_id: ap_id} = user,
289 %Object{data: %{"id" => id}} = object,
290 activity_id
291 ) do
292 data = %{
293 "type" => "Announce",
294 "actor" => ap_id,
295 "object" => id,
296 "to" => [user.follower_address, object.data["actor"]],
297 "cc" => ["https://www.w3.org/ns/activitystreams#Public"],
298 "context" => object.data["context"]
299 }
300
301 if activity_id, do: Map.put(data, "id", activity_id), else: data
302 end
303
304 @doc """
305 Make unannounce activity data for the given actor and object
306 """
307 def make_unannounce_data(
308 %User{ap_id: ap_id} = user,
309 %Activity{data: %{"context" => context}} = activity,
310 activity_id
311 ) do
312 data = %{
313 "type" => "Undo",
314 "actor" => ap_id,
315 "object" => activity.data,
316 "to" => [user.follower_address, activity.data["actor"]],
317 "cc" => ["https://www.w3.org/ns/activitystreams#Public"],
318 "context" => context
319 }
320
321 if activity_id, do: Map.put(data, "id", activity_id), else: data
322 end
323
324 def make_unlike_data(
325 %User{ap_id: ap_id} = user,
326 %Activity{data: %{"context" => context}} = activity,
327 activity_id
328 ) do
329 data = %{
330 "type" => "Undo",
331 "actor" => ap_id,
332 "object" => activity.data,
333 "to" => [user.follower_address, activity.data["actor"]],
334 "cc" => ["https://www.w3.org/ns/activitystreams#Public"],
335 "context" => context
336 }
337
338 if activity_id, do: Map.put(data, "id", activity_id), else: data
339 end
340
341 def add_announce_to_object(%Activity{data: %{"actor" => actor}}, object) do
342 with announcements <- [actor | object.data["announcements"] || []] |> Enum.uniq() do
343 update_element_in_object("announcement", announcements, object)
344 end
345 end
346
347 def remove_announce_from_object(%Activity{data: %{"actor" => actor}}, object) do
348 with announcements <- (object.data["announcements"] || []) |> List.delete(actor) do
349 update_element_in_object("announcement", announcements, object)
350 end
351 end
352
353 #### Unfollow-related helpers
354
355 def make_unfollow_data(follower, followed, follow_activity, activity_id) do
356 data = %{
357 "type" => "Undo",
358 "actor" => follower.ap_id,
359 "to" => [followed.ap_id],
360 "object" => follow_activity.data
361 }
362
363 if activity_id, do: Map.put(data, "id", activity_id), else: data
364 end
365
366 #### Block-related helpers
367 def fetch_latest_block(%User{ap_id: blocker_id}, %User{ap_id: blocked_id}) do
368 query =
369 from(
370 activity in Activity,
371 where:
372 fragment(
373 "? ->> 'type' = 'Block'",
374 activity.data
375 ),
376 where: activity.actor == ^blocker_id,
377 where:
378 fragment(
379 "? @> ?",
380 activity.data,
381 ^%{object: blocked_id}
382 ),
383 order_by: [desc: :id],
384 limit: 1
385 )
386
387 Repo.one(query)
388 end
389
390 def make_block_data(blocker, blocked, activity_id) do
391 data = %{
392 "type" => "Block",
393 "actor" => blocker.ap_id,
394 "to" => [blocked.ap_id],
395 "object" => blocked.ap_id
396 }
397
398 if activity_id, do: Map.put(data, "id", activity_id), else: data
399 end
400
401 def make_unblock_data(blocker, blocked, block_activity, activity_id) do
402 data = %{
403 "type" => "Undo",
404 "actor" => blocker.ap_id,
405 "to" => [blocked.ap_id],
406 "object" => block_activity.data
407 }
408
409 if activity_id, do: Map.put(data, "id", activity_id), else: data
410 end
411
412 #### Create-related helpers
413
414 def make_create_data(params, additional) do
415 published = params.published || make_date()
416
417 %{
418 "type" => "Create",
419 "to" => params.to |> Enum.uniq(),
420 "actor" => params.actor.ap_id,
421 "object" => params.object,
422 "published" => published,
423 "context" => params.context
424 }
425 |> Map.merge(additional)
426 end
427 end