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