2871a2544738086cffe934707c2359f9ec386aa5
[akkoma] / lib / pleroma / web / activity_pub / transmogrifier.ex
1 defmodule Pleroma.Web.ActivityPub.Transmogrifier do
2 @moduledoc """
3 A module to handle coding from internal to wire ActivityPub and back.
4 """
5 alias Pleroma.User
6 alias Pleroma.Object
7 alias Pleroma.Activity
8 alias Pleroma.Repo
9 alias Pleroma.Web.ActivityPub.ActivityPub
10
11 import Ecto.Query
12
13 require Logger
14
15 @doc """
16 Modifies an incoming AP object (mastodon format) to our internal format.
17 """
18 def fix_object(object) do
19 object
20 |> Map.put("actor", object["attributedTo"])
21 |> fix_attachments
22 |> fix_context
23 |> fix_in_reply_to
24 |> fix_emoji
25 |> fix_tag
26 end
27
28 def fix_in_reply_to(%{"inReplyTo" => in_reply_to_id} = object)
29 when not is_nil(in_reply_to_id) do
30 case ActivityPub.fetch_object_from_id(in_reply_to_id) do
31 {:ok, replied_object} ->
32 activity = Activity.get_create_activity_by_object_ap_id(replied_object.data["id"])
33
34 object
35 |> Map.put("inReplyTo", replied_object.data["id"])
36 |> Map.put("inReplyToAtomUri", object["inReplyToAtomUri"] || in_reply_to_id)
37 |> Map.put("inReplyToStatusId", activity.id)
38 |> Map.put("conversation", replied_object.data["context"] || object["conversation"])
39 |> Map.put("context", replied_object.data["context"] || object["conversation"])
40
41 e ->
42 Logger.error("Couldn't fetch #{object["inReplyTo"]} #{inspect(e)}")
43 object
44 end
45 end
46
47 def fix_in_reply_to(object), do: object
48
49 def fix_context(object) do
50 object
51 |> Map.put("context", object["conversation"])
52 end
53
54 def fix_attachments(object) do
55 attachments =
56 (object["attachment"] || [])
57 |> Enum.map(fn data ->
58 url = [%{"type" => "Link", "mediaType" => data["mediaType"], "href" => data["url"]}]
59 Map.put(data, "url", url)
60 end)
61
62 object
63 |> Map.put("attachment", attachments)
64 end
65
66 def fix_emoji(object) do
67 tags = object["tag"] || []
68 emoji = tags |> Enum.filter(fn data -> data["type"] == "Emoji" and data["icon"] end)
69
70 emoji =
71 emoji
72 |> Enum.reduce(%{}, fn data, mapping ->
73 name = data["name"]
74
75 if String.starts_with?(name, ":") do
76 name = name |> String.slice(1..-2)
77 end
78
79 mapping |> Map.put(name, data["icon"]["url"])
80 end)
81
82 # we merge mastodon and pleroma emoji into a single mapping, to allow for both wire formats
83 emoji = Map.merge(object["emoji"] || %{}, emoji)
84
85 object
86 |> Map.put("emoji", emoji)
87 end
88
89 def fix_tag(object) do
90 tags =
91 (object["tag"] || [])
92 |> Enum.filter(fn data -> data["type"] == "Hashtag" and data["name"] end)
93 |> Enum.map(fn data -> String.slice(data["name"], 1..-1) end)
94
95 combined = (object["tag"] || []) ++ tags
96
97 object
98 |> Map.put("tag", combined)
99 end
100
101 # TODO: validate those with a Ecto scheme
102 # - tags
103 # - emoji
104 def handle_incoming(%{"type" => "Create", "object" => %{"type" => "Note"} = object} = data) do
105 with nil <- Activity.get_create_activity_by_object_ap_id(object["id"]),
106 %User{} = user <- User.get_or_fetch_by_ap_id(data["actor"]) do
107 object = fix_object(data["object"])
108
109 params = %{
110 to: data["to"],
111 object: object,
112 actor: user,
113 context: object["conversation"],
114 local: false,
115 published: data["published"],
116 additional:
117 Map.take(data, [
118 "cc",
119 "id"
120 ])
121 }
122
123 ActivityPub.create(params)
124 else
125 %Activity{} = activity -> {:ok, activity}
126 _e -> :error
127 end
128 end
129
130 def handle_incoming(
131 %{"type" => "Follow", "object" => followed, "actor" => follower, "id" => id} = data
132 ) do
133 with %User{local: true} = followed <- User.get_cached_by_ap_id(followed),
134 %User{} = follower <- User.get_or_fetch_by_ap_id(follower),
135 {:ok, activity} <- ActivityPub.follow(follower, followed, id, false) do
136 ActivityPub.accept(%{to: [follower.ap_id], actor: followed.ap_id, object: data, local: true})
137
138 User.follow(follower, followed)
139 {:ok, activity}
140 else
141 _e -> :error
142 end
143 end
144
145 def handle_incoming(
146 %{"type" => "Like", "object" => object_id, "actor" => actor, "id" => id} = data
147 ) do
148 with %User{} = actor <- User.get_or_fetch_by_ap_id(actor),
149 {:ok, object} <-
150 get_obj_helper(object_id) || ActivityPub.fetch_object_from_id(object_id),
151 {:ok, activity, object} <- ActivityPub.like(actor, object, id, false) do
152 {:ok, activity}
153 else
154 _e -> :error
155 end
156 end
157
158 def handle_incoming(
159 %{"type" => "Announce", "object" => object_id, "actor" => actor, "id" => id} = data
160 ) do
161 with %User{} = actor <- User.get_or_fetch_by_ap_id(actor),
162 {:ok, object} <-
163 get_obj_helper(object_id) || ActivityPub.fetch_object_from_id(object_id),
164 {:ok, activity, object} <- ActivityPub.announce(actor, object, id, false) do
165 {:ok, activity}
166 else
167 _e -> :error
168 end
169 end
170
171 def handle_incoming(
172 %{"type" => "Update", "object" => %{"type" => "Person"} = object, "actor" => actor_id} =
173 data
174 ) do
175 with %User{ap_id: ^actor_id} = actor <- User.get_by_ap_id(object["id"]) do
176 {:ok, new_user_data} = ActivityPub.user_data_from_user_object(object)
177
178 banner = new_user_data[:info]["banner"]
179
180 update_data =
181 new_user_data
182 |> Map.take([:name, :bio, :avatar])
183 |> Map.put(:info, Map.merge(actor.info, %{"banner" => banner}))
184
185 actor
186 |> User.upgrade_changeset(update_data)
187 |> User.update_and_set_cache()
188
189 ActivityPub.update(%{
190 local: false,
191 to: data["to"] || [],
192 cc: data["cc"] || [],
193 object: object,
194 actor: actor_id
195 })
196 else
197 e ->
198 Logger.error(e)
199 :error
200 end
201 end
202
203 # TODO: Make secure.
204 def handle_incoming(
205 %{"type" => "Delete", "object" => object_id, "actor" => actor, "id" => id} = data
206 ) do
207 object_id =
208 case object_id do
209 %{"id" => id} -> id
210 id -> id
211 end
212
213 with %User{} = actor <- User.get_or_fetch_by_ap_id(actor),
214 {:ok, object} <-
215 get_obj_helper(object_id) || ActivityPub.fetch_object_from_id(object_id),
216 {:ok, activity} <- ActivityPub.delete(object, false) do
217 {:ok, activity}
218 else
219 e -> :error
220 end
221 end
222
223 # TODO
224 # Accept
225 # Undo
226
227 def handle_incoming(_), do: :error
228
229 def get_obj_helper(id) do
230 if object = Object.get_by_ap_id(id), do: {:ok, object}, else: nil
231 end
232
233 def set_reply_to_uri(%{"inReplyTo" => inReplyTo} = object) do
234 with false <- String.starts_with?(inReplyTo, "http"),
235 {:ok, %{data: replied_to_object}} <- get_obj_helper(inReplyTo) do
236 Map.put(object, "inReplyTo", replied_to_object["external_url"] || inReplyTo)
237 else
238 _e -> object
239 end
240 end
241
242 def set_reply_to_uri(obj), do: obj
243
244 # Prepares the object of an outgoing create activity.
245 def prepare_object(object) do
246 object
247 |> set_sensitive
248 |> add_hashtags
249 |> add_mention_tags
250 |> add_emoji_tags
251 |> add_attributed_to
252 |> prepare_attachments
253 |> set_conversation
254 |> set_reply_to_uri
255 end
256
257 @doc
258 """
259 internal -> Mastodon
260 """
261
262 def prepare_outgoing(%{"type" => "Create", "object" => %{"type" => "Note"} = object} = data) do
263 object =
264 object
265 |> prepare_object
266
267 data =
268 data
269 |> Map.put("object", object)
270 |> Map.put("@context", "https://www.w3.org/ns/activitystreams")
271
272 {:ok, data}
273 end
274
275 def prepare_outgoing(%{"type" => type} = data) do
276 data =
277 data
278 |> maybe_fix_object_url
279 |> Map.put("@context", "https://www.w3.org/ns/activitystreams")
280
281 {:ok, data}
282 end
283
284 def maybe_fix_object_url(data) do
285 if is_binary(data["object"]) and not String.starts_with?(data["object"], "http") do
286 case ActivityPub.fetch_object_from_id(data["object"]) do
287 {:ok, relative_object} ->
288 if relative_object.data["external_url"] do
289 data =
290 data
291 |> Map.put("object", relative_object.data["external_url"])
292 else
293 data
294 end
295
296 e ->
297 Logger.error("Couldn't fetch #{data["object"]} #{inspect(e)}")
298 data
299 end
300 else
301 data
302 end
303 end
304
305 def add_hashtags(object) do
306 tags =
307 (object["tag"] || [])
308 |> Enum.map(fn tag ->
309 %{
310 "href" => Pleroma.Web.Endpoint.url() <> "/tags/#{tag}",
311 "name" => "##{tag}",
312 "type" => "Hashtag"
313 }
314 end)
315
316 object
317 |> Map.put("tag", tags)
318 end
319
320 def add_mention_tags(object) do
321 recipients = object["to"] ++ (object["cc"] || [])
322
323 mentions =
324 recipients
325 |> Enum.map(fn ap_id -> User.get_cached_by_ap_id(ap_id) end)
326 |> Enum.filter(& &1)
327 |> Enum.map(fn user ->
328 %{"type" => "Mention", "href" => user.ap_id, "name" => "@#{user.nickname}"}
329 end)
330
331 tags = object["tag"] || []
332
333 object
334 |> Map.put("tag", tags ++ mentions)
335 end
336
337 # TODO: we should probably send mtime instead of unix epoch time for updated
338 def add_emoji_tags(object) do
339 tags = object["tag"] || []
340 emoji = object["emoji"] || []
341
342 out =
343 emoji
344 |> Enum.map(fn {name, url} ->
345 %{
346 "icon" => %{"url" => url, "type" => "Image"},
347 "name" => ":" <> name <> ":",
348 "type" => "Emoji",
349 "updated" => "1970-01-01T00:00:00Z",
350 "id" => url
351 }
352 end)
353
354 object
355 |> Map.put("tag", tags ++ out)
356 end
357
358 def set_conversation(object) do
359 Map.put(object, "conversation", object["context"])
360 end
361
362 def set_sensitive(object) do
363 tags = object["tag"] || []
364 Map.put(object, "sensitive", "nsfw" in tags)
365 end
366
367 def add_attributed_to(object) do
368 attributedTo = object["attributedTo"] || object["actor"]
369
370 object
371 |> Map.put("attributedTo", attributedTo)
372 end
373
374 def prepare_attachments(object) do
375 attachments =
376 (object["attachment"] || [])
377 |> Enum.map(fn data ->
378 [%{"mediaType" => media_type, "href" => href} | _] = data["url"]
379 %{"url" => href, "mediaType" => media_type, "name" => data["name"], "type" => "Document"}
380 end)
381
382 object
383 |> Map.put("attachment", attachments)
384 end
385
386 defp user_upgrade_task(user) do
387 old_follower_address = User.ap_followers(user)
388
389 q =
390 from(
391 u in User,
392 where: ^old_follower_address in u.following,
393 update: [
394 set: [
395 following:
396 fragment(
397 "array_replace(?,?,?)",
398 u.following,
399 ^old_follower_address,
400 ^user.follower_address
401 )
402 ]
403 ]
404 )
405
406 Repo.update_all(q, [])
407
408 maybe_retire_websub(user.ap_id)
409
410 # Only do this for recent activties, don't go through the whole db.
411 # Only look at the last 1000 activities.
412 since = (Repo.aggregate(Activity, :max, :id) || 0) - 1_000
413
414 q =
415 from(
416 a in Activity,
417 where: ^old_follower_address in a.recipients,
418 where: a.id > ^since,
419 update: [
420 set: [
421 recipients:
422 fragment(
423 "array_replace(?,?,?)",
424 a.recipients,
425 ^old_follower_address,
426 ^user.follower_address
427 )
428 ]
429 ]
430 )
431
432 Repo.update_all(q, [])
433 end
434
435 def upgrade_user_from_ap_id(ap_id, async \\ true) do
436 with %User{local: false} = user <- User.get_by_ap_id(ap_id),
437 {:ok, data} <- ActivityPub.fetch_and_prepare_user_from_ap_id(ap_id) do
438 data =
439 data
440 |> Map.put(:info, Map.merge(user.info, data[:info]))
441
442 already_ap = User.ap_enabled?(user)
443
444 {:ok, user} =
445 User.upgrade_changeset(user, data)
446 |> Repo.update()
447
448 if !already_ap do
449 # This could potentially take a long time, do it in the background
450 if async do
451 Task.start(fn ->
452 user_upgrade_task(user)
453 end)
454 else
455 user_upgrade_task(user)
456 end
457 end
458
459 {:ok, user}
460 else
461 e -> e
462 end
463 end
464
465 def maybe_retire_websub(ap_id) do
466 # some sanity checks
467 if is_binary(ap_id) && String.length(ap_id) > 8 do
468 q =
469 from(
470 ws in Pleroma.Web.Websub.WebsubClientSubscription,
471 where: fragment("? like ?", ws.topic, ^"#{ap_id}%")
472 )
473
474 Repo.delete_all(q)
475 end
476 end
477 end