Formatting
[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
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 @rewrite_policy Keyword.get(@instance, :rewrite_policy)
15
16 def get_recipients(data) do
17 (data["to"] || []) ++ (data["cc"] || [])
18 end
19
20 def insert(map, local \\ true) when is_map(map) do
21 with nil <- Activity.get_by_ap_id(map["id"]),
22 map <- lazy_put_activity_defaults(map),
23 {:ok, map} <- @rewrite_policy.filter(map),
24 :ok <- insert_full_object(map) do
25 {:ok, activity} =
26 Repo.insert(%Activity{
27 data: map,
28 local: local,
29 actor: map["actor"],
30 recipients: get_recipients(map)
31 })
32
33 Notification.create_notifications(activity)
34 stream_out(activity)
35 {:ok, activity}
36 else
37 %Activity{} = activity -> {:ok, activity}
38 error -> {:error, error}
39 end
40 end
41
42 def stream_out(activity) do
43 public = "https://www.w3.org/ns/activitystreams#Public"
44
45 if activity.data["type"] in ["Create", "Announce"] do
46 Pleroma.Web.Streamer.stream("user", activity)
47
48 if Enum.member?(activity.data["to"], public) do
49 Pleroma.Web.Streamer.stream("public", activity)
50
51 if activity.local do
52 Pleroma.Web.Streamer.stream("public:local", activity)
53 end
54 else
55 if !Enum.member?(activity.data["cc"] || [], public) &&
56 !Enum.member?(
57 activity.data["to"],
58 User.get_by_ap_id(activity.data["actor"]).follower_address
59 ),
60 do: Pleroma.Web.Streamer.stream("direct", activity)
61 end
62 end
63 end
64
65 def create(%{to: to, actor: actor, context: context, object: object} = params) do
66 additional = params[:additional] || %{}
67 # only accept false as false value
68 local = !(params[:local] == false)
69 published = params[:published]
70
71 with create_data <-
72 make_create_data(
73 %{to: to, actor: actor, published: published, context: context, object: object},
74 additional
75 ),
76 {:ok, activity} <- insert(create_data, local),
77 :ok <- maybe_federate(activity),
78 {:ok, _actor} <- User.increase_note_count(actor) do
79 {:ok, activity}
80 end
81 end
82
83 def accept(%{to: to, actor: actor, object: object} = params) do
84 # only accept false as false value
85 local = !(params[:local] == false)
86
87 with data <- %{"to" => to, "type" => "Accept", "actor" => actor, "object" => object},
88 {:ok, activity} <- insert(data, local),
89 :ok <- maybe_federate(activity) do
90 {:ok, activity}
91 end
92 end
93
94 def update(%{to: to, cc: cc, actor: actor, object: object} = params) do
95 # only accept false as false value
96 local = !(params[:local] == false)
97
98 with data <- %{
99 "to" => to,
100 "cc" => cc,
101 "type" => "Update",
102 "actor" => actor,
103 "object" => object
104 },
105 {:ok, activity} <- insert(data, local),
106 :ok <- maybe_federate(activity) do
107 {:ok, activity}
108 end
109 end
110
111 # TODO: This is weird, maybe we shouldn't check here if we can make the activity.
112 def like(
113 %User{ap_id: ap_id} = user,
114 %Object{data: %{"id" => _}} = object,
115 activity_id \\ nil,
116 local \\ true
117 ) do
118 with nil <- get_existing_like(ap_id, object),
119 like_data <- make_like_data(user, object, activity_id),
120 {:ok, activity} <- insert(like_data, local),
121 {:ok, object} <- add_like_to_object(activity, object),
122 :ok <- maybe_federate(activity) do
123 {:ok, activity, object}
124 else
125 %Activity{} = activity -> {:ok, activity, object}
126 error -> {:error, error}
127 end
128 end
129
130 def unlike(%User{} = actor, %Object{} = object) do
131 with %Activity{} = activity <- get_existing_like(actor.ap_id, object),
132 {:ok, _activity} <- Repo.delete(activity),
133 {:ok, object} <- remove_like_from_object(activity, object) do
134 {:ok, object}
135 else
136 _e -> {:ok, object}
137 end
138 end
139
140 def announce(
141 %User{ap_id: _} = user,
142 %Object{data: %{"id" => _}} = object,
143 activity_id \\ nil,
144 local \\ true
145 ) do
146 with true <- is_public?(object),
147 announce_data <- make_announce_data(user, object, activity_id),
148 {:ok, activity} <- insert(announce_data, local),
149 {:ok, object} <- add_announce_to_object(activity, object),
150 :ok <- maybe_federate(activity) do
151 {:ok, activity, object}
152 else
153 error -> {:error, error}
154 end
155 end
156
157 def follow(follower, followed, activity_id \\ nil, local \\ true) do
158 with data <- make_follow_data(follower, followed, activity_id),
159 {:ok, activity} <- insert(data, local),
160 :ok <- maybe_federate(activity) do
161 {:ok, activity}
162 end
163 end
164
165 def unfollow(follower, followed, local \\ true) do
166 with %Activity{} = follow_activity <- fetch_latest_follow(follower, followed),
167 unfollow_data <- make_unfollow_data(follower, followed, follow_activity),
168 {:ok, activity} <- insert(unfollow_data, local),
169 :ok,
170 maybe_federate(activity) do
171 {:ok, activity}
172 end
173 end
174
175 def delete(%Object{data: %{"id" => id, "actor" => actor}} = object, local \\ true) do
176 user = User.get_cached_by_ap_id(actor)
177
178 data = %{
179 "type" => "Delete",
180 "actor" => actor,
181 "object" => id,
182 "to" => [user.follower_address, "https://www.w3.org/ns/activitystreams#Public"]
183 }
184
185 with Repo.delete(object),
186 Repo.delete_all(Activity.all_non_create_by_object_ap_id_q(id)),
187 {:ok, activity} <- insert(data, local),
188 :ok <- maybe_federate(activity),
189 {:ok, _actor} <- User.decrease_note_count(user) do
190 {:ok, activity}
191 end
192 end
193
194 def fetch_activities_for_context(context, opts \\ %{}) do
195 public = ["https://www.w3.org/ns/activitystreams#Public"]
196
197 recipients =
198 if opts["user"], do: [opts["user"].ap_id | opts["user"].following] ++ public, else: public
199
200 query = from(activity in Activity)
201
202 query =
203 query
204 |> restrict_blocked(opts)
205 |> restrict_recipients(recipients, opts["user"])
206
207 query =
208 from(
209 activity in query,
210 where:
211 fragment(
212 "?->>'type' = ? and ?->>'context' = ?",
213 activity.data,
214 "Create",
215 activity.data,
216 ^context
217 ),
218 order_by: [desc: :id]
219 )
220
221 Repo.all(query)
222 end
223
224 # TODO: Make this work properly with unlisted.
225 def fetch_public_activities(opts \\ %{}) do
226 q = fetch_activities_query(["https://www.w3.org/ns/activitystreams#Public"], opts)
227
228 q
229 |> Repo.all()
230 |> Enum.reverse()
231 end
232
233 @valid_visibilities ~w[direct unlisted public private]
234
235 defp restrict_visibility(query, %{visibility: "direct"}) do
236 public = "https://www.w3.org/ns/activitystreams#Public"
237
238 from(
239 activity in query,
240 join: sender in User,
241 on: sender.ap_id == activity.actor,
242 where:
243 fragment("not data->'to' \\? ?", ^public) and fragment("not data->'cc' \\? ?", ^public) and
244 fragment("not data->'to' \\? ?", sender.follower_address)
245 )
246 end
247
248 defp restrict_visibility(_query, %{visibility: visibility})
249 when visibility not in @valid_visibilities do
250 Logger.error("Could not restrict visibility to #{visibility}")
251 end
252
253 defp restrict_visibility(query, _visibility), do: query
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 def fetch_activities_query(recipients, opts \\ %{}) do
358 base_query =
359 from(
360 activity in Activity,
361 limit: 20,
362 order_by: [fragment("? desc nulls last", activity.id)]
363 )
364
365 base_query
366 |> restrict_recipients(recipients, opts["user"])
367 |> restrict_tag(opts)
368 |> restrict_since(opts)
369 |> restrict_local(opts)
370 |> restrict_limit(opts)
371 |> restrict_max(opts)
372 |> restrict_actor(opts)
373 |> restrict_type(opts)
374 |> restrict_favorited_by(opts)
375 |> restrict_recent(opts)
376 |> restrict_blocked(opts)
377 |> restrict_media(opts)
378 |> restrict_visibility(opts)
379 end
380
381 def fetch_activities(recipients, opts \\ %{}) do
382 fetch_activities_query(recipients, opts)
383 |> Repo.all()
384 |> Enum.reverse()
385 end
386
387 def upload(file) do
388 data = Upload.store(file)
389 Repo.insert(%Object{data: data})
390 end
391
392 def user_data_from_user_object(data) do
393 avatar =
394 data["icon"]["url"] &&
395 %{
396 "type" => "Image",
397 "url" => [%{"href" => data["icon"]["url"]}]
398 }
399
400 banner =
401 data["image"]["url"] &&
402 %{
403 "type" => "Image",
404 "url" => [%{"href" => data["image"]["url"]}]
405 }
406
407 user_data = %{
408 ap_id: data["id"],
409 info: %{
410 "ap_enabled" => true,
411 "source_data" => data,
412 "banner" => banner
413 },
414 avatar: avatar,
415 nickname: "#{data["preferredUsername"]}@#{URI.parse(data["id"]).host}",
416 name: data["name"],
417 follower_address: data["followers"],
418 bio: data["summary"]
419 }
420
421 {:ok, user_data}
422 end
423
424 def fetch_and_prepare_user_from_ap_id(ap_id) do
425 with {:ok, %{status_code: 200, body: body}} <-
426 @httpoison.get(ap_id, Accept: "application/activity+json"),
427 {:ok, data} <- Jason.decode(body) do
428 user_data_from_user_object(data)
429 else
430 e -> Logger.error("Could not decode user at fetch #{ap_id}, #{inspect(e)}")
431 end
432 end
433
434 def make_user_from_ap_id(ap_id) do
435 if _user = User.get_by_ap_id(ap_id) do
436 Transmogrifier.upgrade_user_from_ap_id(ap_id)
437 else
438 with {:ok, data} <- fetch_and_prepare_user_from_ap_id(ap_id) do
439 User.insert_or_update_user(data)
440 else
441 e -> {:error, e}
442 end
443 end
444 end
445
446 def make_user_from_nickname(nickname) do
447 with {:ok, %{"ap_id" => ap_id}} when not is_nil(ap_id) <- WebFinger.finger(nickname) do
448 make_user_from_ap_id(ap_id)
449 else
450 _e -> {:error, "No AP id in WebFinger"}
451 end
452 end
453
454 def publish(actor, activity) do
455 followers =
456 if actor.follower_address in activity.recipients do
457 {:ok, followers} = User.get_followers(actor)
458 followers |> Enum.filter(&(!&1.local))
459 else
460 []
461 end
462
463 remote_inboxes =
464 (Pleroma.Web.Salmon.remote_users(activity) ++ followers)
465 |> Enum.filter(fn user -> User.ap_enabled?(user) end)
466 |> Enum.map(fn %{info: %{"source_data" => data}} ->
467 (data["endpoints"] && data["endpoints"]["sharedInbox"]) || data["inbox"]
468 end)
469 |> Enum.uniq()
470
471 {:ok, data} = Transmogrifier.prepare_outgoing(activity.data)
472 json = Jason.encode!(data)
473
474 Enum.each(remote_inboxes, fn inbox ->
475 Federator.enqueue(:publish_single_ap, %{
476 inbox: inbox,
477 json: json,
478 actor: actor,
479 id: activity.data["id"]
480 })
481 end)
482 end
483
484 def publish_one(%{inbox: inbox, json: json, actor: actor, id: id}) do
485 Logger.info("Federating #{id} to #{inbox}")
486 host = URI.parse(inbox).host
487
488 signature =
489 Pleroma.Web.HTTPSignatures.sign(actor, %{host: host, "content-length": byte_size(json)})
490
491 @httpoison.post(
492 inbox,
493 json,
494 [{"Content-Type", "application/activity+json"}, {"signature", signature}],
495 hackney: [pool: :default]
496 )
497 end
498
499 # TODO:
500 # This will create a Create activity, which we need internally at the moment.
501 def fetch_object_from_id(id) do
502 if object = Object.get_cached_by_ap_id(id) do
503 {:ok, object}
504 else
505 Logger.info("Fetching #{id} via AP")
506
507 with true <- String.starts_with?(id, "http"),
508 {:ok, %{body: body, status_code: code}} when code in 200..299 <-
509 @httpoison.get(
510 id,
511 [Accept: "application/activity+json"],
512 follow_redirect: true,
513 timeout: 10000,
514 recv_timeout: 20000
515 ),
516 {:ok, data} <- Jason.decode(body),
517 nil <- Object.get_by_ap_id(data["id"]),
518 params <- %{
519 "type" => "Create",
520 "to" => data["to"],
521 "cc" => data["cc"],
522 "actor" => data["attributedTo"],
523 "object" => data
524 },
525 {:ok, activity} <- Transmogrifier.handle_incoming(params) do
526 {:ok, Object.get_by_ap_id(activity.data["object"]["id"])}
527 else
528 object = %Object{} ->
529 {:ok, object}
530
531 _e ->
532 Logger.info("Couldn't get object via AP, trying out OStatus fetching...")
533
534 case OStatus.fetch_activity_from_url(id) do
535 {:ok, [activity | _]} -> {:ok, Object.get_by_ap_id(activity.data["object"]["id"])}
536 e -> e
537 end
538 end
539 end
540 end
541
542 def is_public?(activity) do
543 "https://www.w3.org/ns/activitystreams#Public" in (activity.data["to"] ++
544 (activity.data["cc"] || []))
545 end
546
547 def visible_for_user?(activity, nil) do
548 is_public?(activity)
549 end
550
551 def visible_for_user?(activity, user) do
552 x = [user.ap_id | user.following]
553 y = activity.data["to"] ++ (activity.data["cc"] || [])
554 visible_for_user?(activity, nil) || Enum.any?(x, &(&1 in y))
555 end
556 end