Add test.
[akkoma] / lib / pleroma / web / activity_pub / activity_pub.ex
1 defmodule Pleroma.Web.ActivityPub.ActivityPub do
2 alias Pleroma.{Activity, Repo, Object, Upload, User, Notification}
3 alias Pleroma.Web.ActivityPub.{Transmogrifier, MRF}
4 alias Pleroma.Web.WebFinger
5 alias Pleroma.Web.Federator
6 alias Pleroma.Web.OStatus
7 import Ecto.Query
8 import Pleroma.Web.ActivityPub.Utils
9 require Logger
10
11 @httpoison Application.get_env(:pleroma, :httpoison)
12
13 @instance Application.get_env(:pleroma, :instance)
14
15 def get_recipients(data) do
16 (data["to"] || []) ++ (data["cc"] || [])
17 end
18
19 def insert(map, local \\ true) when is_map(map) do
20 with nil <- Activity.get_by_ap_id(map["id"]),
21 map <- lazy_put_activity_defaults(map),
22 {:ok, map} <- MRF.filter(map),
23 :ok <- insert_full_object(map) do
24 {:ok, activity} =
25 Repo.insert(%Activity{
26 data: map,
27 local: local,
28 actor: map["actor"],
29 recipients: get_recipients(map)
30 })
31
32 Notification.create_notifications(activity)
33 stream_out(activity)
34 {:ok, activity}
35 else
36 %Activity{} = activity -> {:ok, activity}
37 error -> {:error, error}
38 end
39 end
40
41 def stream_out(activity) do
42 if activity.data["type"] in ["Create", "Announce"] do
43 Pleroma.Web.Streamer.stream("user", activity)
44
45 if Enum.member?(activity.data["to"], "https://www.w3.org/ns/activitystreams#Public") do
46 Pleroma.Web.Streamer.stream("public", activity)
47
48 if activity.local do
49 Pleroma.Web.Streamer.stream("public:local", activity)
50 end
51 end
52 end
53 end
54
55 def create(%{to: to, actor: actor, context: context, object: object} = params) do
56 additional = params[:additional] || %{}
57 # only accept false as false value
58 local = !(params[:local] == false)
59 published = params[:published]
60
61 with create_data <-
62 make_create_data(
63 %{to: to, actor: actor, published: published, context: context, object: object},
64 additional
65 ),
66 {:ok, activity} <- insert(create_data, local),
67 :ok <- maybe_federate(activity),
68 {:ok, _actor} <- User.increase_note_count(actor) do
69 {:ok, activity}
70 end
71 end
72
73 def accept(%{to: to, actor: actor, object: object} = params) do
74 # only accept false as false value
75 local = !(params[:local] == false)
76
77 with data <- %{"to" => to, "type" => "Accept", "actor" => actor, "object" => object},
78 {:ok, activity} <- insert(data, local),
79 :ok <- maybe_federate(activity) do
80 {:ok, activity}
81 end
82 end
83
84 def update(%{to: to, cc: cc, actor: actor, object: object} = params) do
85 # only accept false as false value
86 local = !(params[:local] == false)
87
88 with data <- %{
89 "to" => to,
90 "cc" => cc,
91 "type" => "Update",
92 "actor" => actor,
93 "object" => object
94 },
95 {:ok, activity} <- insert(data, local),
96 :ok <- maybe_federate(activity) do
97 {:ok, activity}
98 end
99 end
100
101 # TODO: This is weird, maybe we shouldn't check here if we can make the activity.
102 def like(
103 %User{ap_id: ap_id} = user,
104 %Object{data: %{"id" => _}} = object,
105 activity_id \\ nil,
106 local \\ true
107 ) do
108 with nil <- get_existing_like(ap_id, object),
109 like_data <- make_like_data(user, object, activity_id),
110 {:ok, activity} <- insert(like_data, local),
111 {:ok, object} <- add_like_to_object(activity, object),
112 :ok <- maybe_federate(activity) do
113 {:ok, activity, object}
114 else
115 %Activity{} = activity -> {:ok, activity, object}
116 error -> {:error, error}
117 end
118 end
119
120 def unlike(%User{} = actor, %Object{} = object) do
121 with %Activity{} = activity <- get_existing_like(actor.ap_id, object),
122 {:ok, _activity} <- Repo.delete(activity),
123 {:ok, object} <- remove_like_from_object(activity, object) do
124 {:ok, object}
125 else
126 _e -> {:ok, object}
127 end
128 end
129
130 def announce(
131 %User{ap_id: _} = user,
132 %Object{data: %{"id" => _}} = object,
133 activity_id \\ nil,
134 local \\ true
135 ) do
136 with true <- is_public?(object),
137 announce_data <- make_announce_data(user, object, activity_id),
138 {:ok, activity} <- insert(announce_data, local),
139 {:ok, object} <- add_announce_to_object(activity, object),
140 :ok <- maybe_federate(activity) do
141 {:ok, activity, object}
142 else
143 error -> {:error, error}
144 end
145 end
146
147 def follow(follower, followed, activity_id \\ nil, local \\ true) do
148 with data <- make_follow_data(follower, followed, activity_id),
149 {:ok, activity} <- insert(data, local),
150 :ok <- maybe_federate(activity) do
151 {:ok, activity}
152 end
153 end
154
155 def unfollow(follower, followed, local \\ true) do
156 with %Activity{} = follow_activity <- fetch_latest_follow(follower, followed),
157 unfollow_data <- make_unfollow_data(follower, followed, follow_activity),
158 {:ok, activity} <- insert(unfollow_data, local),
159 :ok,
160 maybe_federate(activity) do
161 {:ok, activity}
162 end
163 end
164
165 def delete(%Object{data: %{"id" => id, "actor" => actor}} = object, local \\ true) do
166 user = User.get_cached_by_ap_id(actor)
167
168 data = %{
169 "type" => "Delete",
170 "actor" => actor,
171 "object" => id,
172 "to" => [user.follower_address, "https://www.w3.org/ns/activitystreams#Public"]
173 }
174
175 with Repo.delete(object),
176 Repo.delete_all(Activity.all_non_create_by_object_ap_id_q(id)),
177 {:ok, activity} <- insert(data, local),
178 :ok <- maybe_federate(activity),
179 {:ok, _actor} <- User.decrease_note_count(user) do
180 {:ok, activity}
181 end
182 end
183
184 def fetch_activities_for_context(context, opts \\ %{}) do
185 public = ["https://www.w3.org/ns/activitystreams#Public"]
186
187 recipients =
188 if opts["user"], do: [opts["user"].ap_id | opts["user"].following] ++ public, else: public
189
190 query = from(activity in Activity)
191
192 query =
193 query
194 |> restrict_blocked(opts)
195 |> restrict_recipients(recipients, opts["user"])
196
197 query =
198 from(
199 activity in query,
200 where:
201 fragment(
202 "?->>'type' = ? and ?->>'context' = ?",
203 activity.data,
204 "Create",
205 activity.data,
206 ^context
207 ),
208 order_by: [desc: :id]
209 )
210
211 Repo.all(query)
212 end
213
214 def fetch_public_activities(opts \\ %{}) do
215 q = fetch_activities_query(["https://www.w3.org/ns/activitystreams#Public"], opts)
216
217 q
218 |> restrict_unlisted()
219 |> Repo.all()
220 |> Enum.reverse()
221 end
222
223 defp restrict_since(query, %{"since_id" => since_id}) do
224 from(activity in query, where: activity.id > ^since_id)
225 end
226
227 defp restrict_since(query, _), do: query
228
229 defp restrict_tag(query, %{"tag" => tag}) do
230 from(
231 activity in query,
232 where: fragment("? <@ (? #> '{\"object\",\"tag\"}')", ^tag, activity.data)
233 )
234 end
235
236 defp restrict_tag(query, _), do: query
237
238 defp restrict_recipients(query, [], _user), do: query
239
240 defp restrict_recipients(query, recipients, nil) do
241 from(activity in query, where: fragment("? && ?", ^recipients, activity.recipients))
242 end
243
244 defp restrict_recipients(query, recipients, user) do
245 from(
246 activity in query,
247 where: fragment("? && ?", ^recipients, activity.recipients),
248 or_where: activity.actor == ^user.ap_id
249 )
250 end
251
252 defp restrict_limit(query, %{"limit" => limit}) do
253 from(activity in query, limit: ^limit)
254 end
255
256 defp restrict_limit(query, _), do: query
257
258 defp restrict_local(query, %{"local_only" => true}) do
259 from(activity in query, where: activity.local == true)
260 end
261
262 defp restrict_local(query, _), do: query
263
264 defp restrict_max(query, %{"max_id" => max_id}) do
265 from(activity in query, where: activity.id < ^max_id)
266 end
267
268 defp restrict_max(query, _), do: query
269
270 defp restrict_actor(query, %{"actor_id" => actor_id}) do
271 from(activity in query, where: activity.actor == ^actor_id)
272 end
273
274 defp restrict_actor(query, _), do: query
275
276 defp restrict_type(query, %{"type" => type}) when is_binary(type) do
277 restrict_type(query, %{"type" => [type]})
278 end
279
280 defp restrict_type(query, %{"type" => type}) do
281 from(activity in query, where: fragment("?->>'type' = ANY(?)", activity.data, ^type))
282 end
283
284 defp restrict_type(query, _), do: query
285
286 defp restrict_favorited_by(query, %{"favorited_by" => ap_id}) do
287 from(
288 activity in query,
289 where: fragment("? <@ (? #> '{\"object\",\"likes\"}')", ^ap_id, activity.data)
290 )
291 end
292
293 defp restrict_favorited_by(query, _), do: query
294
295 defp restrict_media(query, %{"only_media" => val}) when val == "true" or val == "1" do
296 from(
297 activity in query,
298 where: fragment("not (? #> '{\"object\",\"attachment\"}' = ?)", activity.data, ^[])
299 )
300 end
301
302 defp restrict_media(query, _), do: query
303
304 # Only search through last 100_000 activities by default
305 defp restrict_recent(query, %{"whole_db" => true}), do: query
306
307 defp restrict_recent(query, _) do
308 since = (Repo.aggregate(Activity, :max, :id) || 0) - 100_000
309
310 from(activity in query, where: activity.id > ^since)
311 end
312
313 defp restrict_blocked(query, %{"blocking_user" => %User{info: info}}) do
314 blocks = info["blocks"] || []
315
316 from(
317 activity in query,
318 where: fragment("not (? = ANY(?))", activity.actor, ^blocks),
319 where: fragment("not (?->'to' \\?| ?)", activity.data, ^blocks)
320 )
321 end
322
323 defp restrict_blocked(query, _), do: query
324
325 defp restrict_unlisted(query) do
326 from(
327 activity in query,
328 where:
329 fragment(
330 "(?->'to' \\?| ?)",
331 activity.data,
332 ^["https://www.w3.org/ns/activitystreams#Public"]
333 )
334 )
335 end
336
337 def fetch_activities_query(recipients, opts \\ %{}) do
338 base_query =
339 from(
340 activity in Activity,
341 limit: 20,
342 order_by: [fragment("? desc nulls last", activity.id)]
343 )
344
345 base_query
346 |> restrict_recipients(recipients, opts["user"])
347 |> restrict_tag(opts)
348 |> restrict_since(opts)
349 |> restrict_local(opts)
350 |> restrict_limit(opts)
351 |> restrict_max(opts)
352 |> restrict_actor(opts)
353 |> restrict_type(opts)
354 |> restrict_favorited_by(opts)
355 |> restrict_recent(opts)
356 |> restrict_blocked(opts)
357 |> restrict_media(opts)
358 end
359
360 def fetch_activities(recipients, opts \\ %{}) do
361 fetch_activities_query(recipients, opts)
362 |> Repo.all()
363 |> Enum.reverse()
364 end
365
366 def upload(file) do
367 data = Upload.store(file)
368 Repo.insert(%Object{data: data})
369 end
370
371 def user_data_from_user_object(data) do
372 avatar =
373 data["icon"]["url"] &&
374 %{
375 "type" => "Image",
376 "url" => [%{"href" => data["icon"]["url"]}]
377 }
378
379 banner =
380 data["image"]["url"] &&
381 %{
382 "type" => "Image",
383 "url" => [%{"href" => data["image"]["url"]}]
384 }
385
386 user_data = %{
387 ap_id: data["id"],
388 info: %{
389 "ap_enabled" => true,
390 "source_data" => data,
391 "banner" => banner
392 },
393 avatar: avatar,
394 nickname: "#{data["preferredUsername"]}@#{URI.parse(data["id"]).host}",
395 name: data["name"],
396 follower_address: data["followers"],
397 bio: data["summary"]
398 }
399
400 {:ok, user_data}
401 end
402
403 def fetch_and_prepare_user_from_ap_id(ap_id) do
404 with {:ok, %{status_code: 200, body: body}} <-
405 @httpoison.get(ap_id, Accept: "application/activity+json"),
406 {:ok, data} <- Jason.decode(body) do
407 user_data_from_user_object(data)
408 else
409 e -> Logger.error("Could not decode user at fetch #{ap_id}, #{inspect(e)}")
410 end
411 end
412
413 def make_user_from_ap_id(ap_id) do
414 if _user = User.get_by_ap_id(ap_id) do
415 Transmogrifier.upgrade_user_from_ap_id(ap_id)
416 else
417 with {:ok, data} <- fetch_and_prepare_user_from_ap_id(ap_id) do
418 User.insert_or_update_user(data)
419 else
420 e -> {:error, e}
421 end
422 end
423 end
424
425 def make_user_from_nickname(nickname) do
426 with {:ok, %{"ap_id" => ap_id}} when not is_nil(ap_id) <- WebFinger.finger(nickname) do
427 make_user_from_ap_id(ap_id)
428 else
429 _e -> {:error, "No AP id in WebFinger"}
430 end
431 end
432
433 def publish(actor, activity) do
434 followers =
435 if actor.follower_address in activity.recipients do
436 {:ok, followers} = User.get_followers(actor)
437 followers |> Enum.filter(&(!&1.local))
438 else
439 []
440 end
441
442 remote_inboxes =
443 (Pleroma.Web.Salmon.remote_users(activity) ++ followers)
444 |> Enum.filter(fn user -> User.ap_enabled?(user) end)
445 |> Enum.map(fn %{info: %{"source_data" => data}} ->
446 (data["endpoints"] && data["endpoints"]["sharedInbox"]) || data["inbox"]
447 end)
448 |> Enum.uniq()
449
450 {:ok, data} = Transmogrifier.prepare_outgoing(activity.data)
451 json = Jason.encode!(data)
452
453 Enum.each(remote_inboxes, fn inbox ->
454 Federator.enqueue(:publish_single_ap, %{
455 inbox: inbox,
456 json: json,
457 actor: actor,
458 id: activity.data["id"]
459 })
460 end)
461 end
462
463 def publish_one(%{inbox: inbox, json: json, actor: actor, id: id}) do
464 Logger.info("Federating #{id} to #{inbox}")
465 host = URI.parse(inbox).host
466
467 signature =
468 Pleroma.Web.HTTPSignatures.sign(actor, %{host: host, "content-length": byte_size(json)})
469
470 @httpoison.post(
471 inbox,
472 json,
473 [{"Content-Type", "application/activity+json"}, {"signature", signature}],
474 hackney: [pool: :default]
475 )
476 end
477
478 # TODO:
479 # This will create a Create activity, which we need internally at the moment.
480 def fetch_object_from_id(id) do
481 if object = Object.get_cached_by_ap_id(id) do
482 {:ok, object}
483 else
484 Logger.info("Fetching #{id} via AP")
485
486 with true <- String.starts_with?(id, "http"),
487 {:ok, %{body: body, status_code: code}} when code in 200..299 <-
488 @httpoison.get(
489 id,
490 [Accept: "application/activity+json"],
491 follow_redirect: true,
492 timeout: 10000,
493 recv_timeout: 20000
494 ),
495 {:ok, data} <- Jason.decode(body),
496 nil <- Object.get_by_ap_id(data["id"]),
497 params <- %{
498 "type" => "Create",
499 "to" => data["to"],
500 "cc" => data["cc"],
501 "actor" => data["attributedTo"],
502 "object" => data
503 },
504 {:ok, activity} <- Transmogrifier.handle_incoming(params) do
505 {:ok, Object.get_by_ap_id(activity.data["object"]["id"])}
506 else
507 object = %Object{} ->
508 {:ok, object}
509
510 _e ->
511 Logger.info("Couldn't get object via AP, trying out OStatus fetching...")
512
513 case OStatus.fetch_activity_from_url(id) do
514 {:ok, [activity | _]} -> {:ok, Object.get_by_ap_id(activity.data["object"]["id"])}
515 e -> e
516 end
517 end
518 end
519 end
520
521 def is_public?(activity) do
522 "https://www.w3.org/ns/activitystreams#Public" in (activity.data["to"] ++
523 (activity.data["cc"] || []))
524 end
525
526 def visible_for_user?(activity, nil) do
527 is_public?(activity)
528 end
529
530 def visible_for_user?(activity, user) do
531 x = [user.ap_id | user.following]
532 y = activity.data["to"] ++ (activity.data["cc"] || [])
533 visible_for_user?(activity, nil) || Enum.any?(x, &(&1 in y))
534 end
535 end