00b9f74ff34af9327b1448c3acdf297bf8806c2c
[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} <- get_obj_helper(object_id) || ActivityPub.fetch_object_from_id(object_id),
150 {:ok, activity, object} <- ActivityPub.like(actor, object, id, false) do
151 {:ok, activity}
152 else
153 _e -> :error
154 end
155 end
156
157 def handle_incoming(
158 %{"type" => "Announce", "object" => object_id, "actor" => actor, "id" => id} = data
159 ) do
160 with %User{} = actor <- User.get_or_fetch_by_ap_id(actor),
161 {:ok, object} <- get_obj_helper(object_id) || ActivityPub.fetch_object_from_id(object_id),
162 {:ok, activity, object} <- ActivityPub.announce(actor, object, id, false) do
163 {:ok, activity}
164 else
165 _e -> :error
166 end
167 end
168
169 def handle_incoming(
170 %{"type" => "Update", "object" => %{"type" => "Person"} = object, "actor" => actor_id} =
171 data
172 ) do
173 with %User{ap_id: ^actor_id} = actor <- User.get_by_ap_id(object["id"]) do
174 {:ok, new_user_data} = ActivityPub.user_data_from_user_object(object)
175
176 banner = new_user_data[:info]["banner"]
177
178 update_data =
179 new_user_data
180 |> Map.take([:name, :bio, :avatar])
181 |> Map.put(:info, Map.merge(actor.info, %{"banner" => banner}))
182
183 actor
184 |> User.upgrade_changeset(update_data)
185 |> User.update_and_set_cache()
186
187 ActivityPub.update(%{
188 local: false,
189 to: data["to"] || [],
190 cc: data["cc"] || [],
191 object: object,
192 actor: actor_id
193 })
194 else
195 e ->
196 Logger.error(e)
197 :error
198 end
199 end
200
201 # TODO: Make secure.
202 def handle_incoming(
203 %{"type" => "Delete", "object" => object_id, "actor" => actor, "id" => id} = data
204 ) do
205 object_id =
206 case object_id do
207 %{"id" => id} -> id
208 id -> id
209 end
210
211 with %User{} = actor <- User.get_or_fetch_by_ap_id(actor),
212 {:ok, object} <- get_obj_helper(object_id) || ActivityPub.fetch_object_from_id(object_id),
213 {:ok, activity} <- ActivityPub.delete(object, false) do
214 {:ok, activity}
215 else
216 e -> :error
217 end
218 end
219
220 # TODO
221 # Accept
222 # Undo
223
224 def handle_incoming(_), do: :error
225
226 def get_obj_helper(id) do
227 if object = Object.get_by_ap_id(id), do: {:ok, object}, else: nil
228 end
229
230 def set_reply_to_uri(%{"inReplyTo" => inReplyTo} = object) do
231 with false <- String.starts_with?(inReplyTo, "http"),
232 {:ok, %{data: replied_to_object}} <- get_obj_helper(inReplyTo) do
233 Map.put(object, "inReplyTo", replied_to_object["external_url"] || inReplyTo)
234 else
235 _e -> object
236 end
237 end
238
239 def set_reply_to_uri(obj), do: obj
240
241 # Prepares the object of an outgoing create activity.
242 def prepare_object(object) do
243 object
244 |> set_sensitive
245 |> add_hashtags
246 |> add_mention_tags
247 |> add_emoji_tags
248 |> add_attributed_to
249 |> prepare_attachments
250 |> set_conversation
251 |> set_reply_to_uri
252 end
253
254 @doc
255 """
256 internal -> Mastodon
257 """
258
259 def prepare_outgoing(%{"type" => "Create", "object" => %{"type" => "Note"} = object} = data) do
260 object =
261 object
262 |> prepare_object
263
264 data =
265 data
266 |> Map.put("object", object)
267 |> Map.put("@context", "https://www.w3.org/ns/activitystreams")
268
269 {:ok, data}
270 end
271
272 def prepare_outgoing(%{"type" => type} = data) do
273 data =
274 data
275 |> maybe_fix_object_url
276 |> Map.put("@context", "https://www.w3.org/ns/activitystreams")
277
278 {:ok, data}
279 end
280
281 def maybe_fix_object_url(data) do
282 if is_binary(data["object"]) and not String.starts_with?(data["object"], "http") do
283 case ActivityPub.fetch_object_from_id(data["object"]) do
284 {:ok, relative_object} ->
285 if relative_object.data["external_url"] do
286 data =
287 data
288 |> Map.put("object", relative_object.data["external_url"])
289 else
290 data
291 end
292
293 e ->
294 Logger.error("Couldn't fetch #{data["object"]} #{inspect(e)}")
295 data
296 end
297 else
298 data
299 end
300 end
301
302 def add_hashtags(object) do
303 tags =
304 (object["tag"] || [])
305 |> Enum.map(fn tag ->
306 %{
307 "href" => Pleroma.Web.Endpoint.url() <> "/tags/#{tag}",
308 "name" => "##{tag}",
309 "type" => "Hashtag"
310 }
311 end)
312
313 object
314 |> Map.put("tag", tags)
315 end
316
317 def add_mention_tags(object) do
318 recipients = object["to"] ++ (object["cc"] || [])
319
320 mentions =
321 recipients
322 |> Enum.map(fn ap_id -> User.get_cached_by_ap_id(ap_id) end)
323 |> Enum.filter(& &1)
324 |> Enum.map(fn user ->
325 %{"type" => "Mention", "href" => user.ap_id, "name" => "@#{user.nickname}"}
326 end)
327
328 tags = object["tag"] || []
329
330 object
331 |> Map.put("tag", tags ++ mentions)
332 end
333
334 # TODO: we should probably send mtime instead of unix epoch time for updated
335 def add_emoji_tags(object) do
336 tags = object["tag"] || []
337 emoji = object["emoji"] || []
338
339 out =
340 emoji
341 |> Enum.map(fn {name, url} ->
342 %{
343 "icon" => %{"url" => url, "type" => "Image"},
344 "name" => ":" <> name <> ":",
345 "type" => "Emoji",
346 "updated" => "1970-01-01T00:00:00Z",
347 "id" => url
348 }
349 end)
350
351 object
352 |> Map.put("tag", tags ++ out)
353 end
354
355 def set_conversation(object) do
356 Map.put(object, "conversation", object["context"])
357 end
358
359 def set_sensitive(object) do
360 tags = object["tag"] || []
361 Map.put(object, "sensitive", "nsfw" in tags)
362 end
363
364 def add_attributed_to(object) do
365 attributedTo = object["attributedTo"] || object["actor"]
366
367 object
368 |> Map.put("attributedTo", attributedTo)
369 end
370
371 def prepare_attachments(object) do
372 attachments =
373 (object["attachment"] || [])
374 |> Enum.map(fn data ->
375 [%{"mediaType" => media_type, "href" => href} | _] = data["url"]
376 %{"url" => href, "mediaType" => media_type, "name" => data["name"], "type" => "Document"}
377 end)
378
379 object
380 |> Map.put("attachment", attachments)
381 end
382
383 defp user_upgrade_task(user) do
384 old_follower_address = User.ap_followers(user)
385
386 q =
387 from(
388 u in User,
389 where: ^old_follower_address in u.following,
390 update: [
391 set: [
392 following:
393 fragment(
394 "array_replace(?,?,?)",
395 u.following,
396 ^old_follower_address,
397 ^user.follower_address
398 )
399 ]
400 ]
401 )
402
403 Repo.update_all(q, [])
404
405 maybe_retire_websub(user.ap_id)
406
407 # Only do this for recent activties, don't go through the whole db.
408 # Only look at the last 1000 activities.
409 since = (Repo.aggregate(Activity, :max, :id) || 0) - 1_000
410
411 q =
412 from(
413 a in Activity,
414 where: ^old_follower_address in a.recipients,
415 where: a.id > ^since,
416 update: [
417 set: [
418 recipients:
419 fragment(
420 "array_replace(?,?,?)",
421 a.recipients,
422 ^old_follower_address,
423 ^user.follower_address
424 )
425 ]
426 ]
427 )
428
429 Repo.update_all(q, [])
430 end
431
432 def upgrade_user_from_ap_id(ap_id, async \\ true) do
433 with %User{local: false} = user <- User.get_by_ap_id(ap_id),
434 {:ok, data} <- ActivityPub.fetch_and_prepare_user_from_ap_id(ap_id) do
435 data =
436 data
437 |> Map.put(:info, Map.merge(user.info, data[:info]))
438
439 already_ap = User.ap_enabled?(user)
440
441 {:ok, user} =
442 User.upgrade_changeset(user, data)
443 |> Repo.update()
444
445 if !already_ap do
446 # This could potentially take a long time, do it in the background
447 if async do
448 Task.start(fn ->
449 user_upgrade_task(user)
450 end)
451 else
452 user_upgrade_task(user)
453 end
454 end
455
456 {:ok, user}
457 else
458 e -> e
459 end
460 end
461
462 def maybe_retire_websub(ap_id) do
463 # some sanity checks
464 if is_binary(ap_id) && String.length(ap_id) > 8 do
465 q =
466 from(
467 ws in Pleroma.Web.Websub.WebsubClientSubscription,
468 where: fragment("? like ?", ws.topic, ^"#{ap_id}%")
469 )
470
471 Repo.delete_all(q)
472 end
473 end
474 end