Merge branch 'bugfix/1395-email-activation' into 'develop'
[akkoma] / lib / pleroma / web / controller_helper.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.ControllerHelper do
6 use Pleroma.Web, :controller
7
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
12
13 def json_response(conn, status, json) do
14 conn
15 |> put_status(status)
16 |> json(json)
17 end
18
19 @spec fetch_integer_param(map(), String.t(), integer() | nil) :: integer() | nil
20 def fetch_integer_param(params, name, default \\ nil) do
21 params
22 |> Map.get(name, default)
23 |> param_to_integer(default)
24 end
25
26 defp param_to_integer(val, _) when is_integer(val), do: val
27
28 defp param_to_integer(val, default) when is_binary(val) do
29 case Integer.parse(val) do
30 {res, _} -> res
31 _ -> default
32 end
33 end
34
35 defp param_to_integer(_, default), do: default
36
37 def add_link_headers(conn, activities, extra_params \\ %{}) do
38 case List.last(activities) do
39 %{id: max_id} ->
40 params =
41 conn.params
42 |> Map.drop(Map.keys(conn.path_params))
43 |> Map.drop(["since_id", "max_id", "min_id"])
44 |> Map.merge(extra_params)
45
46 limit =
47 params
48 |> Map.get("limit", "20")
49 |> String.to_integer()
50
51 min_id =
52 if length(activities) <= limit do
53 activities
54 |> List.first()
55 |> Map.get(:id)
56 else
57 activities
58 |> Enum.at(limit * -1)
59 |> Map.get(:id)
60 end
61
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}))
64
65 put_resp_header(conn, "link", "<#{next_url}>; rel=\"next\", <#{prev_url}>; rel=\"prev\"")
66
67 _ ->
68 conn
69 end
70 end
71
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()
76 end
77 end
78
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")
83 res -> res
84 end
85 end
86
87 def try_render(conn, _, _) do
88 render_error(conn, :not_implemented, "Can't display this activity")
89 end
90 end