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.ControllerHelper do
6 use Pleroma.Web, :controller
8 # As in MastoAPI, per https://api.rubyonrails.org/classes/ActiveModel/Type/Boolean.html
9 @falsy_param_values [false, 0, "0", "f", "F", "false", "False", "FALSE", "off", "OFF"]
10 def truthy_param?(blank_value) when blank_value in [nil, ""], do: nil
11 def truthy_param?(value), do: value not in @falsy_param_values
13 def json_response(conn, status, json) do
19 @spec fetch_integer_param(map(), String.t(), integer() | nil) :: integer() | nil
20 def fetch_integer_param(params, name, default \\ nil) do
22 |> Map.get(name, default)
23 |> param_to_integer(default)
26 defp param_to_integer(val, _) when is_integer(val), do: val
28 defp param_to_integer(val, default) when is_binary(val) do
29 case Integer.parse(val) do
35 defp param_to_integer(_, default), do: default
37 def add_link_headers(conn, activities, extra_params \\ %{}) do
38 case List.last(activities) do
42 |> Map.drop(Map.keys(conn.path_params))
43 |> Map.drop(["since_id", "max_id", "min_id"])
44 |> Map.merge(extra_params)
48 |> Map.get("limit", "20")
49 |> String.to_integer()
52 if length(activities) <= limit do
58 |> Enum.at(limit * -1)
62 next_url = current_url(conn, Map.merge(params, %{max_id: max_id}))
63 prev_url = current_url(conn, Map.merge(params, %{min_id: min_id}))
65 put_resp_header(conn, "link", "<#{next_url}>; rel=\"next\", <#{prev_url}>; rel=\"prev\"")
72 def assign_account_by_id(%{params: %{"id" => id}} = conn, _) do
73 case Pleroma.User.get_cached_by_id(id) do
74 %Pleroma.User{} = account -> assign(conn, :account, account)
75 nil -> Pleroma.Web.MastodonAPI.FallbackController.call(conn, {:error, :not_found}) |> halt()
79 def try_render(conn, target, params)
80 when is_binary(target) do
81 case render(conn, target, params) do
82 nil -> render_error(conn, :not_implemented, "Can't display this activity")
87 def try_render(conn, _, _) do
88 render_error(conn, :not_implemented, "Can't display this activity")