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