Merge branch 'favicon_tag' 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) do
176 {:ok, activity}
177 end
178 end
179
180 def fetch_activities_for_context(context, opts \\ %{}) do
181 public = ["https://www.w3.org/ns/activitystreams#Public"]
182
183 recipients =
184 if opts["user"], do: [opts["user"].ap_id | opts["user"].following] ++ public, else: public
185
186 query = from(activity in Activity)
187
188 query =
189 query
190 |> restrict_blocked(opts)
191 |> restrict_recipients(recipients, opts["user"])
192
193 query =
194 from(
195 activity in query,
196 where:
197 fragment(
198 "?->>'type' = ? and ?->>'context' = ?",
199 activity.data,
200 "Create",
201 activity.data,
202 ^context
203 ),
204 order_by: [desc: :id]
205 )
206
207 Repo.all(query)
208 end
209
210 # TODO: Make this work properly with unlisted.
211 def fetch_public_activities(opts \\ %{}) do
212 q = fetch_activities_query(["https://www.w3.org/ns/activitystreams#Public"], opts)
213
214 q
215 |> Repo.all()
216 |> Enum.reverse()
217 end
218
219 defp restrict_since(query, %{"since_id" => since_id}) do
220 from(activity in query, where: activity.id > ^since_id)
221 end
222
223 defp restrict_since(query, _), do: query
224
225 defp restrict_tag(query, %{"tag" => tag}) do
226 from(
227 activity in query,
228 where: fragment("? <@ (? #> '{\"object\",\"tag\"}')", ^tag, activity.data)
229 )
230 end
231
232 defp restrict_tag(query, _), do: query
233
234 defp restrict_recipients(query, [], user), do: query
235
236 defp restrict_recipients(query, recipients, nil) do
237 from(activity in query, where: fragment("? && ?", ^recipients, activity.recipients))
238 end
239
240 defp restrict_recipients(query, recipients, user) do
241 from(
242 activity in query,
243 where: fragment("? && ?", ^recipients, activity.recipients),
244 or_where: activity.actor == ^user.ap_id
245 )
246 end
247
248 defp restrict_limit(query, %{"limit" => limit}) do
249 from(activity in query, limit: ^limit)
250 end
251
252 defp restrict_limit(query, _), do: query
253
254 defp restrict_local(query, %{"local_only" => true}) do
255 from(activity in query, where: activity.local == true)
256 end
257
258 defp restrict_local(query, _), do: query
259
260 defp restrict_max(query, %{"max_id" => max_id}) do
261 from(activity in query, where: activity.id < ^max_id)
262 end
263
264 defp restrict_max(query, _), do: query
265
266 defp restrict_actor(query, %{"actor_id" => actor_id}) do
267 from(activity in query, where: activity.actor == ^actor_id)
268 end
269
270 defp restrict_actor(query, _), do: query
271
272 defp restrict_type(query, %{"type" => type}) when is_binary(type) do
273 restrict_type(query, %{"type" => [type]})
274 end
275
276 defp restrict_type(query, %{"type" => type}) do
277 from(activity in query, where: fragment("?->>'type' = ANY(?)", activity.data, ^type))
278 end
279
280 defp restrict_type(query, _), do: query
281
282 defp restrict_favorited_by(query, %{"favorited_by" => ap_id}) do
283 from(
284 activity in query,
285 where: fragment("? <@ (? #> '{\"object\",\"likes\"}')", ^ap_id, activity.data)
286 )
287 end
288
289 defp restrict_favorited_by(query, _), do: query
290
291 defp restrict_media(query, %{"only_media" => val}) when val == "true" or val == "1" do
292 from(
293 activity in query,
294 where: fragment("not (? #> '{\"object\",\"attachment\"}' = ?)", activity.data, ^[])
295 )
296 end
297
298 defp restrict_media(query, _), do: query
299
300 # Only search through last 100_000 activities by default
301 defp restrict_recent(query, %{"whole_db" => true}), do: query
302
303 defp restrict_recent(query, _) do
304 since = (Repo.aggregate(Activity, :max, :id) || 0) - 100_000
305
306 from(activity in query, where: activity.id > ^since)
307 end
308
309 defp restrict_blocked(query, %{"blocking_user" => %User{info: info}}) do
310 blocks = info["blocks"] || []
311 from(activity in query, where: fragment("not (? = ANY(?))", activity.actor, ^blocks))
312 end
313
314 defp restrict_blocked(query, _), do: query
315
316 def fetch_activities_query(recipients, opts \\ %{}) do
317 base_query =
318 from(
319 activity in Activity,
320 limit: 20,
321 order_by: [fragment("? desc nulls last", activity.id)]
322 )
323
324 base_query
325 |> restrict_recipients(recipients, opts["user"])
326 |> restrict_tag(opts)
327 |> restrict_since(opts)
328 |> restrict_local(opts)
329 |> restrict_limit(opts)
330 |> restrict_max(opts)
331 |> restrict_actor(opts)
332 |> restrict_type(opts)
333 |> restrict_favorited_by(opts)
334 |> restrict_recent(opts)
335 |> restrict_blocked(opts)
336 |> restrict_media(opts)
337 end
338
339 def fetch_activities(recipients, opts \\ %{}) do
340 fetch_activities_query(recipients, opts)
341 |> Repo.all()
342 |> Enum.reverse()
343 end
344
345 def upload(file) do
346 data = Upload.store(file)
347 Repo.insert(%Object{data: data})
348 end
349
350 def user_data_from_user_object(data) do
351 avatar =
352 data["icon"]["url"] &&
353 %{
354 "type" => "Image",
355 "url" => [%{"href" => data["icon"]["url"]}]
356 }
357
358 banner =
359 data["image"]["url"] &&
360 %{
361 "type" => "Image",
362 "url" => [%{"href" => data["image"]["url"]}]
363 }
364
365 user_data = %{
366 ap_id: data["id"],
367 info: %{
368 "ap_enabled" => true,
369 "source_data" => data,
370 "banner" => banner
371 },
372 avatar: avatar,
373 nickname: "#{data["preferredUsername"]}@#{URI.parse(data["id"]).host}",
374 name: data["name"],
375 follower_address: data["followers"],
376 bio: data["summary"]
377 }
378
379 {:ok, user_data}
380 end
381
382 def fetch_and_prepare_user_from_ap_id(ap_id) do
383 with {:ok, %{status_code: 200, body: body}} <-
384 @httpoison.get(ap_id, Accept: "application/activity+json"),
385 {:ok, data} <- Jason.decode(body) do
386 user_data_from_user_object(data)
387 else
388 e -> Logger.error("Could not decode user at fetch #{ap_id}, #{inspect(e)}")
389 end
390 end
391
392 def make_user_from_ap_id(ap_id) do
393 if user = User.get_by_ap_id(ap_id) do
394 Transmogrifier.upgrade_user_from_ap_id(ap_id)
395 else
396 with {:ok, data} <- fetch_and_prepare_user_from_ap_id(ap_id) do
397 User.insert_or_update_user(data)
398 else
399 e -> {:error, e}
400 end
401 end
402 end
403
404 def make_user_from_nickname(nickname) do
405 with {:ok, %{"ap_id" => ap_id}} when not is_nil(ap_id) <- WebFinger.finger(nickname) do
406 make_user_from_ap_id(ap_id)
407 else
408 _e -> {:error, "No AP id in WebFinger"}
409 end
410 end
411
412 def publish(actor, activity) do
413 followers =
414 if actor.follower_address in activity.recipients do
415 {:ok, followers} = User.get_followers(actor)
416 followers |> Enum.filter(&(!&1.local))
417 else
418 []
419 end
420
421 remote_inboxes =
422 (Pleroma.Web.Salmon.remote_users(activity) ++ followers)
423 |> Enum.filter(fn user -> User.ap_enabled?(user) end)
424 |> Enum.map(fn %{info: %{"source_data" => data}} ->
425 (data["endpoints"] && data["endpoints"]["sharedInbox"]) || data["inbox"]
426 end)
427 |> Enum.uniq()
428
429 {:ok, data} = Transmogrifier.prepare_outgoing(activity.data)
430 json = Jason.encode!(data)
431
432 Enum.each(remote_inboxes, fn inbox ->
433 Federator.enqueue(:publish_single_ap, %{
434 inbox: inbox,
435 json: json,
436 actor: actor,
437 id: activity.data["id"]
438 })
439 end)
440 end
441
442 def publish_one(%{inbox: inbox, json: json, actor: actor, id: id}) do
443 Logger.info("Federating #{id} to #{inbox}")
444 host = URI.parse(inbox).host
445
446 signature =
447 Pleroma.Web.HTTPSignatures.sign(actor, %{host: host, "content-length": byte_size(json)})
448
449 @httpoison.post(
450 inbox,
451 json,
452 [{"Content-Type", "application/activity+json"}, {"signature", signature}],
453 hackney: [pool: :default]
454 )
455 end
456
457 # TODO:
458 # This will create a Create activity, which we need internally at the moment.
459 def fetch_object_from_id(id) do
460 if object = Object.get_cached_by_ap_id(id) do
461 {:ok, object}
462 else
463 Logger.info("Fetching #{id} via AP")
464
465 with true <- String.starts_with?(id, "http"),
466 {:ok, %{body: body, status_code: code}} when code in 200..299 <-
467 @httpoison.get(
468 id,
469 [Accept: "application/activity+json"],
470 follow_redirect: true,
471 timeout: 10000,
472 recv_timeout: 20000
473 ),
474 {:ok, data} <- Jason.decode(body),
475 nil <- Object.get_by_ap_id(data["id"]),
476 params <- %{
477 "type" => "Create",
478 "to" => data["to"],
479 "cc" => data["cc"],
480 "actor" => data["attributedTo"],
481 "object" => data
482 },
483 {:ok, activity} <- Transmogrifier.handle_incoming(params) do
484 {:ok, Object.get_by_ap_id(activity.data["object"]["id"])}
485 else
486 object = %Object{} ->
487 {:ok, object}
488
489 e ->
490 Logger.info("Couldn't get object via AP, trying out OStatus fetching...")
491
492 case OStatus.fetch_activity_from_url(id) do
493 {:ok, [activity | _]} -> {:ok, Object.get_by_ap_id(activity.data["object"]["id"])}
494 e -> e
495 end
496 end
497 end
498 end
499
500 def is_public?(activity) do
501 "https://www.w3.org/ns/activitystreams#Public" in (activity.data["to"] ++
502 (activity.data["cc"] || []))
503 end
504
505 def visible_for_user?(activity, nil) do
506 is_public?(activity)
507 end
508
509 def visible_for_user?(activity, user) do
510 x = [user.ap_id | user.following]
511 y = activity.data["to"] ++ (activity.data["cc"] || [])
512 visible_for_user?(activity, nil) || Enum.any?(x, &(&1 in y))
513 end
514 end