1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
5 defmodule Pleroma.Web.ControllerHelper do
6 use Pleroma.Web, :controller
10 # As in Mastodon API, per https://api.rubyonrails.org/classes/ActiveModel/Type/Boolean.html
11 @falsy_param_values [false, 0, "0", "f", "F", "false", "False", "FALSE", "off", "OFF"]
13 def explicitly_falsy_param?(value), do: value in @falsy_param_values
15 # Note: `nil` and `""` are considered falsy values in Pleroma
16 def falsy_param?(value),
17 do: explicitly_falsy_param?(value) or value in [nil, ""]
19 def truthy_param?(value), do: not falsy_param?(value)
21 def json_response(conn, status, json) do
27 @spec fetch_integer_param(map(), String.t(), integer() | nil) :: integer() | nil
28 def fetch_integer_param(params, name, default \\ nil) do
30 |> Map.get(name, default)
31 |> param_to_integer(default)
34 defp param_to_integer(val, _) when is_integer(val), do: val
36 defp param_to_integer(val, default) when is_binary(val) do
37 case Integer.parse(val) do
43 defp param_to_integer(_, default), do: default
45 def add_link_headers(conn, activities, extra_params \\ %{})
47 def add_link_headers(%{assigns: %{skip_link_headers: true}} = conn, _activities, _extra_params),
50 def add_link_headers(conn, activities, extra_params) do
51 case List.last(activities) do
55 |> Map.drop(Map.keys(conn.path_params))
56 |> Map.drop(["since_id", "max_id", "min_id"])
57 |> Map.merge(extra_params)
61 |> Map.get("limit", "20")
62 |> String.to_integer()
65 if length(activities) <= limit do
71 |> Enum.at(limit * -1)
75 next_url = current_url(conn, Map.merge(params, %{max_id: max_id}))
76 prev_url = current_url(conn, Map.merge(params, %{min_id: min_id}))
78 put_resp_header(conn, "link", "<#{next_url}>; rel=\"next\", <#{prev_url}>; rel=\"prev\"")
85 def assign_account_by_id(%{params: %{"id" => id}} = conn, _) do
86 case Pleroma.User.get_cached_by_id(id) do
87 %Pleroma.User{} = account -> assign(conn, :account, account)
88 nil -> Pleroma.Web.MastodonAPI.FallbackController.call(conn, {:error, :not_found}) |> halt()
92 def try_render(conn, target, params) when is_binary(target) do
93 case render(conn, target, params) do
94 nil -> render_error(conn, :not_implemented, "Can't display this activity")
99 def try_render(conn, _, _) do
100 render_error(conn, :not_implemented, "Can't display this activity")
103 @spec put_if_exist(map(), atom() | String.t(), any) :: map()
104 def put_if_exist(map, _key, nil), do: map
106 def put_if_exist(map, key, value), do: Map.put(map, key, value)
108 @doc "Whether to skip rendering `[:account][:pleroma][:relationship]`for statuses/notifications"
109 def skip_relationships?(params) do
110 if Config.get([:extensions, :output_relationships_in_statuses_by_default]) do
113 # BREAKING: older PleromaFE versions do not send this param but _do_ expect relationships.
114 not truthy_param?(params["with_relationships"])