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