Merge branch 'fix/docs-dry-run' into 'develop'
[akkoma] / lib / pleroma / web / common_api / common_api.ex
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2019 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
4
5 defmodule Pleroma.Web.CommonAPI do
6 alias Pleroma.Activity
7 alias Pleroma.Bookmark
8 alias Pleroma.Formatter
9 alias Pleroma.Object
10 alias Pleroma.ThreadMute
11 alias Pleroma.User
12 alias Pleroma.Web.ActivityPub.ActivityPub
13 alias Pleroma.Web.ActivityPub.Utils
14 alias Pleroma.Web.ActivityPub.Visibility
15
16 import Pleroma.Web.CommonAPI.Utils
17
18 def follow(follower, followed) do
19 with {:ok, follower} <- User.maybe_direct_follow(follower, followed),
20 {:ok, activity} <- ActivityPub.follow(follower, followed),
21 {:ok, follower, followed} <-
22 User.wait_and_refresh(
23 Pleroma.Config.get([:activitypub, :follow_handshake_timeout]),
24 follower,
25 followed
26 ) do
27 {:ok, follower, followed, activity}
28 end
29 end
30
31 def unfollow(follower, unfollowed) do
32 with {:ok, follower, _follow_activity} <- User.unfollow(follower, unfollowed),
33 {:ok, _activity} <- ActivityPub.unfollow(follower, unfollowed) do
34 {:ok, follower}
35 end
36 end
37
38 def accept_follow_request(follower, followed) do
39 with {:ok, follower} <- User.follow(follower, followed),
40 %Activity{} = follow_activity <- Utils.fetch_latest_follow(follower, followed),
41 {:ok, follow_activity} <- Utils.update_follow_state_for_all(follow_activity, "accept"),
42 {:ok, _activity} <-
43 ActivityPub.accept(%{
44 to: [follower.ap_id],
45 actor: followed,
46 object: follow_activity.data["id"],
47 type: "Accept"
48 }) do
49 {:ok, follower}
50 end
51 end
52
53 def reject_follow_request(follower, followed) do
54 with %Activity{} = follow_activity <- Utils.fetch_latest_follow(follower, followed),
55 {:ok, follow_activity} <- Utils.update_follow_state_for_all(follow_activity, "reject"),
56 {:ok, _activity} <-
57 ActivityPub.reject(%{
58 to: [follower.ap_id],
59 actor: followed,
60 object: follow_activity.data["id"],
61 type: "Reject"
62 }) do
63 {:ok, follower}
64 end
65 end
66
67 def delete(activity_id, user) do
68 with %Activity{data: %{"object" => _}} = activity <-
69 Activity.get_by_id_with_object(activity_id),
70 %Object{} = object <- Object.normalize(activity),
71 true <- User.superuser?(user) || user.ap_id == object.data["actor"],
72 {:ok, _} <- unpin(activity_id, user),
73 {:ok, delete} <- ActivityPub.delete(object) do
74 {:ok, delete}
75 else
76 _ ->
77 {:error, "Could not delete"}
78 end
79 end
80
81 def repeat(id_or_ap_id, user) do
82 with %Activity{} = activity <- get_by_id_or_ap_id(id_or_ap_id),
83 object <- Object.normalize(activity),
84 nil <- Utils.get_existing_announce(user.ap_id, object) do
85 ActivityPub.announce(user, object)
86 else
87 _ ->
88 {:error, "Could not repeat"}
89 end
90 end
91
92 def unrepeat(id_or_ap_id, user) do
93 with %Activity{} = activity <- get_by_id_or_ap_id(id_or_ap_id),
94 object <- Object.normalize(activity) do
95 ActivityPub.unannounce(user, object)
96 else
97 _ ->
98 {:error, "Could not unrepeat"}
99 end
100 end
101
102 def favorite(id_or_ap_id, user) do
103 with %Activity{} = activity <- get_by_id_or_ap_id(id_or_ap_id),
104 object <- Object.normalize(activity),
105 nil <- Utils.get_existing_like(user.ap_id, object) do
106 ActivityPub.like(user, object)
107 else
108 _ ->
109 {:error, "Could not favorite"}
110 end
111 end
112
113 def unfavorite(id_or_ap_id, user) do
114 with %Activity{} = activity <- get_by_id_or_ap_id(id_or_ap_id),
115 object <- Object.normalize(activity) do
116 ActivityPub.unlike(user, object)
117 else
118 _ ->
119 {:error, "Could not unfavorite"}
120 end
121 end
122
123 def vote(user, object, choices) do
124 with "Question" <- object.data["type"],
125 {:author, false} <- {:author, object.data["actor"] == user.ap_id},
126 {:existing_votes, []} <- {:existing_votes, Utils.get_existing_votes(user.ap_id, object)},
127 {options, max_count} <- get_options_and_max_count(object),
128 option_count <- Enum.count(options),
129 {:choice_check, {choices, true}} <-
130 {:choice_check, normalize_and_validate_choice_indices(choices, option_count)},
131 {:count_check, true} <- {:count_check, Enum.count(choices) <= max_count} do
132 answer_activities =
133 Enum.map(choices, fn index ->
134 answer_data = make_answer_data(user, object, Enum.at(options, index)["name"])
135
136 {:ok, activity} =
137 ActivityPub.create(%{
138 to: answer_data["to"],
139 actor: user,
140 context: object.data["context"],
141 object: answer_data,
142 additional: %{"cc" => answer_data["cc"]}
143 })
144
145 activity
146 end)
147
148 object = Object.get_cached_by_ap_id(object.data["id"])
149 {:ok, answer_activities, object}
150 else
151 {:author, _} -> {:error, "Poll's author can't vote"}
152 {:existing_votes, _} -> {:error, "Already voted"}
153 {:choice_check, {_, false}} -> {:error, "Invalid indices"}
154 {:count_check, false} -> {:error, "Too many choices"}
155 end
156 end
157
158 defp get_options_and_max_count(object) do
159 if Map.has_key?(object.data, "anyOf") do
160 {object.data["anyOf"], Enum.count(object.data["anyOf"])}
161 else
162 {object.data["oneOf"], 1}
163 end
164 end
165
166 defp normalize_and_validate_choice_indices(choices, count) do
167 Enum.map_reduce(choices, true, fn index, valid ->
168 index = if is_binary(index), do: String.to_integer(index), else: index
169 {index, if(valid, do: index < count, else: valid)}
170 end)
171 end
172
173 def get_visibility(%{"visibility" => visibility}, in_reply_to)
174 when visibility in ~w{public unlisted private direct},
175 do: {visibility, get_replied_to_visibility(in_reply_to)}
176
177 def get_visibility(_, in_reply_to) when not is_nil(in_reply_to) do
178 visibility = get_replied_to_visibility(in_reply_to)
179 {visibility, visibility}
180 end
181
182 def get_visibility(_, in_reply_to), do: {"public", get_replied_to_visibility(in_reply_to)}
183
184 def get_replied_to_visibility(nil), do: nil
185
186 def get_replied_to_visibility(activity) do
187 with %Object{} = object <- Object.normalize(activity) do
188 Pleroma.Web.ActivityPub.Visibility.get_visibility(object)
189 end
190 end
191
192 def post(user, %{"status" => status} = data) do
193 limit = Pleroma.Config.get([:instance, :limit])
194
195 with status <- String.trim(status),
196 attachments <- attachments_from_ids(data),
197 in_reply_to <- get_replied_to_activity(data["in_reply_to_status_id"]),
198 {visibility, in_reply_to_visibility} <- get_visibility(data, in_reply_to),
199 {_, false} <-
200 {:private_to_public, in_reply_to_visibility == "direct" && visibility != "direct"},
201 {content_html, mentions, tags} <-
202 make_content_html(
203 status,
204 attachments,
205 data,
206 visibility
207 ),
208 mentioned_users <- for({_, mentioned_user} <- mentions, do: mentioned_user.ap_id),
209 addressed_users <- get_addressed_users(mentioned_users, data["to"]),
210 {poll, poll_emoji} <- make_poll_data(data),
211 {to, cc} <- get_to_and_cc(user, addressed_users, in_reply_to, visibility),
212 context <- make_context(in_reply_to),
213 cw <- data["spoiler_text"] || "",
214 sensitive <- data["sensitive"] || Enum.member?(tags, {"#nsfw", "nsfw"}),
215 full_payload <- String.trim(status <> cw),
216 :ok <- validate_character_limit(full_payload, attachments, limit),
217 object <-
218 make_note_data(
219 user.ap_id,
220 to,
221 context,
222 content_html,
223 attachments,
224 in_reply_to,
225 tags,
226 cw,
227 cc,
228 sensitive,
229 poll
230 ),
231 object <-
232 Map.put(
233 object,
234 "emoji",
235 Map.merge(Formatter.get_emoji_map(full_payload), poll_emoji)
236 ) do
237 res =
238 ActivityPub.create(
239 %{
240 to: to,
241 actor: user,
242 context: context,
243 object: object,
244 additional: %{"cc" => cc, "directMessage" => visibility == "direct"}
245 },
246 Pleroma.Web.ControllerHelper.truthy_param?(data["preview"]) || false
247 )
248
249 res
250 else
251 {:private_to_public, true} -> {:error, "The message visibility must be direct"}
252 {:error, _} = e -> e
253 e -> {:error, e}
254 end
255 end
256
257 # Updates the emojis for a user based on their profile
258 def update(user) do
259 user =
260 with emoji <- emoji_from_profile(user),
261 source_data <- (user.info.source_data || %{}) |> Map.put("tag", emoji),
262 info_cng <- User.Info.set_source_data(user.info, source_data),
263 change <- Ecto.Changeset.change(user) |> Ecto.Changeset.put_embed(:info, info_cng),
264 {:ok, user} <- User.update_and_set_cache(change) do
265 user
266 else
267 _e ->
268 user
269 end
270
271 ActivityPub.update(%{
272 local: true,
273 to: [user.follower_address],
274 cc: [],
275 actor: user.ap_id,
276 object: Pleroma.Web.ActivityPub.UserView.render("user.json", %{user: user})
277 })
278 end
279
280 def pin(id_or_ap_id, %{ap_id: user_ap_id} = user) do
281 with %Activity{
282 actor: ^user_ap_id,
283 data: %{
284 "type" => "Create"
285 },
286 object: %Object{
287 data: %{
288 "type" => "Note"
289 }
290 }
291 } = activity <- get_by_id_or_ap_id(id_or_ap_id),
292 true <- Visibility.is_public?(activity),
293 %{valid?: true} = info_changeset <-
294 User.Info.add_pinnned_activity(user.info, activity),
295 changeset <-
296 Ecto.Changeset.change(user) |> Ecto.Changeset.put_embed(:info, info_changeset),
297 {:ok, _user} <- User.update_and_set_cache(changeset) do
298 {:ok, activity}
299 else
300 %{errors: [pinned_activities: {err, _}]} ->
301 {:error, err}
302
303 _ ->
304 {:error, "Could not pin"}
305 end
306 end
307
308 def unpin(id_or_ap_id, user) do
309 with %Activity{} = activity <- get_by_id_or_ap_id(id_or_ap_id),
310 %{valid?: true} = info_changeset <-
311 User.Info.remove_pinnned_activity(user.info, activity),
312 changeset <-
313 Ecto.Changeset.change(user) |> Ecto.Changeset.put_embed(:info, info_changeset),
314 {:ok, _user} <- User.update_and_set_cache(changeset) do
315 {:ok, activity}
316 else
317 %{errors: [pinned_activities: {err, _}]} ->
318 {:error, err}
319
320 _ ->
321 {:error, "Could not unpin"}
322 end
323 end
324
325 def add_mute(user, activity) do
326 with {:ok, _} <- ThreadMute.add_mute(user.id, activity.data["context"]) do
327 {:ok, activity}
328 else
329 {:error, _} -> {:error, "conversation is already muted"}
330 end
331 end
332
333 def remove_mute(user, activity) do
334 ThreadMute.remove_mute(user.id, activity.data["context"])
335 {:ok, activity}
336 end
337
338 def thread_muted?(%{id: nil} = _user, _activity), do: false
339
340 def thread_muted?(user, activity) do
341 with [] <- ThreadMute.check_muted(user.id, activity.data["context"]) do
342 false
343 else
344 _ -> true
345 end
346 end
347
348 def bookmarked?(user, activity) do
349 with %Bookmark{} <- Bookmark.get(user.id, activity.id) do
350 true
351 else
352 _ ->
353 false
354 end
355 end
356
357 def report(user, data) do
358 with {:account_id, %{"account_id" => account_id}} <- {:account_id, data},
359 {:account, %User{} = account} <- {:account, User.get_cached_by_id(account_id)},
360 {:ok, {content_html, _, _}} <- make_report_content_html(data["comment"]),
361 {:ok, statuses} <- get_report_statuses(account, data),
362 {:ok, activity} <-
363 ActivityPub.flag(%{
364 context: Utils.generate_context_id(),
365 actor: user,
366 account: account,
367 statuses: statuses,
368 content: content_html,
369 forward: data["forward"] || false
370 }) do
371 {:ok, activity}
372 else
373 {:error, err} -> {:error, err}
374 {:account_id, %{}} -> {:error, "Valid `account_id` required"}
375 {:account, nil} -> {:error, "Account not found"}
376 end
377 end
378
379 def update_report_state(activity_id, state) do
380 with %Activity{} = activity <- Activity.get_by_id(activity_id),
381 {:ok, activity} <- Utils.update_report_state(activity, state) do
382 {:ok, activity}
383 else
384 nil ->
385 {:error, :not_found}
386
387 {:error, reason} ->
388 {:error, reason}
389
390 _ ->
391 {:error, "Could not update state"}
392 end
393 end
394
395 def update_activity_scope(activity_id, opts \\ %{}) do
396 with %Activity{} = activity <- Activity.get_by_id_with_object(activity_id),
397 {:ok, activity} <- toggle_sensitive(activity, opts),
398 {:ok, activity} <- set_visibility(activity, opts) do
399 {:ok, activity}
400 else
401 nil ->
402 {:error, :not_found}
403
404 {:error, reason} ->
405 {:error, reason}
406 end
407 end
408
409 defp toggle_sensitive(activity, %{"sensitive" => sensitive}) when sensitive in ~w(true false) do
410 toggle_sensitive(activity, %{"sensitive" => String.to_existing_atom(sensitive)})
411 end
412
413 defp toggle_sensitive(%Activity{object: object} = activity, %{"sensitive" => sensitive})
414 when is_boolean(sensitive) do
415 new_data = Map.put(object.data, "sensitive", sensitive)
416
417 {:ok, object} =
418 object
419 |> Object.change(%{data: new_data})
420 |> Object.update_and_set_cache()
421
422 {:ok, Map.put(activity, :object, object)}
423 end
424
425 defp toggle_sensitive(activity, _), do: {:ok, activity}
426
427 defp set_visibility(activity, %{"visibility" => visibility}) do
428 Utils.update_activity_visibility(activity, visibility)
429 end
430
431 defp set_visibility(activity, _), do: {:ok, activity}
432
433 def hide_reblogs(user, muted) do
434 ap_id = muted.ap_id
435
436 if ap_id not in user.info.muted_reblogs do
437 info_changeset = User.Info.add_reblog_mute(user.info, ap_id)
438 changeset = Ecto.Changeset.change(user) |> Ecto.Changeset.put_embed(:info, info_changeset)
439 User.update_and_set_cache(changeset)
440 end
441 end
442
443 def show_reblogs(user, muted) do
444 ap_id = muted.ap_id
445
446 if ap_id in user.info.muted_reblogs do
447 info_changeset = User.Info.remove_reblog_mute(user.info, ap_id)
448 changeset = Ecto.Changeset.change(user) |> Ecto.Changeset.put_embed(:info, info_changeset)
449 User.update_and_set_cache(changeset)
450 end
451 end
452 end