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