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