1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2019 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
5 defmodule Pleroma.Web.CommonAPI do
7 alias Pleroma.ActivityExpiration
8 alias Pleroma.Conversation.Participation
9 alias Pleroma.FollowingRelationship
11 alias Pleroma.ThreadMute
13 alias Pleroma.Web.ActivityPub.ActivityPub
14 alias Pleroma.Web.ActivityPub.Utils
15 alias Pleroma.Web.ActivityPub.Visibility
17 import Pleroma.Web.Gettext
18 import Pleroma.Web.CommonAPI.Utils
20 require Pleroma.Constants
22 def follow(follower, followed) do
23 timeout = Pleroma.Config.get([:activitypub, :follow_handshake_timeout])
25 with {:ok, follower} <- User.maybe_direct_follow(follower, followed),
26 {:ok, activity} <- ActivityPub.follow(follower, followed),
27 {:ok, follower, followed} <- User.wait_and_refresh(timeout, follower, followed) do
28 {:ok, follower, followed, activity}
32 def unfollow(follower, unfollowed) do
33 with {:ok, follower, _follow_activity} <- User.unfollow(follower, unfollowed),
34 {:ok, _activity} <- ActivityPub.unfollow(follower, unfollowed),
35 {:ok, _unfollowed} <- User.unsubscribe(follower, unfollowed) do
40 def accept_follow_request(follower, followed) do
41 with {:ok, follower} <- User.follow(follower, followed),
42 %Activity{} = follow_activity <- Utils.fetch_latest_follow(follower, followed),
43 {:ok, follow_activity} <- Utils.update_follow_state_for_all(follow_activity, "accept"),
44 {:ok, _relationship} <- FollowingRelationship.update(follower, followed, "accept"),
49 object: follow_activity.data["id"],
56 def reject_follow_request(follower, followed) do
57 with %Activity{} = follow_activity <- Utils.fetch_latest_follow(follower, followed),
58 {:ok, follow_activity} <- Utils.update_follow_state_for_all(follow_activity, "reject"),
59 {:ok, _relationship} <- FollowingRelationship.update(follower, followed, "reject"),
64 object: follow_activity.data["id"],
71 def delete(activity_id, user) do
72 with %Activity{data: %{"object" => _}} = activity <-
73 Activity.get_by_id_with_object(activity_id),
74 %Object{} = object <- Object.normalize(activity),
75 true <- User.superuser?(user) || user.ap_id == object.data["actor"],
76 {:ok, _} <- unpin(activity_id, user),
77 {:ok, delete} <- ActivityPub.delete(object) do
80 _ -> {:error, dgettext("errors", "Could not delete")}
84 def repeat(id_or_ap_id, user, params \\ %{}) do
85 with %Activity{} = activity <- get_by_id_or_ap_id(id_or_ap_id),
86 object <- Object.normalize(activity),
87 nil <- Utils.get_existing_announce(user.ap_id, object),
88 public <- public_announce?(object, params) do
89 ActivityPub.announce(user, object, nil, true, public)
91 _ -> {:error, dgettext("errors", "Could not repeat")}
95 def unrepeat(id_or_ap_id, user) do
96 with %Activity{} = activity <- get_by_id_or_ap_id(id_or_ap_id) do
97 object = Object.normalize(activity)
98 ActivityPub.unannounce(user, object)
100 _ -> {:error, dgettext("errors", "Could not unrepeat")}
104 def favorite(id_or_ap_id, user) do
105 with %Activity{} = activity <- get_by_id_or_ap_id(id_or_ap_id),
106 object <- Object.normalize(activity),
107 nil <- Utils.get_existing_like(user.ap_id, object) do
108 ActivityPub.like(user, object)
110 _ -> {:error, dgettext("errors", "Could not favorite")}
114 def unfavorite(id_or_ap_id, user) do
115 with %Activity{} = activity <- get_by_id_or_ap_id(id_or_ap_id) do
116 object = Object.normalize(activity)
117 ActivityPub.unlike(user, object)
119 _ -> {:error, dgettext("errors", "Could not unfavorite")}
123 def react_with_emoji(id, user, emoji) do
124 with %Activity{} = activity <- Activity.get_by_id(id),
125 object <- Object.normalize(activity) do
126 ActivityPub.react_with_emoji(user, object, emoji)
129 {:error, dgettext("errors", "Could not add reaction emoji")}
133 def unreact_with_emoji(id, user, emoji) do
134 with %Activity{} = reaction_activity <- Utils.get_latest_reaction(id, user, emoji) do
135 ActivityPub.unreact_with_emoji(user, reaction_activity.data["id"])
138 {:error, dgettext("errors", "Could not remove reaction emoji")}
142 def vote(user, %{data: %{"type" => "Question"}} = object, choices) do
143 with :ok <- validate_not_author(object, user),
144 :ok <- validate_existing_votes(user, object),
145 {:ok, options, choices} <- normalize_and_validate_choices(choices, object) do
147 Enum.map(choices, fn index ->
148 answer_data = make_answer_data(user, object, Enum.at(options, index)["name"])
151 ActivityPub.create(%{
152 to: answer_data["to"],
154 context: object.data["context"],
156 additional: %{"cc" => answer_data["cc"]}
162 object = Object.get_cached_by_ap_id(object.data["id"])
163 {:ok, answer_activities, object}
167 defp validate_not_author(%{data: %{"actor" => ap_id}}, %{ap_id: ap_id}),
168 do: {:error, dgettext("errors", "Poll's author can't vote")}
170 defp validate_not_author(_, _), do: :ok
172 defp validate_existing_votes(%{ap_id: ap_id}, object) do
173 if Utils.get_existing_votes(ap_id, object) == [] do
176 {:error, dgettext("errors", "Already voted")}
180 defp get_options_and_max_count(%{data: %{"anyOf" => any_of}}), do: {any_of, Enum.count(any_of)}
181 defp get_options_and_max_count(%{data: %{"oneOf" => one_of}}), do: {one_of, 1}
183 defp normalize_and_validate_choices(choices, object) do
184 choices = Enum.map(choices, fn i -> if is_binary(i), do: String.to_integer(i), else: i end)
185 {options, max_count} = get_options_and_max_count(object)
186 count = Enum.count(options)
188 with {_, true} <- {:valid_choice, Enum.all?(choices, &(&1 < count))},
189 {_, true} <- {:count_check, Enum.count(choices) <= max_count} do
190 {:ok, options, choices}
192 {:valid_choice, _} -> {:error, dgettext("errors", "Invalid indices")}
193 {:count_check, _} -> {:error, dgettext("errors", "Too many choices")}
197 def public_announce?(_, %{"visibility" => visibility})
198 when visibility in ~w{public unlisted private direct},
199 do: visibility in ~w(public unlisted)
201 def public_announce?(object, _) do
202 Visibility.is_public?(object)
205 def get_visibility(_, _, %Participation{}), do: {"direct", "direct"}
207 def get_visibility(%{"visibility" => visibility}, in_reply_to, _)
208 when visibility in ~w{public unlisted private direct},
209 do: {visibility, get_replied_to_visibility(in_reply_to)}
211 def get_visibility(%{"visibility" => "list:" <> list_id}, in_reply_to, _) do
212 visibility = {:list, String.to_integer(list_id)}
213 {visibility, get_replied_to_visibility(in_reply_to)}
216 def get_visibility(_, in_reply_to, _) when not is_nil(in_reply_to) do
217 visibility = get_replied_to_visibility(in_reply_to)
218 {visibility, visibility}
221 def get_visibility(_, in_reply_to, _), do: {"public", get_replied_to_visibility(in_reply_to)}
223 def get_replied_to_visibility(nil), do: nil
225 def get_replied_to_visibility(activity) do
226 with %Object{} = object <- Object.normalize(activity) do
227 Visibility.get_visibility(object)
231 def check_expiry_date({:ok, nil} = res), do: res
233 def check_expiry_date({:ok, in_seconds}) do
234 expiry = NaiveDateTime.utc_now() |> NaiveDateTime.add(in_seconds)
236 if ActivityExpiration.expires_late_enough?(expiry) do
239 {:error, "Expiry date is too soon"}
243 def check_expiry_date(expiry_str) do
244 Ecto.Type.cast(:integer, expiry_str)
245 |> check_expiry_date()
248 def listen(user, %{"title" => _} = data) do
249 with visibility <- data["visibility"] || "public",
250 {to, cc} <- get_to_and_cc(user, [], nil, visibility, nil),
252 Map.take(data, ["album", "artist", "title", "length"])
253 |> Map.put("type", "Audio")
256 |> Map.put("actor", user.ap_id),
258 ActivityPub.listen(%{
262 context: Utils.generate_context_id(),
263 additional: %{"cc" => cc}
269 def post(user, %{"status" => _} = data) do
270 with {:ok, draft} <- Pleroma.Web.CommonAPI.ActivityDraft.create(user, data) do
272 |> ActivityPub.create(draft.preview?)
273 |> maybe_create_activity_expiration(draft.expires_at)
277 defp maybe_create_activity_expiration({:ok, activity}, %NaiveDateTime{} = expires_at) do
278 with {:ok, _} <- ActivityExpiration.create(activity, expires_at) do
283 defp maybe_create_activity_expiration(result, _), do: result
285 # Updates the emojis for a user based on their profile
287 emoji = emoji_from_profile(user)
288 source_data = Map.put(user.source_data, "tag", emoji)
291 case User.update_source_data(user, source_data) do
296 ActivityPub.update(%{
298 to: [Pleroma.Constants.as_public(), user.follower_address],
301 object: Pleroma.Web.ActivityPub.UserView.render("user.json", %{user: user})
305 def pin(id_or_ap_id, %{ap_id: user_ap_id} = user) do
308 data: %{"type" => "Create"},
309 object: %Object{data: %{"type" => "Note"}}
310 } = activity <- get_by_id_or_ap_id(id_or_ap_id),
311 true <- Visibility.is_public?(activity),
312 {:ok, _user} <- User.add_pinnned_activity(user, activity) do
315 {:error, %{errors: [pinned_activities: {err, _}]}} -> {:error, err}
316 _ -> {:error, dgettext("errors", "Could not pin")}
320 def unpin(id_or_ap_id, user) do
321 with %Activity{} = activity <- get_by_id_or_ap_id(id_or_ap_id),
322 {:ok, _user} <- User.remove_pinnned_activity(user, activity) do
325 {:error, %{errors: [pinned_activities: {err, _}]}} -> {:error, err}
326 _ -> {:error, dgettext("errors", "Could not unpin")}
330 def add_mute(user, activity) do
331 with {:ok, _} <- ThreadMute.add_mute(user.id, activity.data["context"]) do
334 {:error, _} -> {:error, dgettext("errors", "conversation is already muted")}
338 def remove_mute(user, activity) do
339 ThreadMute.remove_mute(user.id, activity.data["context"])
343 def thread_muted?(%{id: nil} = _user, _activity), do: false
345 def thread_muted?(user, activity) do
346 ThreadMute.check_muted(user.id, activity.data["context"]) != []
349 def report(user, %{"account_id" => account_id} = data) do
350 with {:ok, account} <- get_reported_account(account_id),
351 {:ok, {content_html, _, _}} <- make_report_content_html(data["comment"]),
352 {:ok, statuses} <- get_report_statuses(account, data) do
354 context: Utils.generate_context_id(),
358 content: content_html,
359 forward: data["forward"] || false
364 def report(_user, _params), do: {:error, dgettext("errors", "Valid `account_id` required")}
366 defp get_reported_account(account_id) do
367 case User.get_cached_by_id(account_id) do
368 %User{} = account -> {:ok, account}
369 _ -> {:error, dgettext("errors", "Account not found")}
373 def update_report_state(activity_id, state) do
374 with %Activity{} = activity <- Activity.get_by_id(activity_id) do
375 Utils.update_report_state(activity, state)
377 nil -> {:error, :not_found}
378 _ -> {:error, dgettext("errors", "Could not update state")}
382 def update_activity_scope(activity_id, opts \\ %{}) do
383 with %Activity{} = activity <- Activity.get_by_id_with_object(activity_id),
384 {:ok, activity} <- toggle_sensitive(activity, opts) do
385 set_visibility(activity, opts)
387 nil -> {:error, :not_found}
388 {:error, reason} -> {:error, reason}
392 defp toggle_sensitive(activity, %{"sensitive" => sensitive}) when sensitive in ~w(true false) do
393 toggle_sensitive(activity, %{"sensitive" => String.to_existing_atom(sensitive)})
396 defp toggle_sensitive(%Activity{object: object} = activity, %{"sensitive" => sensitive})
397 when is_boolean(sensitive) do
398 new_data = Map.put(object.data, "sensitive", sensitive)
402 |> Object.change(%{data: new_data})
403 |> Object.update_and_set_cache()
405 {:ok, Map.put(activity, :object, object)}
408 defp toggle_sensitive(activity, _), do: {:ok, activity}
410 defp set_visibility(activity, %{"visibility" => visibility}) do
411 Utils.update_activity_visibility(activity, visibility)
414 defp set_visibility(activity, _), do: {:ok, activity}
416 def hide_reblogs(user, %{ap_id: ap_id} = _muted) do
417 if ap_id not in user.muted_reblogs do
418 User.add_reblog_mute(user, ap_id)
422 def show_reblogs(user, %{ap_id: ap_id} = _muted) do
423 if ap_id in user.muted_reblogs do
424 User.remove_reblog_mute(user, ap_id)