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