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