Get avatar and banner from AP users.
[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} = Repo.insert(%Activity{data: map, local: local, actor: map["actor"], recipients: get_recipients(map)})
22 Notification.create_notifications(activity)
23 stream_out(activity)
24 {:ok, activity}
25 else
26 %Activity{} = activity -> {:ok, activity}
27 error -> {:error, error}
28 end
29 end
30
31 def stream_out(activity) do
32 if activity.data["type"] in ["Create", "Announce"] do
33 Pleroma.Web.Streamer.stream("user", activity)
34 if Enum.member?(activity.data["to"], "https://www.w3.org/ns/activitystreams#Public") do
35 Pleroma.Web.Streamer.stream("public", activity)
36 if activity.local do
37 Pleroma.Web.Streamer.stream("public:local", activity)
38 end
39 end
40 end
41 end
42
43 def create(%{to: to, actor: actor, context: context, object: object} = params) do
44 additional = params[:additional] || %{}
45 local = !(params[:local] == false) # only accept false as false value
46 published = params[:published]
47
48 with create_data <- make_create_data(%{to: to, actor: actor, published: published, context: context, object: object}, additional),
49 {:ok, activity} <- insert(create_data, local),
50 :ok <- maybe_federate(activity) do
51 {:ok, activity}
52 end
53 end
54
55 def accept(%{to: to, actor: actor, object: object} = params) do
56 local = !(params[:local] == false) # only accept false as false value
57
58 with data <- %{"to" => to, "type" => "Accept", "actor" => actor, "object" => object},
59 {:ok, activity} <- insert(data, local),
60 :ok <- maybe_federate(activity) do
61 {:ok, activity}
62 end
63 end
64
65 # TODO: This is weird, maybe we shouldn't check here if we can make the activity.
66 def like(%User{ap_id: ap_id} = user, %Object{data: %{"id" => _}} = object, activity_id \\ nil, local \\ true) do
67 with nil <- get_existing_like(ap_id, object),
68 like_data <- make_like_data(user, object, activity_id),
69 {:ok, activity} <- insert(like_data, local),
70 {:ok, object} <- add_like_to_object(activity, object),
71 :ok <- maybe_federate(activity) do
72 {:ok, activity, object}
73 else
74 %Activity{} = activity -> {:ok, activity, object}
75 error -> {:error, error}
76 end
77 end
78
79 def unlike(%User{} = actor, %Object{} = object) do
80 with %Activity{} = activity <- get_existing_like(actor.ap_id, object),
81 {:ok, _activity} <- Repo.delete(activity),
82 {:ok, object} <- remove_like_from_object(activity, object) do
83 {:ok, object}
84 else _e -> {:ok, object}
85 end
86 end
87
88 def announce(%User{ap_id: _} = user, %Object{data: %{"id" => _}} = object, activity_id \\ nil, local \\ true) do
89 with true <- is_public?(object),
90 announce_data <- make_announce_data(user, object, activity_id),
91 {:ok, activity} <- insert(announce_data, local),
92 {:ok, object} <- add_announce_to_object(activity, object),
93 :ok <- maybe_federate(activity) do
94 {:ok, activity, object}
95 else
96 error -> {:error, error}
97 end
98 end
99
100 def follow(follower, followed, activity_id \\ nil, local \\ true) do
101 with data <- make_follow_data(follower, followed, activity_id),
102 {:ok, activity} <- insert(data, local),
103 :ok <- maybe_federate(activity) do
104 {:ok, activity}
105 end
106 end
107
108 def unfollow(follower, followed, local \\ true) do
109 with %Activity{} = follow_activity <- fetch_latest_follow(follower, followed),
110 unfollow_data <- make_unfollow_data(follower, followed, follow_activity),
111 {:ok, activity} <- insert(unfollow_data, local),
112 :ok, maybe_federate(activity) do
113 {:ok, activity}
114 end
115 end
116
117 def delete(%Object{data: %{"id" => id, "actor" => actor}} = object, local \\ true) do
118 user = User.get_cached_by_ap_id(actor)
119 data = %{
120 "type" => "Delete",
121 "actor" => actor,
122 "object" => id,
123 "to" => [user.follower_address, "https://www.w3.org/ns/activitystreams#Public"]
124 }
125 with Repo.delete(object),
126 Repo.delete_all(Activity.all_non_create_by_object_ap_id_q(id)),
127 {:ok, activity} <- insert(data, local),
128 :ok <- maybe_federate(activity) do
129 {:ok, activity}
130 end
131 end
132
133 def fetch_activities_for_context(context, opts \\ %{}) do
134 public = ["https://www.w3.org/ns/activitystreams#Public"]
135 recipients = if opts["user"], do: [opts["user"].ap_id | opts["user"].following] ++ public, else: public
136
137 query = from activity in Activity
138 query = query
139 |> restrict_blocked(opts)
140 |> restrict_recipients(recipients, opts["user"])
141
142 query = from activity in query,
143 where: fragment("?->>'type' = ? and ?->>'context' = ?", activity.data, "Create", activity.data, ^context),
144 order_by: [desc: :id]
145 Repo.all(query)
146 end
147
148 def fetch_public_activities(opts \\ %{}) do
149 public = %{to: ["https://www.w3.org/ns/activitystreams#Public"]}
150 q = fetch_activities_query([], opts)
151 q = from activity in q,
152 where: fragment(~s(? @> ?), activity.data, ^public)
153 q
154 |> Repo.all
155 |> Enum.reverse
156 end
157
158 defp restrict_since(query, %{"since_id" => since_id}) do
159 from activity in query, where: activity.id > ^since_id
160 end
161 defp restrict_since(query, _), do: query
162
163 defp restrict_tag(query, %{"tag" => tag}) do
164 from activity in query,
165 where: fragment("? <@ (? #> '{\"object\",\"tag\"}')", ^tag, activity.data)
166 end
167 defp restrict_tag(query, _), do: query
168
169 defp restrict_recipients(query, [], user), do: query
170 defp restrict_recipients(query, recipients, nil) do
171 from activity in query,
172 where: fragment("? && ?", ^recipients, activity.recipients)
173 end
174 defp restrict_recipients(query, recipients, user) do
175 from activity in query,
176 where: fragment("? && ?", ^recipients, activity.recipients),
177 or_where: activity.actor == ^user.ap_id
178 end
179
180 defp restrict_local(query, %{"local_only" => true}) do
181 from activity in query, where: activity.local == true
182 end
183 defp restrict_local(query, _), do: query
184
185 defp restrict_max(query, %{"max_id" => max_id}) do
186 from activity in query, where: activity.id < ^max_id
187 end
188 defp restrict_max(query, _), do: query
189
190 defp restrict_actor(query, %{"actor_id" => actor_id}) do
191 from activity in query,
192 where: activity.actor == ^actor_id
193 end
194 defp restrict_actor(query, _), do: query
195
196 defp restrict_type(query, %{"type" => type}) when is_binary(type) do
197 restrict_type(query, %{"type" => [type]})
198 end
199 defp restrict_type(query, %{"type" => type}) do
200 from activity in query,
201 where: fragment("?->>'type' = ANY(?)", activity.data, ^type)
202 end
203 defp restrict_type(query, _), do: query
204
205 defp restrict_favorited_by(query, %{"favorited_by" => ap_id}) do
206 from activity in query,
207 where: fragment("? <@ (? #> '{\"object\",\"likes\"}')", ^ap_id, activity.data)
208 end
209 defp restrict_favorited_by(query, _), do: query
210
211 defp restrict_media(query, %{"only_media" => val}) when val == "true" or val == "1" do
212 from activity in query,
213 where: fragment("not (? #> '{\"object\",\"attachment\"}' = ?)", activity.data, ^[])
214 end
215 defp restrict_media(query, _), do: query
216
217 # Only search through last 100_000 activities by default
218 defp restrict_recent(query, %{"whole_db" => true}), do: query
219 defp restrict_recent(query, _) do
220 since = (Repo.aggregate(Activity, :max, :id) || 0) - 100_000
221
222 from activity in query,
223 where: activity.id > ^since
224 end
225
226 defp restrict_blocked(query, %{"blocking_user" => %User{info: info}}) do
227 blocks = info["blocks"] || []
228 from activity in query,
229 where: fragment("not (? = ANY(?))", activity.actor, ^blocks)
230 end
231 defp restrict_blocked(query, _), do: query
232
233 def fetch_activities_query(recipients, opts \\ %{}) do
234 base_query = from activity in Activity,
235 limit: 20,
236 order_by: [fragment("? desc nulls last", activity.id)]
237
238 base_query
239 |> restrict_recipients(recipients, opts["user"])
240 |> restrict_tag(opts)
241 |> restrict_since(opts)
242 |> restrict_local(opts)
243 |> restrict_max(opts)
244 |> restrict_actor(opts)
245 |> restrict_type(opts)
246 |> restrict_favorited_by(opts)
247 |> restrict_recent(opts)
248 |> restrict_blocked(opts)
249 |> restrict_media(opts)
250 end
251
252 def fetch_activities(recipients, opts \\ %{}) do
253 fetch_activities_query(recipients, opts)
254 |> Repo.all
255 |> Enum.reverse
256 end
257
258 def upload(file) do
259 data = Upload.store(file)
260 Repo.insert(%Object{data: data})
261 end
262
263 def fetch_and_prepare_user_from_ap_id(ap_id) do
264 with {:ok, %{status_code: 200, body: body}} <- @httpoison.get(ap_id, ["Accept": "application/activity+json"]),
265 {:ok, data} <- Poison.decode(body)
266 do
267 avatar = %{
268 "type" => "Image",
269 "url" => [%{"href" => data["icon"]["url"]}]
270 }
271
272 banner = %{
273 "type" => "Image",
274 "url" => [%{"href" => data["image"]["url"]}]
275 }
276
277 user_data = %{
278 ap_id: data["id"],
279 info: %{
280 "ap_enabled" => true,
281 "source_data" => data,
282 "banner" => banner
283 },
284 avatar: avatar,
285 nickname: "#{data["preferredUsername"]}@#{URI.parse(ap_id).host}",
286 name: data["name"],
287 follower_address: data["followers"],
288 }
289
290 {:ok, user_data}
291 end
292 end
293
294 def make_user_from_ap_id(ap_id) do
295 if user = User.get_by_ap_id(ap_id) do
296 Transmogrifier.upgrade_user_from_ap_id(ap_id)
297 else
298 with {:ok, data} <- fetch_and_prepare_user_from_ap_id(ap_id) do
299 User.insert_or_update_user(data)
300 else
301 e -> e
302 end
303 end
304 end
305
306 def make_user_from_nickname(nickname) do
307 with {:ok, %{"ap_id" => ap_id}} when not is_nil(ap_id) <- WebFinger.finger(nickname) do
308 make_user_from_ap_id(ap_id)
309 end
310 end
311
312 def publish(actor, activity) do
313 followers = if actor.follower_address in activity.recipients do
314 {:ok, followers} = User.get_followers(actor)
315 followers
316 else
317 []
318 end
319
320 remote_inboxes = (Pleroma.Web.Salmon.remote_users(activity) ++ followers)
321 |> Enum.filter(fn (user) -> User.ap_enabled?(user) end)
322 |> Enum.map(fn (%{info: %{"source_data" => data}}) ->
323 (data["endpoints"] && data["endpoints"]["sharedInbox"]) || data["inbox"]
324 end)
325 |> Enum.uniq
326
327 {:ok, data} = Transmogrifier.prepare_outgoing(activity.data)
328 json = Poison.encode!(data)
329 Enum.each remote_inboxes, fn(inbox) ->
330 Federator.enqueue(:publish_single_ap, %{inbox: inbox, json: json, actor: actor, id: activity.data["id"]})
331 end
332 end
333
334 def publish_one(%{inbox: inbox, json: json, actor: actor, id: id}) do
335 Logger.info("Federating #{id} to #{inbox}")
336 host = URI.parse(inbox).host
337 signature = Pleroma.Web.HTTPSignatures.sign(actor, %{host: host, "content-length": byte_size(json)})
338 @httpoison.post(inbox, json, [{"Content-Type", "application/activity+json"}, {"signature", signature}])
339 end
340
341 # TODO:
342 # This will create a Create activity, which we need internally at the moment.
343 def fetch_object_from_id(id) do
344 if object = Object.get_cached_by_ap_id(id) do
345 {:ok, object}
346 else
347 Logger.info("Fetching #{id} via AP")
348 with {:ok, %{body: body, status_code: code}} when code in 200..299 <- @httpoison.get(id, [Accept: "application/activity+json"], follow_redirect: true, timeout: 10000, recv_timeout: 20000),
349 {:ok, data} <- Poison.decode(body),
350 nil <- Object.get_by_ap_id(data["id"]),
351 params <- %{"type" => "Create", "to" => data["to"], "cc" => data["cc"], "actor" => data["attributedTo"], "object" => data},
352 {:ok, activity} <- Transmogrifier.handle_incoming(params) do
353 {:ok, Object.get_by_ap_id(activity.data["object"]["id"])}
354 else
355 object = %Object{} -> {:ok, object}
356 e ->
357 Logger.info("Couldn't get object via AP, trying out OStatus fetching...")
358 case OStatus.fetch_activity_from_url(id) do
359 {:ok, [activity | _]} -> {:ok, Object.get_by_ap_id(activity.data["object"]["id"])}
360 _ -> e
361 end
362 end
363 end
364 end
365
366 def is_public?(activity) do
367 "https://www.w3.org/ns/activitystreams#Public" in (activity.data["to"] ++ (activity.data["cc"] || []))
368 end
369
370 def visible_for_user?(activity, nil) do
371 is_public?(activity)
372 end
373 def visible_for_user?(activity, user) do
374 x = [user.ap_id | user.following]
375 y = (activity.data["to"] ++ (activity.data["cc"] || []))
376 visible_for_user?(activity, nil) || Enum.any?(x, &(&1 in y))
377 end
378 end