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